text stringlengths 8 267k | meta dict |
|---|---|
Q: DotNetOpenAuth Claimed Identifier from Facebook is never the same I'm using DotNetOpenAuth v3.5.0.10357 and each time a user authenticates against Facebook I get a different claimed identifier back. The token looks to be encrypted so I assume DNOA is somehow encrypting the token along with the expiry. Can anyone confirm this? Or am I using it wrong:
public ActionResult FacebookLogOn(string returnUrl)
{
IAuthorizationState authorization = m_FacebookClient.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
return new FacebookAuthenticationResult(m_FacebookClient, returnUrl);
}
else
{
// TODO: can we check response status codes to see if request was successful?
var baseTokenUrl = "https://graph.facebook.com/me?access_token=";
var requestUrl = String.Format("{0}{1}", baseTokenUrl, Uri.EscapeDataString(authorization.AccessToken));
var claimedIdentifier = String.Format("{0}{1}", baseTokenUrl, authorization.AccessToken.Split('|')[0]);
var request = WebRequest.Create(requestUrl);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
var token = RelyingPartyLogic.User.ProcessUserLogin(graph, claimedIdentifier);
this.FormsAuth.SignIn(token.ClaimedIdentifier, false);
}
}
return RedirectAfterLogin(returnUrl);
}
}
Here's the code for FacebookAuthenticationResult:
public class FacebookAuthenticationResult : ActionResult
{
private FacebookClient m_Client;
private OutgoingWebResponse m_Response;
public FacebookAuthenticationResult(FacebookClient client, string returnUrl)
{
m_Client = client;
var authorizationState = new AuthorizationState(new String[] { "email" });
if (!String.IsNullOrEmpty(returnUrl))
{
var currentUri = HttpContext.Current.Request.Url;
var path = HttpUtility.UrlDecode(returnUrl);
authorizationState.Callback = new Uri(String.Format("{0}?returnUrl={1}", currentUri.AbsoluteUri, path));
}
m_Response = m_Client.PrepareRequestUserAuthorization(authorizationState);
}
public FacebookAuthenticationResult(FacebookClient client) : this(client, null) { }
public override void ExecuteResult(ControllerContext context)
{
m_Response.Send();
}
}
Also, I am using the RelyingPartyLogic project included in the DNOA samples, but I added an overload for ProcessUserLogin that's specific to facebook:
public static AuthenticationToken ProcessUserLogin(FacebookGraph claim, string claimedIdentifier)
{
string name = claim.Name;
string email = claim.Email;
if (String.IsNullOrEmpty(name))
name = String.Format("{0} {1}", claim.FirstName, claim.LastName).TrimEnd();
return ProcessUserLogin(claimedIdentifier, "http://facebook.com", email, name, claim.Verified);
}
It looks as though FacebookClient inherits from WebServerClient but I looked for the source on GitHub and I don't see a branch or a tag related (or at least not labeled) with the corresponding v3.5 version.
A: Facebook does not support OpenID. Claimed Identifier is an OpenID term. Facebook uses OAuth 2.0, so you're mixing up OpenID and OAuth.
Facebook sends a different access token every time, which is normal for the OAuth protocol. You have to use the access token to query Facebook for the user id that is consistent on every visit.
A: I think you need to add the offline_access permission in the token request as well, see https://developers.facebook.com/docs/reference/api/permissions/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to have a "no image found" icon if the image used in the function returns an error? In my application I use timthumb for resizing images. Those images are not controlled by me because I get them from RSS feeds. Sometimes the image are not shown in my page. When I examine the entire link with the timthumb I get this
Warning: imagecreatefromjpeg(http://www.domain.com/image.jpg)
[function.imagecreatefromjpeg]: failed to open stream: HTTP request
failed! HTTP/1.1 404 Not Found in /timthumb.php on line 193 Unable to
open image : http://www.domain.com/image.jpg
So, I am looking for a way to know when an image returns an error, so that I will not display it on page ( the red X icon).
From my RSS feeds, I use regex to get the first image
if (thumb[0]) { show the image using timthumb }
else { show a no-image icon }
but the example above falls into the "show the image using timthumb".
This is a paste from my code
http://codepad.org/7aFXE8ZY
Thank you.
A: You could use a function which fetch headers for the given url using curl and check for the HTTP status code and for the image/* content type.
If your url refer to an image the following function will return true, otherwise it returns false.
Notice the curl_setopt($ch, CURLOPT_NOBODY, 1); line which tells curl to fetch only the headers for the given page and not the whole content. In this way you can save bandwidth when checking for image existence.
<?php
function image_exist($url, $check_mime_type = true) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);
if (!preg_match('/^HTTP\/1.1 200 OK/i', $result)) {
// status != 200, handle redirects, not found, forbidden and so on
return false;
}
if ($check_mime_type && !preg_match('/^Content-Type:\\s+image\/.*$/im', $result)) {
// mime != image/*
return false;
}
return true;
}
$url = 'http://static.php.net/www.php.net/images/php.gif';
var_dump(image_exist($url)); // return true since it's an image
$bogus_url = 'http://www.google.com/foobar';
var_dump(image_exist($bogus_url)); // return false since page doesn't exist
$text_url = 'http://stackoverflow.com/';
var_dump(image_exist($text_url)); // return false since page exists but it's a text page
By using this code you could avoid the @ error suppression operator, which should not be used and fetch the actual image only when it exists.
@ is bad since it will suppress even fatal error, so your script can die with a blank page and you won't know why because it will set error_reporting to 0 and the restore it to its previous value, see the warning here.
Furthermore it slows down your code as reported in this comment and following.
A: If imagecreatefromjpeg steps over an error (like the file not being readable), it will return false, and, depending on the server configuration, output an error message. Outputting an error message (or anything) makes php send the request headers automatically. After headers have been sent, you can't take them back to indicate you're actually sending an image instead of a HTML document.
Therefore, you may want to suppress error output, like this:
set_error_handler(function($en, $es) {}, E_WARNING);
$im = imagecreatefromjpeg($url);
restore_error_handler();
if ($im === false) {
header('Content-Type: image/jpeg');
readfile('static/red-x-icon.jpeg');
exit();
}
// Continue processing $im, eventually send headers and the image itself
A: Create an error handler using set_error_handler(), and if an error is thrown just return a blank image and possibly log the error elsewhere.
A: Why not see if you can open the image file first?
function fileExists($path){
return (@fopen($path,"r")==true);
}
$img = 'no_image.jpg';
if (fileExists(thumb[0])) {
$img = thumb[0];
}
Also, are you checking to make sure you are not passing a non-jpeg (PNG, etc) image to imagecreatefromjpeg()?
A: This can be the problem when the page does not allow to download images when user agent is not set. Try to set one before running imagecreatefromjpeg. For instance:
ini_set('user_agent', 'Mozilla/5.0 (Windows NT 5.1; U; rv:5.0) Gecko/20100101 Firefox/5.0');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: problem in appending two strings I am trying to append two strings. But it is generating an error that -[CFString stringByAppendingString:]: message sent to deallocated instance 0x5db1310 what does this mean? I am unable to resolve this error. Please tell me where I am doing wrong.
Thank you very much.
- (void)updatestatus:(id)sender event:(UIEvent *)event {
NSIndexPath *indexPath = [alarmtimetable indexPathForRowAtPoint:[[[event touchesForView:sender] anyObject] locationInView:alarmtimetable]];
timeselect = [rangetime objectAtIndex:indexPath.row];
datetimeselected = [todaydate stringByAppendingString:timeselect];
NSLog(@"datetimeselected:%@",datetimeselected); [self onButtonClick:(id)sender];
}
A: The message means that the string you are trying to append to no longer exists. Most likely it was not retained or was over released. Run the Xcode Analyzer, it may very well pinpoint the error.
A: Try doing this instead....
.... [CFString stringByAppendingString:[NSString stringWithFormat:@"%@", yourString]];
But for the reasons stated before me, it looks like the string has been deallocated before it gets to that line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Request permissions to fetch user data AND publish to Timeline in same dialog Has anyone figured this out yet?
The question with more fancy details:
You've got a Facebook application that on one side fetches and analyzes the user's data, and on the other side posts fancy posts to the user's timeline using the new OG features launched yesterday. When the user begins using your application, is it required to first show the standard dialog requesting permissions to fetch and post data to Facebook, and then in a separate dialog request permission to publish to the user's timeline? To be even more specific with my question, is it possible to combine these two dialogs into a single request?
Thanks in advance!
Edit: Guess it was easier than I first thought. Here's the new Auth dialog for all people as blind as me: https://developers.facebook.com/docs/beta/authentication/
A: As you discovered, the new Open Auth dialogue can do multiple permissions although you should review how it handles "extended permissions" beyond email and publish_actions.
Be certain to review your application settings and specifically the auth and advanced tabs as there are new options to fill out for explaining additional permissions as well as an option to enable the new dialogue before the system-wide rollout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AS3: invalid Bitmap I am trying to run the following function where car is a movieclip:
public function cacheCar():void
{
car.bounded = new Rectangle(car.getBounds(car));
var carOffset:Matrix = car.transform.matrix;
carOffset.tx = car.x - car.bounded.x;
carOffset.ty = car.y - car.bounded.y;
car.bmpData = new BitmapData(car.bounded.width,car.bounded.height,true,0);
car.bmpData.draw(car, carOffset);
}
but I am recieving the following error:
ArgumentError: Error #2015: Invalid BitmapData. at
flash.display::BitmapData/ctor() at flash.display::BitmapData() at
com.George.MegaAmazingApp.Components::Road/cacheCar()
[C:\path\to\class\called\Road.as:55]
Line 55 is: car.bmpData = new BitmapData(car.bounded.width,car.bounded.height,true,0);
Can anyone see why this is?
A: Either width or height for the BitmapData is returning 0. Try getting the bounds using the stage: car.bounded = car.getBounds( car.stage );
On a side note, getBounds() returns a Rectangle so you don't need to create a new one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ListView Border Color Is it possible to create a 1px width, colored border around a ListView?
I tried the following coding:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#BFFFFFFF" android:endColor="#BFFFFFFF" />
<corners android:bottomRightRadius="10dp" android:radius="10dp"
android:bottomLeftRadius="10dp" android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
</shape>
So... does anyone know how I can make a border line and set its color?
PS: I really searched for this issue in another posts and no success, that's why I created this one.
Thanks!
A: Yes, it is possible. Just add the <stroke> tag as shown below
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#BFFFFFFF" android:endColor="#BFFFFFFF" />
<stroke
android:width="1dp"
android:color="#d8d8d8" />
<corners android:bottomRightRadius="10dp" android:radius="10dp"
android:bottomLeftRadius="10dp" android:topLeftRadius="10dp"
android:topRightRadius="10dp" />
</shape>
Please use 1dp instead of 1px and you can replace any border color as you wish for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting a "Page X of Y" message in Wordpress' single.php I'm wondering how i can make i.e 'Page 2 of 13' appear on the bottom of Wordpress' single.php page.
Let's say a user clicks a post title on the front page, and when it's opened with single.php the user sees what page he's on (and also how many are total). So if he chooses to view the third post it would say 'Post 3 of 13'. If he then clicks Next or Previous, he gets 'Post 2 of 13', or 'Post 4 of 13' and so on.
I've managed to do this on the front page, but can't seem to get it working properly on single.php
The reason i want this is to have the message between a prev and next arrow.
A: Have you tried
posts_nav_link();
previous_post();
next_post();
Refer here
A: Here's an easy way that will work in your sidebar:
<?php
$page_id = $post->ID;
$page_parent = $post->post_parent;
if ($page_parent) { // there's a parent page, get the children
$args = array(
'parent' => $page_parent,
'child_of' => $page_parent,
'hierarchical' => 0,
'sort_column' => 'menu_order'
);
}
else { // no parent, so just get top level pages
$args = array(
'parent' => 0,
'sort_column' => 'menu_order'
);
}
$my_pages = get_pages($args);
while ($page = current($my_pages)) { // find this page's position in the page array
if ($page->ID == $page_id) {
echo key($my_pages) + 1;
}
next($my_pages);
}
$result = count($my_pages);
echo " of " . $result;
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to place reference lines ['abline()'] in background? This is perhaps very basic, but I just can't seem to find a working solution:
I'm building a boxplot with custom axes using the 'boxplot()' function in R, and I'd like to have thin grey lines for reference across the y-tick intervals, something like:
boxplot("MyDataTable", ylim=ylim, axes=FALSE, col=312, notch=TRUE)
axis(2, lwd=1.5, at=ytk, las=2, tck=-0.02, cex.axis=0.75, font=2)
abline(h=yln, lty=1.5, lwd=0.5, col=336)
When this prints out (to pdf, in my case), the thin grey lines overlap the boxplot's boxes and whiskers.
How can I have the same plot with the graphed boxes and whiskers being in the foreground...?
A: One way is just to repeat the boxplot call by adding it to the existing plot, so the horizontal lines become background.
For example:
boxplot(count ~ spray, data = InsectSprays, col = "lightgray", main = "plot title")
abline(h = 1:25, lty=1.5, lwd=0.5, col=336)
boxplot(count ~ spray, data = InsectSprays, col = "lightgray", add = TRUE)
Since you also need interaction with the axis ticks, you might find something similar works there as well but your code is not reproducible, so we can only guess at the actual effect you want to see.
Simple boxplot, overplotted on horizontal lines http://beta1.opencpu.org/R/call/store:tmp/a2884b758f76d5c808e0f9751c35ad74/png?main=%22plot%20title%22
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send and receive data between emulators? I want to send data (text data) from 1 emulator to other emulator. 1 emulator act as server and other as client. where i can get client & server side code for this, plz help me .
A: Assuming both devices are connected to the same WIFI network, you could use sockets:
http://www.oracle.com/technetwork/java/socket-140484.html
A: To get started, the dev site has some guidelines for how to interconnect two emulator devices. I largely suspect that you'll be setting up a small mini server on one of your devices and the client device will be sending POST messages. Here is a good android server app.
I don't know if you're actually going to be using the emulator or real devices but these two links should help you get started on at least developing the app and testing it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Task Killer Apps vs. SupportFragmentManager Backstack I face the following very annoying problem:
I'm using the Google Compatibility Library in order to future-proof my apps.
Now... I'm keeping track of my backstack:
1) Launch App.
2) User Interaction A -> Fragment gets added to UI/ Back Stack.
--- Backstack Size: 1 ---
3) User "backgrounds" the app.
4) User kills the App with a Taskkiller / or the app gets killed by the android system
5) Launch app again. Full Restart of the application (Application.onCreate()) presented to the User.
6) User Interaction A -> Fragment gets added to UI/ Back Stack.
--- Backstack Size: 2 ---
At this point I would want to have a backstack size of 1.
If the user presses back now, the app takes him back to some former state, which doesn't make sense anymore, because the app presented a fresh start.
Any Idea on How to do this??
Thx
A: Although your application has indeed been killed, there is not technically a 'full restart' when you try to launch it again. This is certainly not the way Android would want you to consider the situation.
When you background your app, Android will save the state of the fragments that have been added to the fragment manager (as well as the state of which activities are open, and their view state). When you relaunch your app after getting killed, Android will give you back all of this state and so you should be able to resume from exactly where you left off. This means you should consider that 'User Interaction A' has already happened and really you are at step 2) again. As you have noticed, the backstack is preserved; this is because the fragment transactions you have performed are also preserved.
The problem is of course, that we don't always write our apps in a way to match this behaviour. If your app presents a 'fresh start' after being killed whilst backgrounded, then arguably it is not really following the Android approach (assuming there is some user state worth saving).
I think you should try as best you can to resume as at step 2); it will likely be (marginally!) easier than trying to prevent Android from saving this state.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Syntax issue with case expression inside scalar function Having trouble creating a scalar function inside MS SQL 2005. Any suggestions would be appreciated. The title1_type field should be set according to the case statement. The sku is passed which should determine the type base on the case statement.
create FUNCTION [dbo].[gettitle1_type] (@sku varchar(50))
RETURNS varchar(50) AS
BEGIN
DECLARE @title1_type varchar(50)
DECLARE @title1 varchar(50)
select @title1_type = case @title1
when @title1 like '%SMALL%' then 'size'
when @title1 like '%large%' then 'size'
when @title1 like '%pink%' then 'color'
when @title1 like '%red%' then 'color'
when @title1 like '%brunette%' then 'color'
else ''
END;
where sku = @sku
RETURN isnull(@title1_type,'')
A: You need to
*
*Get rid of the semi colon after END; This is not the end of the statement. Optionally you could put one after where sku = @sku though.
*Don't use case @title1, use Case instead. You are mingling the 2 forms of the CASE expression.
*Add a final END to finish the function definition.
*Either remove the WHERE or add a FROM
*(Optional and dependant on 4) It is best practice to put WITH SCHEMABINDING on scalar UDFs that do not do data access. This can help performance in some cases.
Giving the below
CREATE FUNCTION [dbo].[gettitle1_type] (@sku VARCHAR(50))
RETURNS VARCHAR(50)
WITH SCHEMABINDING
AS
BEGIN
DECLARE @title1_type VARCHAR(50)
DECLARE @title1 VARCHAR(50) /*This is never assigned to ?!*/
SELECT @title1_type = CASE
WHEN @title1 LIKE '%SMALL%' THEN 'size'
WHEN @title1 LIKE '%large%' THEN 'size'
WHEN @title1 LIKE '%pink%' THEN 'color'
WHEN @title1 LIKE '%red%' THEN 'color'
WHEN @title1 LIKE '%brunette%' THEN 'color'
ELSE ''
END
/*
FROM xyz
WHERE sku = @sku;*/
RETURN ISNULL(@title1_type,'')
END
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Linking problem in dynamic library while mixing C C++ code I had a C dynamic library, due to some requirement change I have to do some refactoring.
I had following code in one c file.
__attribute__((noinline))
static void *find_document(...)
{
...
}
bool docuemnt_found(const char *name) {
...
find_document(...);
...
}
I separated the docuemnt_found() function in different cpp file. Now docuemnt_found() function cannot link to find_document() method?
I tried creating header for the c file and then include header using extern "C" but it did not work.
I want to keep find_document() inline. Is there anything missing here or something wrong?
A: The problem here is the declaration of the function as static - in C, this says that it should be available to other functions within the same compilation unit (.c file), but not to other functions outside the file. Removing static should solve the problem.
Incidentally, the second function is misspelled - it should be document_found, not docuemnt_found.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Redoing a try after catch in Java import java.util.Scanner;
public class Questioner {
Scanner scanner = new Scanner(System.in);
boolean condition;
int tempInt;
double tempDouble;
public Questioner()
{
condition = true;
}
public String stringInput(String text)
{
System.out.print(text);
return scanner.nextLine();
}
public int intInput(String text)
{
do
{
System.out.print(text);
try
{
tempInt = scanner.nextInt();
condition = false;
}
catch (java.util.InputMismatchException error)
{
System.out.println("Please use valid input.");
}
} while (condition == true);
return tempInt;
}
public double doubleInput(String text)
{
System.out.print(text);
try
{
return scanner.nextDouble();
}
catch (java.util.InputMismatchException error)
{
System.out.println("Please use valid input.");
return 0;
}
}
}
Right now, it loops infinitely on the catch after one error. How can I make it go back to the try after a catch? boolean condition is declared properly, no compilation errors or anything. The rest of the code in the class is kind of a mess as I'm waiting for an answer about the re-trying.
A: The documentation for java.util.Scanner states
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
So you'll retrieve indefinitely using this method. In the catch block you'll need to skip over the token.
A: As well as Jeff's answer, there's no indication that anything will ever set condition back to true after it's been set to false once. You could make it a local variable, or you could just return from the try block:
public int intInput(String text)
{
do
{
System.out.print(text);
try
{
return scanner.nextInt();
}
catch (java.util.InputMismatchException error)
{
System.out.println("Please use valid input.");
// Consume input here, appropriately...
}
} while (true);
}
Now the method doesn't affect any state other than the scanner, which is probably what you want - and (IMO) it's simpler as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: when clicking don't want to go to top of page
Possible Duplicate:
Href=“#” Don't Scroll
I have the following html in my code
<a href="#">link</a>
When i click on 'link', then my page goes automatically to top what is very normal as you all know. But i want that my page stays where it is when clicked on that link.
Somebody knows a good workaround for this?
PS: I can't change the html, it has to be a hyperlink
Thanks.
A: If you can edit the a tag, you can put :
<a href="#stay_here" name="stay_here">link</a>
A: You can use like this <a href="javascript:;">link</a>
A: First of all, you can change the html if you apply cursor:pointer (from CSS) on it.
For your problem, you need event.returnValue = false; in ie and event.preventDefault(); for the browsers.
See this too: Href="#" Don't Scroll
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Control memory used by shelve I am using shelve in Python to handle a huge dictionary that would not fit in the memory, as well as to achieve persistence.
While running my code, which requires frequent retrieval and insertion into random locations in the dictionary, I noticed that the shelve is using only about 3% of the 4GB available memory. This is causing my code to run slower, as there would be greater number of read/writes from the disk required.
Is there any way to make the shelve use greater amount of available memory (say ~50%), so that number of hits in the memory are higher?
A: Consider ZODB or other key-value stores that integrate well with Python. Any object that can be shelved/pickled can go into ZODB. The shelve module doesnt seem to be designed for that kind of performance or consistency.
http://www.ibm.com/developerworks/aix/library/au-zodb/
You can also go for an SQL solution, with the pickle module to serialize/unserialize that object to and from text. It is the heart of Shelve and ZODB. If you are feeling really adventurous, you can try an in-memory SQLite DB. SQLite is bundled in Python.
A: I also highly recommend ZODB. You can port your shelve database to a ZODB database like this:
#!/usr/bin/env python
import shelve
import ZODB, ZODB.FileStorage
import transaction
from optparse import OptionParser
import os
import sys
import re
reload(sys)
sys.setdefaultencoding("utf-8")
parser = OptionParser()
parser.add_option("-o", "--output", dest = "out_file", default = False, help ="original shelve database filename")
parser.add_option("-i", "--input", dest = "in_file", default = False, help ="new zodb database filename")
parser.set_defaults()
options, args = parser.parse_args()
if options.in_file == False or options.out_file == False :
print "Need input and output database filenames"
exit(1)
db = shelve.open(options.in_file, writeback=True)
zstorage = ZODB.FileStorage.FileStorage(options.out_file)
zdb = ZODB.DB(zstorage)
zconnection = zdb.open()
newdb = zconnection.root()
for key, value in db.iteritems() :
print "Copying key: " + str(key)
newdb[key] = value
transaction.commit()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does declaring pointer makes it contents nil?
Possible Duplicate:
Declared but unset variable evaluates as true?
Why does this code work on Mac OS
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *str;
NSLog(@"%@", [str length]);
NSLog(@"Hello, World!");
[pool drain];
return 0;
}
and console output is
2011-09-23 15:37:17.481 Untitled1[80021:903] (null)
2011-09-23 15:37:17.495 Untitled1[80021:903] Hello, World!
but crashes on iPhone ?
A: Two mistakes.
First, you declare pointer str, don't set it's value and use it in NSLog.
Second, you use formatting %@, but supply integer value ([str length]), result is undefined. That's why on simulator it prints null, but crashes on device.
A: You were just lucky. Local variables are uninitialised and could contain anything. It's likely that on OS X, str contains 0 (aka nil), sending -length to nil returns 0. Then you are treating the length (which is an NSInteger) as a pointer for the NSLog.
If the length is 0, the NSLog will treat it as a nil pointer if the format specifier is %@ and will print (null).
If str has a random non zero value, either your program will crash when you send length or if it miraculously works and returns a non zero length, it'll probably crash trying to treat it as an object pointer in NSLog
A: the value is never initialized (or set). it could be any random value. in debug, it may be zero-iniitalized.
a crash (or some UB) is what you should expect in this case. so... turn up your compiler and static analyzer warnings, fix the issues, and always initialize your values.
A: try this.
NSString *str=@"";
NSLog(@"%d", [str length]);
A: See ,
You can call only release method over a nil object. other than release method we cannot call any method over a nil.
Here you are calling a method ( length )over an object which is pointing to nil , in this case it should point to nsstring object in general before sending length message .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP license code implementation Does anyone have any suggestions on how to implement a activation license for PHP applications? Whilst I'm not planning on encrypting the source, and I'm not expecting there to be some magical way to stop people breaking the license check (people who want to do it, are going to do it anyway), I'd still like to find the balance between being annoying for people trying to break it, and being too annoying for me that it wouldn't be worth doing.
I'd like the license check to mainly work locally without having to call home, but also to on occasion call home to confirm (say once a day/week or something) if possible. Any thoughts on how to do it?
A: You could implement a simple licensekey system, and maybe setup your own "license" server to query all your systems for a valid license key once or two times a day. Maybe also implement a license check during login to your product.
What exactly are you building this for? A CMS, offline intranet software or?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Non-preemptive Pthreads? Is there a way to use pthreads without a scheduler, so context switch occurs only if a thread explicitly yields, or is blocked on a mutex/cond? If not, is there a way to minimize the scheduling overhead, so that forced context switches will occur as rarely as possible?
The question refers to the Linux gcc/g++ implementation of POSIX threads.
A: You can use Pth (a.k.a. GNU Portable Threads), a non-preemptive thread library. Configuring it with --enable-pthread will create a plug-in replacement for pthreads. I just built and tested this on my Mac and it works fine for a simple pthreads program.
From the README:
Pth is a very portable POSIX/ANSI-C based library for Unix platforms
which provides non-preemptive priority-based scheduling for multiple
threads of execution (aka `multithreading') inside event-driven
applications. All threads run in the same address space of the server
application, but each thread has its own individual program-counter,
run-time stack, signal mask and errno variable.
The thread scheduling itself is done in a cooperative way, i.e., the
threads are managed by a priority- and event-based non-preemptive
scheduler. The intention is, that this way one can achieve better
portability and run-time performance than with preemptive scheduling.
The event facility allows threads to wait until various types of
events occur, including pending I/O on filedescriptors, asynchronous
signals, elapsed timers, pending I/O on message ports, thread and
process termination, and even customized callback functions.
Additionally Pth provides an optional emulation API for POSIX.1c
threads (`Pthreads') which can be used for backward compatibility to
existing multithreaded applications.
A: If you have a process running in normal user land, context switches will naturally happen as part of the system operation - there is always another process that needs the CPU time. Preemptive context switches between your threads are quite well optimized by the OS already and are bound to be necessary sometimes.
If you really happen to have problems with excessive context switching, you are best off tweaking the Linux scheduler first, which is off-topic here. pthread_setschedprio and pthread_setschedparam can set some hints, but are limited to setting priorities, and the interpretation of these priorities is implementation-defined, i.e. up to the Linux scheduler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Execute 'adb' from an APK Planning to execute adb to do some operation from a TestActivity.Java and try to execute the TestActivity.apk.
File wd = new File("/Android/android-sdk-windows/tools/");
Process proc = Runtime.getRuntime().exec(
"adb shell monkey -p com.sample.cts -v 50", null, wd);
proc.waitFor();
Getting the following error:
java.io.IOException: Error running exec(). Command: [adb, shell, monkey, -p, com.sample.cts, -v, 5000] Working Directory: null Environment: null
Can you please help me on this?
A: adb stands for Android Debug Bridge and it's a local helper program for developers. I doubt that this program is actually located on the device itself.
A: This is an error that android sdk is not properly attach to your eclipse
Go to preference -> click on android -> see whether all sdk are files displaying -> if it not display go for solution that i given below
This thing properly happen when antiviruses remove some sdk files in your sdk folder
Solution:
Once again download the sdk file from beginning or otherwise get the sdk package from others and put it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Points array visualization in 3d I need to show points array in three-dimensional coordinate system. Which component or library should I use for it(Winforms/WPF)?
A: Here is a tutorial for Direct3D in C#, it's for winforms: http://msdn.microsoft.com/en-us/library/ms920768.aspx. I don't think it matters whether you use winforms or wpf, the trick is to get your videocard do you drawing and that bypasses wpf.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: set methods aren't working for HttpsURLConnection I'm trying to make a rest request in java. I tested the web service using RestClient in Firefox and it works great.
When i try to modify the HttpsUrlConnection instance in java the values aren't changing and i get a 500 response code.
Here's my code:
public String getAuthToken() throws IOException {
URL url =new URL("https://webserviceurl"); // webservice url is the url of the webservice
String data = URLEncoder.encode("username") + "=" + URLEncoder.encode("myusername","UTF-8");
data+= "&" + URLEncoder.encode("password") + "=" + URLEncoder.encode("pass","UTF-8");
HttpsURLConnection conn =(HttpsURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setHostnameVerifier(new AllowAllHostnameVerifier()); //this works HostName verifier changes
conn.setRequestMethod("POST"); // this doens't work. requestMethod is still set to GET
conn.setDoOutput(true); // this doesnt work. DoOutput still set on false
conn.setRequestProperty("Content-Type", "application/json"); // doens't work either
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
wr.write(data);
wr.flush();
wr.close();
//conn has a 500 response code
if (conn.getResponseCode()==200)
{
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
String token = rd.readLine();
rd.close();
return token;
}
else
return null;
}
I'm stucked at this point and cannot find anything to make this work.
Thank you!
A: I actually think it's a bug with HttpsURLConnection. As i changed it to a HttpURLConnection object everything works just fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to change encoding in a Receive Pipeline in Biztalk? I have a receive pipeline with only a flat file dissambler in the dissamble stage,
but I need to change the encoding. The incoming file isn't utf-8 but it should be when it comes out.
A: See Tomas Restrepo's Fix Message Encoding Custom Pipeline Component here:
https://github.com/tomasr/fixencoding/tree/master/Winterdom.BizTalk.Samples.FixEncoding
A: Since the incoming file is not UTF-8 and you are using a flatfile disassembler, it means you must have defined a flat file XSD in your project. You use this flat file XSD in your pipeline componet at disassemble stage.
If the above is true, the easiest fix is to use the code page in your flat file schama(XSD) rather than the pipeline component or writing a custom pipeline component just to fix encoding. The screenshot below shows where you can set the source encoding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript isn't uploading binary data My javascript function only uploads text files correctly. Can anybody help me figure out how to make it also accept images etc. ?
function fileUpload(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
//Set vars
var file = files[i],
fileName = file.name,
fileSize = file.size,
fileData = file.getAsBinary(),
boundary = "xxxxxxxxx",
uri = "receive.php",
//Create file info HTML output
li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = file.name + ": " + file.size + " bytes";
li.appendChild(info);
//Start sending file
var xhr = new XMLHttpRequest();
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
if (xhr.responseText != "") {
alert(xhr.responseText); // display response.
}
}
}
}
var body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + fileName + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += fileData + "\r\n";
body += "--" + boundary + "--";
xhr.send(body);
}
fileList.appendChild(list);
return true;
}
}
Update: I found the following function online at http://code.google.com/p/html5uploader/ but I can't figure out how to apply it to my current function. Is xhr.sendAsBinary the only thing that changed?
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', targetPHP+'?up=true', true);
var boundary = 'xxxxxxxxx';
var body = '--' + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += bin + "\r\n";
body += '--' + boundary + '--';
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
*snip*
A: There is a W3C example of sending a GIF image using multipart/form-data at http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="submit-name"
Larry
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y
--BbC04y
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--BbC04y
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif...
--BbC04y--
--AaB03x--
Notice the extra line Content-Transfer-Encoding: binary. Try adding that.
EDIT: Try base64-encoding the file data using the Base64 jQuery plugin:
var body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + fileName + "'\r\n";
body += "Content-Type: application/octet-stream\r\n";
body += "Content-Transfer-Encoding: base64\r\n\r\n";
body += $.base64Encode(fileData) + "\r\n";
body += "--" + boundary + "--";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Android: how to process onClick without an activity? http://developer.android.com/reference/android/view/View.html#attr_android:onClick
Here it is said that
For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
I'm intrested in "typically, your Activity"... And what if not typically? I'm creating a widget app so I don't have an activity at all...
Almost forgot..
And the question is: where should I write that sayHello method?
A: Here's the code which is responsible for the invacation:
try {
mHandler = getContext().getClass().getMethod(handlerName, View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity", e);
}
So basiclly it searches in the class which implements the context for the given method. Usually the context is an activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Removing jQuery small boilerplate this is my code:
$(document).ready(function() {
$('td').empty();
getWeather();
});
$('.data').change(function() {
$('td').empty();
getWeather();
});
How can I optimize it?
I was thinking of using "OR", but I couldn't fit it anywhere.
Thanks in advance.
A: What about...
var f = function() {
$('td').empty();
getWeather();
}
$(document).ready(f);
$('.data').change(f);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best practices for Storing JSON in DOM I want to render some json data using HTML template.
I haven't started implementing anything yet, but I would like to be able to "set" values of data from json to html element which contains template for one record, or to render some collection of items using some argument which is template html for each item, but also to be able to get JSON object back in same format as source JSON which was used to render item (I want my initial JSON to contain some more information about behavior of record row, without the need to make ajax request to check if user can or can't do something with this record, and not all of this info is visible in template).
I know that I could make hidden form with an input element for each property of object to store, and mapper function to/from JSON, but it sounds like overkill to me, and I don't like that, I want some lighter "envelope".
I was wondering is there some JS library that can "serialize" and "deserialize" JSON objects into html so I can store it somewhere in DOM (i.e. in element which contains display for data, but I want to be able to store additional attributes which don't have to be shown as form elements)?
UPDATE As first answer suggested storing JSON in global variable, I also have thought about that, and my "best" mental solution was to make JavaScript module (or jQuery plugin) which would do "mapping" of JSON to html, and if not possible to store values in html then it can store them in internal variable, so when I want to "get" data from html element it can pull it from its local copy. I want to know is there better way for this? If there is some library that stores this info in variable, but does real-time "binding" of that data with html, I would be very happy with that.
UPDATE 2 This is now done using http://knockoutjs.com/, no need to keep json in DOM anymore, knockout does the JSON<=>HTML mapping automatically
A: So you want to keep a reference to the JSON data that created your DOMFragment from a template?
Let's say you have a template function that takes a template and data and returns a DOM node.
var node = template(tmpl, json);
node.dataset.origJson = json;
node.dataset.templateName = tmpl.name;
You can store the original json on the dataset of a node. You may need a dataset shim though.
There is also no way to "map" JSON to HTML without using a template engine. Even then you would have to store the template name in the json data (as meta data) and that feels ugly to me.
A: I have done this in the past as well in a couple of different ways.
The $('selector').data idea is probably one of the most useful techniques. I like this way of storing data because I can store the data in a logical, intuitive and orderly fashion.
Let's say you have an ajax call that retrieves 3 articles on page load. The articles may contain data relating to the headline, the date/time, the source etc. Let's further assume you want to show the headlines and when a headline is clicked you want to show the full article and its details.
To illustrate the concept a bit let's say we retrieve json looking something like:
{
articles: [
{
headline: 'headline 1 text',
article: 'article 1 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
},
{
headline: 'headline 2 text',
article: 'article 2 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
},
{
headline: 'headline 3 text',
article: 'article 3 text ...',
source: 'source of the article, where it came from',
date: 'date of the article'
}
]
}
From an ajax call like this . . .
$.ajax({
url: "news/getArticles",
data: { count: 3, filter: "popular" },
success: function(data){
// check for successful data call
if(data.success) {
// iterate the retrieved data
for(var i = 0; i < data.articles.length; i++) {
var article = data.articles[i];
// create the headline link with the text on the headline
var $headline = $('<a class="headline">' + article.headline + '</a>');
// assign the data for this article's headline to the `data` property
// of the new headline link
$headline.data.article = article;
// add a click event to the headline link
$headline.click(function() {
var article = $(this).data.article;
// do something with this article data
});
// add the headline to the page
$('#headlines').append($headline);
}
} else {
console.error('getHeadlines failed: ', data);
}
}
});
The idea being we can store associated data to a dom element and access/manipulate/delete that data at a later time when needed. This cuts down on possible additional data calls and effectively caches data to a specific dom element.
anytime after the headline link is added to the document the data can be accessed through a jquery selector. To access the article data for the first headline:
$('#headlines .headline:first()').data.article.headline
$('#headlines .headline:first()').data.article.article
$('#headlines .headline:first()').data.article.source
$('#headlines .headline:first()').data.article.date
Accessing your data through a selector and jquery object is sorta neat.
A: Why not store it as nature intended: as a javascript object? The DOM is a horrible place.
That said, jQuery has the data method that allows just this.
A: I don't think there are any libraries that store json in dom.
You could render the html using the data from json and keep a copy of that json variable as a global variable in javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Naming a list from an item within an other list That's probably a very easy one, but I cannot solve my issue. The below code returns an error:
person = c("name", "surname")
list(person[1]= "John")
Error : '=' unexpected in "list(person[1]="
I would like it to return:
$name
[1] "John"
Can StackOverflow help me with this?
A: Perhaps the following will be of use:
> p <- list("John", "Smith")
> names(p) <- c("name", "surname")
> p
$name
[1] "John"
$surname
[1] "Smith"
A: Since you seem to be trying to access a list element via a named variable, this might be what you are after. This is pretty much the same as aix's answer, but via a different route.
person = c("name", "surname")
Create the empty list, which can be inefficient when you grow the list later.
x <- list()
Now assign values to this list via the "person" values.
x[person[1]] <- "John"
x[person[2]] <- "Smith"
x
$name
[1] "John"
$surname
[1] "Smith"
I don't think that's really going to help much when you want to keep growing the list, but it might help you see how these things work a little better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Optimized C# equivalent of tsql "in (value1, value2)"? In SQL you can write something like
if value in (value1,value2) then ... else ...
In C# it would be nice to write
A) if( value == (value1 or value2) ) { ... }
Or
B) if( value in (value1, value2) ) { ... }
Of course you can already write:
C) if( new[]{value1, value2}.Contains(value) )
But this code is slow as it builds a new array.
Which one do you like best ?
A: If value1 and value2 are always the same, I'd build a collection (whether a set, an array, a list or whatever) once, and store them in a static variable.
Otherwise, I'd probably write:
if (value == value1 || value == value2)
If I had several values, then for readability I would create the collection - but with just two values I probably wouldn't bother - the above more readable than the array-creating form, IMO.
If I'd gone for the collection-creating form, I would then consider optimizing back to the non-collection-creating form only when I'd discovered that the application was too slow and proved that it was due to creating the collection.
In other words:
*
*Simplicity first (comparing two values with == and || is fine)
*Simplicity again (create a collection when it genuinely improves simplicity)
*Performance only when it's been tested and found to be important in this piece of code
*Simplicity and performance together where possible (using a single "constant" collection where that makes sense)
A: If it's only two or three values I would use if (value == value1 || value == value2) otherwise you could use your third way, but make the array static if it doesn't change.
A: Depends on the performance balance that you want to achieve and the size of your data set.
If you can afford a relatively expensive construction and the lookup is absolutely critical performance-wise and the lookup happens frequently compared to construction and the number of items is large enough to justify it all, construct a new HashSet, then use HashSet.Contains.
If, on the other hand, you only have few items, having if (value == value1 || value == value2 /* Etc.. */) is probably good enough. Just be careful to "sort" your values from most-likely-to-match to least-likely-to-match. For example, if value2 tends to match more frequently than value1, rewrite the above "if" as: if (value == value2 || value == value1) so the || operator can perform its short-circuiting.
A: The idea here is to have a construct easier to read than a serie of IF when you have few non constant items.
I will suggest the C# team to add a contruct like this in C# next :
if( value in (value1, value2) ) { ... }
which should expand to a temporary collection and use Contains, or a const collection if all values are constants.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: on draw on an android button First I'm new to android.
Okay, here goes.
I'm attempting to override the onDraw of a button, because I want to create a different styled button.. Something ever so slightly different.
Now I can draw the background quite easily, but I can't for the life of me figure out why I have no text on my button.
public class TriButton extends Button {
private Paint m_paint = new Paint();
private int m_color = 0XFF92C84D; //LIKE AN OLIVE GREEN..
public TriButton(Context context) {
super(context);
setBackgroundColor(Color.BLACK);
}
public void onDraw(Canvas iCanvas) {
//draw the button background
m_paint.setColor(m_color);
iCanvas.drawRoundRect(new RectF(0, 0,getWidth(),getHeight()), 30, 30, m_paint);
//draw the text
m_paint.setColor(Color.WHITE);
iCanvas.drawText( "bash is king", 0, 0, m_paint);
}
public static RelativeLayout.LayoutParams GetRelativeParam(int iLeft, int iTop, int iWidth, int iHeight){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(iHeight, iWidth);
params.leftMargin = iLeft;
params.topMargin = iTop;
return params;
}
}
Here's the code that creates the button.
RelativeLayout relLay = new RelativeLayout(this);
m_button = new TriButton(this);
setContentView(relLay);
relLay.addView(m_button, m_button.GetRelativeParam(0,0,100,500) );
Now everything I've read has me expecting to see text in my olive green button oval button.
The olive green oval shows up, but it doesn't have text in it.. It is a void. A green smudge that laughs at me and reminds me with it's silence, that I am utterly alone :(.
A: Normally you would do that via xml.
for examle put the following in the layout of your custom class:
android:background="@drawable/shape"
and then something like that which would be shape.xml placed in /drawable.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="2px"
android:color="#555555"/>
<corners
android:radius="10px"/>
<gradient
android:startColor="#000000"
android:endColor="#ffffff"
android:angle="90"/>
</shape>
This example creates a rounded rectangle with a border and a gradient in it. Let me know if you need further explanation.
See http://developer.android.com/guide/topics/ui/themes.html
A: Ok, I figured, it's not visible because coordinates are (0,0) which is bottom left of the button, so text is not visible. Try this and it works:
iCanvas.drawText( "bash is king", 0, 15, m_paint);
Olive green is a good choice btw :)
A: To draw text in your button, get rid of the call to drawText() within the onDraw of your button class. All you need to do is call setText on the instance of the button since Button extends view:
m_button.setText("bash is king");
Also, to make a custom button, you may want to consider just using an Image and assigning an OnClickListener to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading corresponding entities while loading a collection Currenty I'm working on a webshop using an auction module. This auction module has its own set of entities representing an auction and their bids. The main entity is the ProductAuction model. This model has an relation to the Catalog_Product model of Magento.
Everywhere the collection is loaded the products have to be loaded after the collection of ProductAuctions has been loaded.
Now I have to write some exotic queries to load a specific sets of auctions in combination with category and search queries. Now I first have to load a collection of products belonging to the given category and search query, then load the active auctions belonging to the set of corresponding products.
In some scenarios I can't reuse the set of loaded products and then have to execute another query to load the products corresponding the auctions.
Worst case I'll have to execute three big queries and process the resultsets which should be possible in one query.
Is it possible in Magento to load relating entities within a collection, just like any decent ORM would do with One-2-One, Many-2-One and other relations?
I haven't found any example of this, but I can't imagine this isn't possible in Magento.
Thanks for any help on this.
== EDIT ==
A bit of example code to show what I'm doing at the moment:
/**
* Build the correct query to load the product collection for
* either the search result page or the catalog overview page
*/
private function buildProductCollectionQuery() {
/**
* @var Mage_CatalogSearch_Model_Query
*/
$searchQuery = Mage::helper('catalogsearch')->getQuery();
$store_id = Mage::app()->getStore()->getId();
$productIds = Mage::helper('auction')->getProductAuctionIds($store_id);
$IDs = array();
$productIds = array();
$collection = Mage::getModel('auction/productauction')
->getCollection()
->addFieldToFilter(
'status', array('in' => array(4))
);
if (count($collection)) {
foreach ($collection as $item) {
$IDs[] = $item->getProductId();
}
}
$collection = Mage::getResourceModel('catalog/product_collection')
->addFieldToFilter('entity_id',array('in'=> $IDs ))
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter();
if( $searchQuery != null ) {
$collection->addAttributeToFilter(array(
array('attribute' => 'name', 'like'=>'%' . $searchQuery->getQueryText() . '%'),
array('attribute' => 'description', 'like'=>'%' . $searchQuery->getQueryText() . '%')
)
);
// @TODO This should be done via the Request object, but the object doesn't see the cat parameter
if( isset($_GET['cat']) ) {
$collection->addCategoryFilter(Mage::getModel('catalog/category')->load($_GET['cat']) );
}
}
return $collection;
}
A: Managed to come up with a solution. I now use the following code to get all the information I need. Still I'm surprised it is so hard to create instances of relating objects like any normal ORM would do. But perhaps I am expecting too much of Magento..
Anyway, this is the code I use now:
/**
* Build the correct query to load the product collection for
* either the search result page or the catalog overview page
*/
private function buildProductCollectionQuery() {
/**
* @var Mage_CatalogSearch_Model_Query
*/
$searchQuery = Mage::helper('catalogsearch')->getQuery();
$collection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addAttributeToSelect(array('product_id' => 'entity_id'))
->joinTable(array('productauction' => 'auction/productauction'), 'product_id=entity_id', array('start_time' => 'productauction.start_time','end_time' => 'productauction.end_time','entity_id' => 'productauction.productauction_id', 'product_id' => 'product_id'))
->joinTable(array('auction' => 'auction/auction'), 'product_id = entity_id', array('last_bid' => 'MAX(auction.price)'), 'auction.productauction_id = productauction.productauction_id', 'inner')
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter()
->setPage((int) $this->getRequest()->getParam('p', 1), 1);
$currentCategory = Mage::registry('current_category');
if( $currentCategory != null ) {
$collection->addCategoryFilter($currentCategory);
}
if( $searchQuery != null ) {
$collection->addAttributeToFilter(array(
array('attribute' => 'name', 'like'=>'%' . $searchQuery->getQueryText() . '%'),
array('attribute' => 'description', 'like'=>'%' . $searchQuery->getQueryText() . '%')
)
);
// @TODO This should be done via the Request object, but the object doesn't see the cat parameter
if( isset($_GET['cat']) ) {
$collection->addCategoryFilter(Mage::getModel('catalog/category')->load($_GET['cat']) );
}
}
$collection->getSelect()->group('productauction.productauction_id');
return $collection;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simple automated slideshow in jQuery i have a simple slideshow which is working okay so far. it consists of a pager and the images to display. both are an unordered list:
<ul id="keyvisualpager">
<li><a><span>Show Keyvisual 1</span></a></li>
<li><a><span>Show Keyvisual 2</span></a></li>
<li><a><span>Show Keyvisual 3</span></a></li>
</ul>
<ul id="keyvisualslides">
<li><img src="index_files/mbr_keyvisual1.jpg" alt="Keyvisual" /></li>
<li><img src="index_files/mbr_keyvisual2.jpg" alt="Keyvisual" /></li>
<li><img src="index_files/mbr_keyvisual3.jpg" alt="Keyvisual" /></li>
</ul>
The according jQuery code is:
$('#keyvisualpager li a').click(function () {
// get position of a element
var mbr_index = $(this).parent().prevAll().length;
var mbr_targetkeyvisual = mbr_index + 1;
// hide current image and show the target image
$('#keyvisualslides li:visible').hide();
$('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show()
// remove active class from current indicator and add the same class to target indicator
$('#keyvisualpager li a').removeClass('keyvisualactive');
$('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive');
});
initially all images are set to display: none; ... upcon clicking a a link in #keyvisualpager the according image is then displayed. at the same time the indicator changes accordingly.
now, my problem:
apart from this mode of navigating through the images i need the whole slideshow to automatically advance. how can i achieve that:
a) the next image is shown after lets say 5 seconds and
b) the class ".keyvisualactive" is added to the according a element in #keyvisualpager
note: unfortunately i have to use jquery 1.2.1, updating is not an option.
thanks for your help guys
EDIT
i am now using this code. it almost works. but after the last image in the set is displayed: how can i tell it to start over with the first image? thanks!
var reload = setInterval(function(){
// get position of a element
var mbr_index = $('#keyvisualpager li .keyvisualactive').parent().prevAll().length;
var mbr_targetkeyvisual = mbr_index + 2;
// alert(mbr_index+'//'+mbr_targetkeyvisual)
// hide current image and show the target image
$('#keyvisualslides li:visible').hide();
$('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show();
// remove active class from current indicator and add the same class to target indicator
$('#keyvisualpager li a').removeClass('keyvisualactive');
$('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive');
}, 2000);
A: You can use JavaScript's setInterval() method to achieve this.
var reload = setInterval(function(){
// do something
}, 5000);
The number is length of every pause in milliseconds.
To stop the slideshow, for example when a user selects an image, you can use clearInterval() method.
EDIT
Try something like this:
$('#keyvisualpager li a').click(function () {
var reload = setInterval(function(){
// get position of a element
var mbr_index = $(this).parent().prevAll().length;
var mbr_targetkeyvisual = mbr_index + 1;
// hide current image and show the target image
$('#keyvisualslides li:visible').hide();
$('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show()
// remove active class from current indicator and add the same class to target indicator
$('#keyvisualpager li a').removeClass('keyvisualactive');
$('#keyvisualpager li:nth-child('+mbr_targetkeyvisual+') a').addClass('keyvisualactive');
}, 5000);
$('#pagerstop').click(function(){
clearInterval(reload);
}
});
EDIT 2
You have to keep track of image count and the index you are at (if I understood correctly you have this in your var mbr_targetkeyvisual?) so it should work like this (not tested):
// Image count
var content_length = $('#keyvisualslides').children().length;
var automate = setInterval(function(){
if(index < content_length){
$('#keyvisualslides li:visible').hide();
$('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show();
mbr_targetkeyvisual++;
}
else{
mbr_targetkeyvisual = 0;
$('#keyvisualslides li:visible').hide();
$('#keyvisualslides li:nth-child('+mbr_targetkeyvisual+')').show();
mbr_targetkeyvisual++;
}
}, 5000);
A: how to make this be automated to, or we can add navigation next and prev
$(function(){
$('.slide-thumb .thumb').on("mouseenter",function(){
var dataImage = $(this).data('image');
$('.slide-jumbo .jumbo:visible').fadeOut(1000,function(){
$('.slide-jumbo .jumbo[data-image="'+dataImage+'"]').fadeIn(500);
});
});
});
* {
font-family: Arial;
}
.slide-container {
/*border: solid 1px;*/
width: 500px;
height: 360px;
}
.slide-jumbo {
/*border: solid 1px;*/
width: 500px;
height: 300px;
overflow: hidden;
}
.jumbo {
position: relative;
display: inline-block;
width: 500px;
height: 300px;
float: left;
}
.jumbo img, .thumb img {
position: absolute;
left: 0;
}
.jumbo img {
top: 0;
}
.thumb img {
bottom: 0;
}
.jumbo-capt, .thumb-capt {
width: 100%;
background-color: rgba(0,0,0,0.8);
position: absolute;
color: #fff;
z-index: 100;
/* -webkit-transition: all 300ms ease-out;
-moz-transition: all 300ms ease-out;
-o-transition: all 300ms ease-out;
-ms-transition: all 300ms ease-out;
transition: all 300ms ease-out; */
left: 0;
bottom: 0;
}
.slide-thumb {
/*border: solid 1px;*/
width: 500px;
height: 60px;
overflow: hidden;
}
.thumb {
position: relative;
/*border: solid 1px;*/
display: inline-block;
width: 100px;
height: 60px;
overflow: hidden;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="slide-container">
<div class="slide-jumbo">
<div class="jumbo" data-image="1">
<img src="images/2.png">
<div class="jumbo-capt">
<h3>Title 1</h3>
<p>Summary 1</p>
</div>
</div>
<div class="jumbo" data-image="2">
<img src="images/3.png">
<div class="jumbo-capt">
<h3>Title 2</h3>
<p>Summary 2</p>
</div>
</div>
<div class="jumbo" data-image="3">
<img src="images/9.png">
<div class="jumbo-capt">
<h3>Title 3</h3>
<p>Summary 3</p>
</div>
</div>
<div class="jumbo" data-image="4">
<img src="images/7.png">
<div class="jumbo-capt">
<h3>Title 4</h3>
<p>Summary 4</p>
</div>
</div>
<div class="jumbo" data-image="5">
<img src="images/9.png">
<div class="jumbo-capt">
<h3>Title 5</h3>
<p>Summary 5</p>
</div>
</div>
</div>
<div class="slide-thumb">
<div class="thumb" data-image="1">
<img src="images/2small.png">
<div class="thumb-capt">
<p>
<strong>
Title 1
</strong>
</p>
</div>
</div>
<div class="thumb" data-image="2">
<img src="images/3small.png">
<div class="thumb-capt">
<p>
<strong>
Title 2
</strong>
</p>
</div>
</div>
<div class="thumb" data-image="3">
<img src="images/9small.png">
<div class="thumb-capt">
<p>
<strong>
Title 3
</strong>
</p>
</div>
</div>
<div class="thumb" data-image="4">
<img src="images/7small.png">
<div class="thumb-capt">
<p>
<strong>
Title 4
</strong>
</p>
</div>
</div>
<div class="thumb" data-image="5">
<img src="images/9small.png">
<div class="thumb-capt">
<p>
<strong>
Title 5
</strong>
</p>
</div>
</div>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Implement locking & unlocking a document while editing Here's the situation:
I have a web-based ticket application, multiple users.
One problem that might occur (and does happen in the old version I'm replacing) is that user1 opens a ticket, edits it, and saves it. But while he was editing it, user2 also opened and saved the ticked. The changes user2 made will be lost/overwritten by user1.
To prevent this I implemented a locking mechanism, it's fairly simply:
*
*On opening a ticket the PHP script checks for existing locks.
*If it doesn't find any, it locks & opens the document.
*In JS, setTimeout() and an XmlHttpRequest call to unlocks the ticket after 10 minutes (works w/o problems).
*I also set an unload event to unlock the ticket when closing/moving away from the window/tab
The problem sits in step 4: The unload event (& it's friend beforeunload) just doesn't work well enough to implement this reliably (for this feature to have any serious meaning, it needs to be reliable), many browsers don't always fire it when I would like it to be fired (Like pressing back button, hitting F5, closing tab, etc. This varies per browser)
The only alternative I can come up with is using a setTimeout() and XmlHttpRequest() call to a php script to tell it the page is still open. If this "heartbeat" monitor fails we assume the user moved away from the ticket and unlock the document.
This seems horribly inefficient to me and quickly leads to many requests to the server with even a few users.
Anyone got a better idea on how to handle this?
It needs to work in IE8+ and other modern browsers (ideally, Firefox, Webkit, Opera). I don't care about IE6/IE7, our organization doesn't use those).
A: Using heartbeat pings via XHR is the way to go. Depending on the use case you might also want to send them after the user stopped typing in a field instead of every x seconds - this would ensure the page being kept open but inactive would not keep it locked.
If you send those XHRs after the user stopped typing, use one of the keydown/up/press events and a debounce / throttle script to send the request only when the user stops typing for e.g. 5 seconds and one every x seconds (in case it's likely enough the user will be typing for a long time).
A: Maybe it's not the best solution, but it's worth looking into it : websockets.
You could establish a connection with the server at page load and when the connection fails (ie the client does not respond to the ping), you can unlock the ticket.
Using something like socket.io ensures you that this procedure will work even on ie8.
*
*The main advantage is that you do not send a request every n seconds, but the server sends you a ping every n seconds and you don't have to care about unload/beforeunload events. If the client doesn't respond to the ping, unlock the ticket.
*The main disadvantage is that you need a server to handle all your websocket connections, which can be done in almost any server-side language, but it can be a bit harder than a simple web-service (in case of xhr polling)
A: Implementing ajax heartbeats or unload handlers to unlock the document automatically is tricky.
You problem is that even if you have support for beforeunload in all browsers that you target, it still might not be called if the browser crashes or the user falls asleep.
Look at how webdav works. You explicitly aquire a lock before you start edit, then you save and release the lock explicitly.
Other users can see who has acquired a lock and admins can release locks that has been left behind by accident.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Entity Framework 4.1 - Code First with existing Database, how to define classes, using Attributes or EntityTypeConfiguration? What is the difference? I have been studying the EF for a short time and cant find the answer to this question.
I have existing database and I am using CodeFirst to create classes for the model.
What is the difference in using Attributes and EntityTypeConfiguration to define parameters of table columns?
Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?
Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?
Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?
Thank You
A: Get the Entity Framework Power Tools CTP1 and it will reverse engineer your database and create entities, and a full data mapping. This is different than Model or Database first in that it generates a fluent model rather than using an .edmx file. You can see exactly how it works then.
A: See the following article about how you can create your entity classes from existing database :
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Code generation templates will do the work for you, you don't need to write them if you have an existing db.
For validation, you can create new partial classes under the same namespace and put DataAnottations for your properties. Here is an example for you :
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace TugberkUgurlu.App1.DataAccess.SqlServer {
[MetadataType(typeof(Country.MetaData))]
public partial class Country {
private class MetaData {
[Required]
[StringLength(50)]
[DisplayName("Name of Country")]
public string CountryName { get; set; }
[Required]
[StringLength(5)]
[DisplayName("ISO 3166 Code of Country")]
public string CountryISO3166Code { get; set; }
[DisplayName("Is Country Approved?")]
public string IsApproved { get; set; }
}
}
}
A: -Since the database already has defined foreign keys and unique constraints, and so on, how and where to implement the validation for a best and most fluid result for use in ASP.NET MVC3?
These should happen via your generated model. Keys are automatically inferred. If you reverse engineer an existing database the attributes will be created for you. If not, there are basic rules that are followed. The entity framework will attempt to use an auto incrementing primary key for example unless you tell it otherwise via
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
The relationships are already part of your model so there is your referential integrity, and the data annotations will define the validation rules.
-Is it better to implement Attributes and CustomValidation or to use TryCatch blocks to catch errors from db?
Implement attributes. Define your metadata classes with your attributes in them.
In addition you want to catch any db errors for anything else that is unexpected if your db has additional logic in there not defined in your model (try catch at some level should generally be used anyways for logging purposes_
-Does Validator.TryValidateObject(myModelObject, context, results, true); use validation rules defined only as Attributes or can it use rules defined in EntityTypeConfiguration?
As far as I'm aware only the attributes are used. I'm going to try to test this later though as I'd like a definite answer on this as well :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: error with Qt libraries in visual c++ application I am working with a Qt based project in visual c++. Initially I installed Qt 4.7.3 and imported its libraries in visual c++. Everything was working fine. yesterday, I ran "configure" command on command on command prompt. After that I am receiving error messages while compiling the program.
So I uninstalled Qt 4.7.3 and installed 4.7.4 and configured again the libraries. But still I am receiving the same error messages.
Qwt.lib(moc_qwt_scale_widget.obj) : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QWidget::staticMetaObject" (?staticMetaObject@QWidget@@2UQMetaObject@@B)
1>Qwt.lib(moc_qwt_dyngrid_layout.obj) : error LNK2001: unresolved external symbol "public: static struct QMetaObject const QLayout::staticMetaObject" (?staticMetaObject@QLayout@@2UQMetaObject@@B)
1>..\Debug\project.exe : fatal error LNK1120: 9 unresolved externals
1>
Can anyone please help me in this issue.
A: Its a linker error.. you need to compile your headers that contain Q_OBJECT macro with moc compiler. Look at this guys solutions
Q_OBJECT Problem in Visual C++
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python -- trying to count the length of the words from a file with dictionaries def myfunc(filename):
filename=open('hello.txt','r')
lines=filename.readlines()
filename.close()
lengths={}
for line in lines:
for punc in ".,;'!:&?":
line=line.replace(punc," ")
words=line.split()
for word in words:
length=len(word)
if length not in lengths:
lengths[length]=0
lengths[length]+=1
for length,counter in lengths.items():
print(length,counter)
filename.close()
A: Use Counter. (<2.7 version)
A: You are counting the frequency of words in a single line.
for line in lines:
for word in length.keys():
print(wordct,length)
length is dict of all distinct words plus their frequency, not their length
length.get(word,0)+1
so you probably want to replace the above with
for line in lines:
....
#keep this at this indentaiton - will have a v large dict but of all words
for word in sorted(length.keys(), key=lambda x:len(x)):
#word, freq, length
print(word, length[word], len(word), "\n")
I would also suggest
*
*Dont bring the file into memory like that, the file objects and handlers are now iterators and well optimised for reading from files.
*drop the wordct and so on in the main lines loop.
*rename length to something else - perhaps words or dict_words
Errr, maybe I misunderstood - are you trying to count the number of distinct words in the file, in which case use len(length.keys()) or the length of each word in the file, presumably ordered by length....
A: The question has been more clearly defined now so replacing the above answer
The aim is to get a frequency of word lengths throughout the whole file.
I would not even bother with line by line but use something like:
fo = open(file)
d_freq = {}
st = 0
while 1:
next_space_index = fo.find(" ", st+1)
word_len = next_space_index - st
d_freq.get(word_len,0) += 1
print d_freq
I think that will work, not enough time to try it now. HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Keeping multiple OnClickListeners in one class I am kinda new to Android and it would improve my application a lof if I coul keep several OnClickListenres in one class. What I am thiking of is something like this :
Public class OnClickListeners {
public Button.OnClickListener open;
public Button.OnClickListener doSomethingElse;
public Button.OnClickListener etc;
public OnClickListeners() {
open = new Button.OnClickListener()
{
public void onClick(View view)
{
DetailList.SetId(view.getId());
Intent intent = new Intent(view.getContext(), DetailList.class);
startActivityForResult(intent, 100);
}
};
}
}
So I can then reference it in other class B like this
button1.setOnClickListener(OnClickListeners.open);
Any though how to do it?
Android SDK seems to be against me as I can figure it out now for about 2 days now...
Thanks for any advices and help
A: There is a sleek way to consolidate all your anonymous classes into one and switch on the view. This works best if you know ahead of time which buttons will be using the clicklistener :
public class AndroidTestClickListenerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new MyClickListener());
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new MyClickListener());
Button button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener(new MyClickListener());
}
}
class MyClickListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.button1:
// do soemthign for button1
break;
case R.id.button2:
// do something for button2
break;
case R.id.button3:
// do something for button3
break;
default:
// do something for any other button
}
}
}
A: You can, but you have to declare the OnClickListener as static if you would like to use it in this manner.
public static Button.OnClickListener openListener = new Button.OnClickListener() {
public void onClick(View view) {
}
};
Then you can use:
button1.setOnClickListener(OnClickListeners.openListener);
As noted by other user - this approach is most like bad. You should handle view listeners on the same view and then maybe call another method like openActivity(). I would not do this - you are also openning an activity from another activity, this will probably don't work at all or will mess up the activity history stack
A: You can write
button1.setOnClickListener(new OnClickListeners().open);
instead, but this seems an odd architecture for me. I'd suggest you to keep 1 listener in 1 file, having all of them in 1 package, and use like
button1.setOnClickListener(new OpenListener());
A: The problem of you approach is that usually listeners have to manipulate some data that is part of the class where UI elements are.
If you take listeners out and put them in a separate class, you will also have to provide a lot of references to objects where data to be manipulated is. This will create a lot of interdependent classes, which will not be nice.
IMHO the cleanest way is to use anonymous inner classes.
A: As none of the solutions actually did what I wanted to achieve - I needed a second (or multiple) onClickListener that did not override the onClickListeners that were already assigned to the control.
Here is the java class that I wrote for that purpose:
https://gist.github.com/kosiara/c090dcd684ec6fb2ac42#file-doubleclicklistenerimagebutton-java
public class DoubleClickListenerImageButton extends ImageButton {
View.OnClickListener mSecondOnClickListener;
public DoubleClickListenerImageButton(Context context) {
super(context);
}
[...]
public void setSecondOnClickListener(View.OnClickListener l) {
mSecondOnClickListener = l;
}
@Override
public boolean performClick() {
if (mSecondOnClickListener != null)
mSecondOnClickListener.onClick(this);
return super.performClick();
}
@Override
public boolean performContextClick() {
if (mSecondOnClickListener != null)
mSecondOnClickListener.onClick(this);
return super.performContextClick();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unhandled Error in Silverlight Application Code: 4004 System.Collections.Generic.KeyNotFoundException I'm getting this error in a very strange manner. I've been able to isolate it, and I know what is causing it, but I don't have a clue why.
This is the situation: I have a ChildWindow, which contains a TabControl, which contains two UserControl, and both of them contain a datagrid like this causing the unhandled error:
<sdk:DataGrid x:Name="PersonEmailDataContainer" AutoGenerateColumns="False" Height="119" HorizontalAlignment="Left" Margin="12,39,0,0" VerticalAlignment="Top" Width="736"
ItemsSource="{Binding PagedListOfPersonEmail, Mode=TwoWay}"
ColumnHeaderStyle="{StaticResource ColBinding}"
SelectedItem="{Binding SelectedPersonEmail, Mode=TwoWay}"
IsReadOnly="{Binding PersonEmailDataContainerIsReadOnly, Mode=TwoWay}">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True"
CanUserSort="True" Width="Auto" />
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True"
CanUserSort="True" Width="20*"
Binding="{Binding Email, Mode=TwoWay}"
Header="{Binding ConverterParameter=HdrEmail, Converter={StaticResource Localization}, Source={StaticResource Localization}}" />
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True"
CanUserSort="True" Width="20*"
Binding="{Binding WebSite, Mode=TwoWay}"
Header="{Binding ConverterParameter=HdrWebSite, Converter={StaticResource Localization}, Source={StaticResource Localization}}" />
</sdk:DataGrid.Columns>
<!-- more columns -->
</sdk:DataGrid>
I solved it by removing the first column, which is just a blank column. It displays no data, it has no bindings, it doesn't even have a header to display. Any ideas why this was causing the error?
A: If you have a DataGrid that is bound to an ItemsSource then you cannot have a sdk:DataGridTextColumn that does not have a binding. You can use the sdk:DataGridTemplateColumn instead. This column type does not require a binding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PayPal - How to refuse payments below a certain threshold? I am selling a high volume product that costs a minimal amount per piece. ($0.001 USD each to be exact).
I allow my customers to purchase a one time amount of product or a recurring payment amount of product at their desired choice of USD per payment.
How can I limit my customers to only spending $10 USD or more per payment through PayPal? They limit it at $10,000 USD, can I limit it at $10 USD?
Right now, I am not processing payments of less than $10 USD, and recommending that customers do not, but it is still possible to make them.
The problem arises when a customer purchases $1 worth of product and paypal takes 40 odd percent of that payment due to per-payment fees.
A: I do not believe PayPal offers a setting for minimum allowed payment. This is something you would need to handle on the server side. It would be easy enough to do. Just don't display the "Pay with PayPal" button unless the order total is $10 or more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to create a "header row" for a Winforms ComboBox? Is there a way to create a "header row" for a winforms combo box?
So that's it's always displayed at the top?
A: The quick answer is: probably not. You would have to make your own usercontrol to do something like that.
This Getting ComboBox to show a TreeView shows how to so something like that. Just replace the treeview with a usercontrol that contains a label at the top and a listbox. Pass your combobox list of items to the usercontrol, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: One Log4j for two Web Applications I have two war files , one is client war file and another is Axis2.war file.
Is it possible to have common Log4j for both these Applications (Means both using one Log4j.properties file )
Thank you .
A: Yes, you need to place Log4J JAR in common directory (like /lib in Tomcat) and remove it from /WEB-INF/lib directories inside both WARs. Now place log4j.xml on the CLASSPATH, so it will be loaded upon servlet container startup, not the web application.
A: Yes, just configure Log4j via the PropertyConfigurator.configure(location), where location may be a parameter passed to tomcat via -Dlog.location or configured in each application to point to the same file.
Do that configuration in a ServletContextListener.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamic linq - Group by interval (DateTime, Numeric) I search everywhere and didn`t find anwser for this question. I want to group by intervals (DateTime, Numeric) in Dynamic linq (the data will be crated dynamically so i must use dynamic linq)
Lets assume that we have such data:
ID|Date|Price
1|2010-11-01|100
2|2010-11-01|120
3|2010-11-02|50
4|2010-12-01|30
5|2010-12-01|220
6|2011-01-01|400
How to get this data grouped by like this
-(Group by Day) following groups
->2010-11-01 = 2 elements
->2010-11-02 = 1 elements
->2010-12-01 = 2 elements
->2011-01-01 = 1 elements
-(Group by Month) following groups
->2010-11 = 3 elements
->2010-12 = 2 elements
->2011-01 = 1 elements
-(Group by Quarter) following groups
->2010 q.03 = 5 elements
->2011 q.01 = 1 elements
-(Group by Year) following groups
->2010 = 5 elements
->2011 = 1 element
-(Group by Price (From 0, Each 50)) following groups
-> <0-50) = 1 elements
-> <50-100) = 1 elements
-> <100-150) = 2 elements
-> <200-250) = 1 elements
-> <400-450) = 1 elements
-(ideally it would be Group by Price (From 0-50,From 50-150, From 150-500)) following groups
-> <0-50) = 1 elements
-> <50-150) = 3 elements
-> <150-500) = 2 elements
Any Ideas? I stress again - it must be DYNAMIC LINQ or eventually some sophisticated lambda expression? I should been able to "group" it by column name that will be in string. e.g.
GroupBy("Date"), GroupBy("Price");
A: Here's how to do it:
For instance:
Group by Month
public Item[] data =
{
new Item { Date = new DateTime(2011, 11, 6), Price = 103, Name = "a" },
new Item { Date = new DateTime(2011, 11, 16), Price = 110, Name = "b" },
new Item { Date = new DateTime(2011, 12, 4), Price = 200, Name = "c" },
new Item { Date = new DateTime(2011, 12, 4), Price = 230, Name = "d" },
new Item { Date = new DateTime(2012, 1, 15), Price = 117, Name = "e" }
};
var groups = data.AsQueryable().GroupBy("Date.Month", "it").Cast<IGrouping<int, Item>>();
You can use "Date.Day" and "Date.Year" and for something like a price range you could use a function which maps everything in the range onto the same value e.g. using integer division "(it.Price / 50)"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get totalsize of files in directory? How to get totalsize of files in directory ? Best way ?
A: I tested the following code and it works perfectly fine.
Please do let me know if there is anything that you don't understand.
var util = require('util'),
spawn = require('child_process').spawn,
size = spawn('du', ['-sh', '/path/to/dir']);
size.stdout.on('data', function (data) {
console.log('size: ' + data);
});
// --- Everything below is optional ---
size.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
size.on('exit', function (code) {
console.log('child process exited with code ' + code);
});
Courtesy Link
2nd method:
var util = require('util'), exec = require('child_process').exec, child;
child = exec('du -sh /path/to/dir', function(error, stdout, stderr){
console.log('stderr: ' + stderr);
if (error !== null){
console.log('exec error: ' + error);
}
});
You might want to refer the Node.js API for child_process
A: Use du : https://www.npmjs.org/package/du
require('du')('/home/rvagg/.npm/', function (err, size) {
console.log('The size of /home/rvagg/.npm/ is:', size, 'bytes')
})
A: ES6 variant:
import path_module from 'path'
import fs from 'fs'
// computes a size of a filesystem folder (or a file)
export function fs_size(path, callback)
{
fs.lstat(path, function(error, stats)
{
if (error)
{
return callback(error)
}
if (!stats.isDirectory())
{
return callback(undefined, stats.size)
}
let total = stats.size
fs.readdir(path, function(error, names)
{
if (error)
{
return callback(error)
}
let left = names.length
if (left === 0)
{
return callback(undefined, total)
}
function done(size)
{
total += size
left--
if (left === 0)
{
callback(undefined, total)
}
}
for (let name of names)
{
fs_size(path_module.join(path, name), function(error, size)
{
if (error)
{
return callback(error)
}
done(size)
})
}
})
})
}
A: Review the node.js File System functions. It looks like you can use a combination of fs.readdir(path, [cb]), and fs.stat(file, [cb]) to list the files in a directory and sum their sizes.
Something like this (totally untested):
var fs = require('fs');
fs.readdir('/path/to/dir', function(err, files) {
var i, totalSizeBytes=0;
if (err) throw err;
for (i=0; i<files.length; i++) {
fs.stat(files[i], function(err, stats) {
if (err) { throw err; }
if (stats.isFile()) { totalSizeBytes += stats.size; }
});
}
});
// Figure out how to wait for all callbacks to complete
// e.g. by using a countdown latch, and yield total size
// via a callback.
Note that this solution only considers the plain files stored directly in the target directory and performs no recursion. A recursive solution would come naturally by checking stats.isDirectory() and entering, although it likely complicates the "wait for completion" step.
A: Here is a simple solution using the core Nodejs fs libraries combined with the async library. It is fully asynchronous and should work just like the 'du' command.
var fs = require('fs'),
path = require('path'),
async = require('async');
function readSizeRecursive(item, cb) {
fs.lstat(item, function(err, stats) {
if (!err && stats.isDirectory()) {
var total = stats.size;
fs.readdir(item, function(err, list) {
if (err) return cb(err);
async.forEach(
list,
function(diritem, callback) {
readSizeRecursive(path.join(item, diritem), function(err, size) {
total += size;
callback(err);
});
},
function(err) {
cb(err, total);
}
);
});
}
else {
cb(err);
}
});
}
A: 'use strict';
const async = require('async');
const fs = require('fs');
const path = require('path')
const getSize = (item, callback) => {
let totalSize = 0;
fs.lstat(item, (err, stats) => {
if (err) return callback(err);
if (stats.isDirectory()) {
fs.readdir(item, (err, list) => {
if (err) return callback(err);
async.each(list, (listItem, cb) => {
getSize(path.join(item, listItem), (err, size) => {
totalSize += size;
cb();
});
},
(err) => {
if (err) return callback(err);
callback(null, totalSize);
});
});
} else {
// Ensure fully asynchronous API
process.nextTick(function() {
callback(null, (totalSize += stats.size))
});
}
});
}
getSize('/Applications', (err, totalSize) => { if (!err) console.log(totalSize); });
A: I know I'm a bit late to the part but I though I'd include my solution which uses promises based on @maerics answer:
const fs = require('fs');
const Promise = require('bluebird');
var totalSizeBytes=0;
fs.readdir('storage', function(err, files) {
if (err) throw err;
Promise.mapSeries(files, function(file){
return new Promise((resolve, reject) => {
fs.stat('storage/' + file,function(err, stats) {
if (err) { throw err; }
if (stats.isFile()) { totalSizeBytes += stats.size; resolve(); }
});
})
}).then(()=>{
console.log(totalSizeBytes);
});
});
A: function readSizeRecursive(folder, nested = 0) {
return new Promise(function(resolve, reject) {
const stats = fs.lstatSync(path.resolve(__dirname, '../projects/', folder));
var total = stats.size;
const list = fs.readdirSync(path.resolve(__dirname, '../projects/', folder));
if(list.length > 0){
Promise.all(list.map(async li => {
const stat = await fs.lstatSync(path.resolve(__dirname, '../projects/', folder, li));
if(stat.isDirectory() && nested == 0){
const tt = await readSizeRecursive(folder, 1);
total += tt;
} else {
total += stat.size;
}
})).then(() => resolve(convertBytes(total)));
} else {
resolve(convertBytes(total));
}
});
}
const convertBytes = function(bytes) {
const sizes = ["Bytes", "KB", "MB", "GB", "TB"]
if (bytes == 0) {
return "n/a"
}
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)))
if (i == 0) {
return bytes + " " + sizes[i]
}
// return (bytes / Math.pow(1024, i)).toFixed(1) + " " + sizes[i]
return parseFloat((bytes / Math.pow(1024, i)).toFixed(1));
}
A: This combines async/await and the fs Promises API introduced in Node.js v14.0.0 for a clean, readable implementation:
const { readdir, stat } = require('fs/promises');
const dirSize = async directory => {
const files = await readdir( directory );
const stats = files.map( file => stat( path.join( directory, file ) ) );
let size = 0;
for await ( const stat of stats ) size += stat.size;
return size;
};
Usage:
const size = await dirSize( '/path/to/directory' );
console.log( size );
An shorter-but-less-readable alternative of the dirSize function would be:
const dirSize = async directory => {
const files = await readdir( directory );
const stats = files.map( file => stat( path.join( directory, file ) ) );
return ( await Promise.all( stats ) ).reduce( ( accumulator, { size } ) => accumulator + size, 0 );
}
A: A very simple synchronous solution that I implemented.
const fs = require("fs");
function getSize(path){
// Get the size of a file or folder recursively
let size = 0;
if(fs.statSync(path).isDirectory()){
const files = fs.readdirSync(path);
files.forEach(file => {
size += getSize(path + "/" + file);
});
}
else{
size += fs.statSync(path).size;
}
return size;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Which lightweight python web framework has applications and hot-deployed code I am used to PHP having applications. For example,
c:\xampp\htdocs\app1
c:\xampp\htdocs\app2
can be accessed as
localhost://app1/page.php
localhost://app2/page.php
Things to be noticed:
*
*a directory placed inside the www-root directory maps directly with the URL
*when a file/directory is added/removed/changed, the worker processes seamlessly reflect that change (new files are hot-deployed).
I am on the lookout for a mature python web framework. Its for a web API which will be deployed for multiple clients, and each copy will diverge on customization. And our workflow has frequent interaction/revision cycles between us and our clients. Hence the "drag and drop" deployment is a must.
Which python framework enables this? I prefer a lightweight solution (which doesnt impose MVC, ORMs etc)
Related
How to build Twisted servers which are able to do hot code swap in Python?
Python web hosting: Why are server restarts necessary?
fastcgi, cherrypy, and python
A: No mature python framework that I'm aware of allows you to map urls to python modules, and frankly, for good reason. You can do this with CGI, but it's definitely not the recommended way to deploy python apps. Setting that requirement aside, flask and bottle are both lightweight micro web-frameworks with similar approaches, both allow you to reload automatically when changes are detected (this is only wise during development).
A: There is no web framework in Python that I know of that lets you do that out of the box, but if you need it it's not to hard to add with a bit of convention over configuration.
Simply pick your web framework of choice in Python and then write a wrapper to the main application that walks a directory or set of directory and auto-registers routes from the modules inside of them. Have your modules do the same thing in their __init__.py files to the other files located with them. Then just set up your WSGI code to autoreload when the WSGI script is updated and your deployment during development simply becomes a two step process - add file then touch dev_app.wsgi. You could even add a real deployment option to this wrapper that walks a set up dev environment like this and generates hard-coded URL-to-function mappings for deployment.
However, all of this work isn't really necessary. Python is not PHP and the way you develop in one doesn't necessarily translate to the other well. If the client wants variable routes, use dynamic routes and give them (or you) an admin interface to control the mapping of content to URL. Use flat files, SQLite, a NoSQL datastore, or the ether to store these mappings and the content. Use a template engine like Jinja2, Mako, Cheetah or Genshi to maintain your general layout. Wrap this all up with an object oriented structure to make extending it easy (or use a functional paradigm if that comes more naturally to you). Or, drop the whole dynamic in production portion and generate flat HTML files a la Jekyll.
A: CherryPy is a mature web framework that redeploys automatically when changes are detected. The file structure - URL isn't there, but it is a lightweight framework that doesn't impose ORM, MVC, or even a templating engine.
A: If you are used to PHP, you might want to take a look at the Apache modules mod_python or mod_wsgi (and WSGI in general if you do web development -- which is the Pythonic way).
With those two modules, the Python interpreter gets started every time a request comes in (similar to PHP). Needless to say, this slows things down but you'll always get the result based on your newest code. Depending on your expected traffic numbers, this might or might not be okay for you.
BUT: If you decide to write your own framework, you most probably do not want to write a system that supports "hot-deploying". Even though the reload() command is built-in, it takes more than just that and will get you into a world full of pain.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to run Python on Bada? I'm starting developing to Bada platform. But C++ isn't my favorite language. So, is there any way to run Python on Bada?
Update: For Android there is a scpripting layer (SL4A), and it's make possible to quickly prototype applications for android on the device itself using high level scripting languages. Is there nothing like that for Bada?
Thanks.
A: Is it possible to use Python on Bada ?
In simple words No.
Applications must be written originally in C/C++/Objective-C . No third-party APIs, development tools or “code translators (e.g. from Python to C++) are allowed.
You can’t even compile very classic library such as OpenSSL or libCurl. The support of the STL is not complete
The Bada platform APIs are a lot more closed than Apple’s ones.
A: You can try with boost::python, but Im not sure if it will work in a proper way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Running both 32 bit and 64 bit unit test in TFS 2010 My project has both 32 bit and 64 bit components. THey have both managed and unmanaged components. I need to run unit test for both configuration. I also have separate set of different test files to deploy for each configuration, so I've been using deployment item using .testrunconfig. I saw you can force it to run in 32 bit or run in 64 bit is the machine is 64 bit. I suppose I could create 2 build definition one for 32 bit and 64 bit, but if it's possible I rather have one.
So is there a way to accomplish this with one build configuration ? How do you conditionally set the deployment item based on the configuration ?
A: Since you already have two different .testrunconfig files that specify the deployment items as well as whether tests should run in 32bit or 64 bit environment, you can add a second test to your build by editing your build definition from Visual Studio, choosing the Process tab and selecting the little "..." button to edit your tests (assuming you're using the Default Template). This will open the Automated Tests dialog window where you can add your tests a second time and specify your second testrunconfig.
IIRC if you're building multiple configurations/platforms in your Items to Build specification, this method will run all tests for all configurations, which may or may not be what you want. To run your x86 binaries in 32 bit test environment, and your x64 binaries in 64 bit, you will have to edit the Build process template accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Free Record / Replay solution for j2ee EJB layer I'm looking for a free (if possible) solution where:
*
* You can 'record' all the kinds of objects created during normal (production-like) usage of a webapp on an EJB application server (like Weblogic).
* Afterwards you can 'replay' each page separately on an non-EJB application server like Tomcat.
Moreover, it would be fantastic if:
*
* One could easily create test-suites from all the recorded scenarios and replay them in different browsers (to test regressions).
* One could modify or substitute single recorded objects (for example changing the fields of a map etc.) Changed objects can be saved and added into a test suite.
* It would be possible to integrate the solution with an IDE, optimally Eclipse.
I've tried googling and I've found Replay Solutions . Their product seems to be pretty well-suited to my requirements but
unfortunately it is paid and they don't even put pricing directly on the webpage (it's available after contacting the company).
Does anybody know such a solution or am I demanding too much?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how do i make addition of two fields in ssrs expression? I have generated one ssrs report
now i have two fields having values
1st field value is =Fields!FirstNO.Value
2nd field value is =Fields!SecondNO.Value
now i have one field average and i need to write expression like
average = (Fields!FirstNO.Value+Fields!SecondNO.Value) / (Fields!SecondNO.Value)
how can i write above in expression?? directly as i shown or any other syntax is there please help?
A: Are you sure these fields are numeric? Maybe try convert to numeric, like =cint(Fields!FirstNO.Value)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: defining the negative start parameter in substr as a variable Is using the following correct for defining the negative start parameter for a substr,
because its the only way i know how to get it to retur the correct result.
$start == (-44);
or
$start == (int) -44;
$pair = substr($str, $start, 4);
A: You can just add a - before an expression (including a variable) to invert its sign:
$pair = substr($str, -$start, 4);
Or
$pair = substr($str, -44, 4);
A: the substr call is valid, the only error in your code (posted here) is the == operator.
It should be:
$start = -44;
$pair = substr($str, $start, 4)
Also is the start value -44 the 44th character from start or the end. The above code considers -44 to mean 44th character from end of string.
One more error you could run into is if the length of $str is less than 44.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I integrate MakerClusterer with current Google Map? V3 I'm having trouble getting the MarkerClusterer into my current Google Map (which has taken a long time to get this far!!). How can I combine the two? I'm using V3 of the api.
Here's the MarkerClusterer code:
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var markers = [];
for (var i = 0; i < 100; i++) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var marker = new google.maps.Marker({'position': latLng});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
Update: I've attempted to add the clusterer to my current code but it doesn't seem to work. Places[i] doesn't seem to feed into the clusterer.
A: You just need to add each of your markers into an array, then after you've added them all, create the MarkerClusterer object
var markers = [];
// Adding a LatLng object for each city
for (var i = 0; i < marker_data1.length; i++) {
(function(i) {
geocoder.geocode( {'address': marker_data1[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
places[i] = results[0].geometry.location;
// Adding the markers
var marker = new google.maps.Marker({
position: places[i],
map: map,
title: 'Place number ' + i,
});
markers.push(marker);
// Creating the event listener. It now has access to the values of
// i and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
// Check to see if we already have an InfoWindow
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow
infowindow.setContent(marker_data[i]);
// Tying the InfoWindow to the marker
infowindow.open(map, marker);
});
// Extending the bounds object with each LatLng
bounds.extend(places[i]);
// Adjusting the map to new bounding box
map.fitBounds(bounds)
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
})(i);
}
var markerCluster = new MarkerClusterer(map, markers);
A: The problem was around the geocoding. Solved with A LOT of playing around:
for (var i = 0; i < address.length; i++) {
(function(i) {
geocoder.geocode( {'address': address[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
places[i] = results[0].geometry.location;
// Adding the markers
var marker = new google.maps.Marker({position: places[i]});
markers.push(marker);
//add the marker to the markerClusterer
markerCluster.addMarker(marker);
A: OK, here's a working solution. I basically stripped out things until it started to work. I think the problem might lie in the geocoder. Also you have a trailing comma at the end of var marker = new google.maps.Marker({position: places[i], map: map,}); when you create the markers, which will cause problems in IE. You'll notice I'm using coordinates instead of the geocoder (which I have no experience of), but it could be a conflict betweeen geocoder and markerclusterer?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> « Mediwales Mapping</title>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
p { font-family: Helvetica;}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
// Creating an object literal containing the properties we want to pass to the map
var options = {
zoom: 10,
center: new google.maps.LatLng(52.40, -3.61),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
// Creating an array that will contain the addresses
var places = [];
// Creating a variable that will hold the InfoWindow object
var infowindow;
var popup_content = ["<p>DTR Medical<\/p><img src=\"http:\/\/www.mediwales.com\/mapping\/wp-content\/uploads\/2011\/09\/dtr-logo.png\" \/><br \/><br \/><a href=\"http:\/\/www.mediwales.com\/mapping\/home\/dtr-medical\/\">View profile<\/a>","<p>MediWales<\/p><img src=\"http:\/\/www.mediwales.com\/mapping\/wp-content\/uploads\/2011\/09\/index.png\" \/><br \/><br \/><a href=\"http:\/\/www.mediwales.com\/mapping\/home\/mediwales\/\">View profile<\/a>","<p>Teamworks Design & Marketing<\/p><img src=\"http:\/\/www.mediwales.com\/mapping\/wp-content\/uploads\/2011\/09\/Teamworks-Design-Logo.png\" \/><br \/><br \/><a href=\"http:\/\/www.mediwales.com\/mapping\/home\/teamworks-design-and-marketing\/\">View profile<\/a>","<p>Acuitas Medical<\/p><img src=\"http:\/\/www.mediwales.com\/mapping\/wp-content\/uploads\/2011\/09\/acuitas-medical-logo.gif\" \/><br \/><br \/><a href=\"http:\/\/www.mediwales.com\/mapping\/home\/acuitas-medical\/\">View profile<\/a>","<p>Nightingale<\/p><img src=\"http:\/\/www.mediwales.com\/mapping\/wp-content\/uploads\/2011\/09\/Nightingale.png\" \/><br \/><br \/><a href=\"http:\/\/www.mediwales.com\/mapping\/home\/nightingale\/\">View profile<\/a>"];
var address = ["17 Clarion Court, Llansamlet, Swansea, SA6 8RF","7 Schooner Way, , Cardiff, CF10 4DZ","65 St Brides Rd, Aberkenfig, Bridgend, CF32 9RA","Kings Road, , Swansea, SA1 8PH","Unit 20 Abenbury Way, Wrexham Industrial Estate, Wrexham, LL13 9UG"];
var geocoder = new google.maps.Geocoder();
var markers = [];
var places = [
new google.maps.LatLng(53.077528,-2.978211),
new google.maps.LatLng(52.83264,-3.906555),
new google.maps.LatLng(51.508742,-3.259048),
new google.maps.LatLng(51.467697,-3.208923),
new google.maps.LatLng(51.628248,-3.923035)
];
// Adding a LatLng object for each city
for (var i = 0; i < address.length; i++) {
//places[i] = results[0].geometry.location;
// Adding the markers
var marker = new google.maps.Marker({position: places[i], map: map, draggable:true});
markers.push(marker);
// Creating the event listener. It now has access to the values of i and marker as they were during its creation
google.maps.event.addListener(marker, 'click', function() {
// Check to see if we already have an InfoWindow
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
// Setting the content of the InfoWindow
infowindow.setContent(popup_content[i]);
// Tying the InfoWindow to the marker
infowindow.open(map, marker);
});
// Extending the bounds object with each LatLng
bounds.extend(places[i]);
// Adjusting the map to new bounding box
map.fitBounds(bounds) ;
}
var markerCluster = new MarkerClusterer(map, markers, {
zoomOnClick: true,
averageCenter: true
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body class="home page page-id-1873 page-parent page-template page-template-page-php">
<div id="map_canvas"></div>
</body></html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: programmatically add a UIButton to rootview, what am I doing wrong? I have freshly setup app, just with a window an a root view (from the iOS single view application template, provided by XCode).
Now I try to add a button to it.
The according code looks like this:
- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIButton* button0 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button0.frame = CGRectMake(140, 230, 40, 20);
[button0 setTitle:@"Exit" forState:UIControlStateNormal];
[button0 addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
[self.viewController.view addSubview:button0];
if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
else
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
When I start the app, I can only see the empty view.
However, when comment out the line, which adds the view as root to the window and instead directly add the button to the window, then I can see the button just fine.
So why isn't this working with the view?
A: The problem is that, you are adding button0 as subview of self.viewController.view even before allocating the viewController.
By the time you call addSubview: method, self.viewController is nil. So, the button is not added to the viewController. You should add the button after you allocate the viewController.
self.viewController = [[ViewController alloc]...
[self.viewController.view addSubview:button0];
A: At first, create the root viewcontroller, later add subviews to it. You did it the other way round.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FTP SocketTimeoutException even with using passive mode We are using commons-net-1.4.1.jar and java5_64 on AIX. I am getting the following exception on listing files on an FTP server.
java.net.SocketTimeoutException: Accept timed out
at java.net.PlainSocketImpl.socketAccept(Native Method)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:427)
at java.net.ServerSocket.implAccept(ServerSocket.java:466)
at java.net.ServerSocket.accept(ServerSocket.java:434)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:502)
at org.apache.commons.net.ftp.FTPClient.listFiles(FTPClient.java:2488)
This error is intermittent as the process runs around 60 times a day and I'm getting the error 2 or 3 times, the rest of the time it runs fine.
I found a possible solution on the internet of changing the connection mode from active to passive, however this is not helping either.
Could you please help me, I don't know what may be the cause.
A: the remote server you are trying to list files from is simply not responding... (which is a fairly common case). either their internet connection is down at this moment, or your own internet connection is down, or the server is saturated and refusing connections, or whatever may be the case.
(do you properly close the connection to the server each time the process succeeds ? the server may be refusing the connection because it thinks you are already connected)
A: If everything is correct in connection i.e Passive and ASCII as per server, and still you are getting socket timeout then increase the time in connection under ftpClient.setTimeout(220);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "Operation not permitted" on using os.setuid( ) [python] I'm trying to build a platform to launch some scripts. This scripts are placed in home folder of each user. Every launch should be done with each user id so, I'm doing, for each user, this:
user_id = pwd.getpwnam( user )[ 3 ]
user_home = pwd.getpwnam( user )[ 5 ]
os.chdir( user_home )
os.setuid( user_id )
subprocess.Popen( shlex.split( "user_script.py" ) )
But, when python trys to do os.setuid( user_id ) it raise this exception:
Traceback (most recent call last):
File "launcher.py", line XX, in <module>
OSError: [Errno 1] Operation not permitted
By the way, the user who starts this script is in the root group (on GNU/linux OS) and it has all the root privileges.
If I try to launch the same code with root user I get a different error:
OSError: [Errno 13] Permission denied
If someone can help me to understand what's happening please...
A: Only root can do a setuid, being in the root-group is not enough.
A: Only superuser can change uid whenever it feels like it, just adding the user to the root group is not enough.
setuid(2) for example mentions:
The setuid() system call is permitted if the specified ID is equal to the
real user ID or the effective user ID of the process, or if the effective
user ID is that of the super user.
On Linux, there's also:
Under Linux, setuid() is implemented like the POSIX version with the
_POSIX_SAVED_IDS feature. This allows a set-user-ID (other than root)
program to drop all of its user privileges, do some un-privileged work, and
then reengage the original effective user ID in a secure manner.
I don't even know if Python directly implements this, but it's not exactly what you want anyway.
So the short answer is: Start the initial process as root.
If you're worried about security, start two processes, one as root, one as non-privileged user, and have the non-privileged process communicate with the root process with a socket. This is a more advanced setup though...
A: OSError: [Errno 1] Operation not permitted indicates the user who starts the script has insufficient privileges. Being in the root group is not enough, it actually needs the CAP_SETUID capability.
OSError: [Errno 13] Permission denied is probably an unrelated error. You should have a look at its stacktrace.
A: The line
subprocess.Popen( shlex.split( "user_script.py" ) )
confuses me in manifold ways.
*
*The shlex.split() seems to be redundant, as there is nothing to split.
*Better put Popen()'s parameter in a list.
*If user_script.py has no execute permissions, even root cannot do that.
A: you also use setuid permission . That is give ,
chmod 4755 script.py
Now even from normal user if you execute the program it will switch as that particular use. You won't get any permission issues .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Issue with respond time loader I am usign jquery ajax method to send data to another page. But issue is I want to show response loader while fetching result from other page. I have id of img is #ajaxloader. BUt issue is when I show it, it continue to respond. that is if result is fetched its not hiding loader...I got script from google... but as I am sending data though $.post(), jquery method.
What should I replace for, .ajaxsend and .ajaxStop.
$().ajaxSend( function( r, s ) {
$("#ajaxloader").show();
});
$().ajaxStop( function( r, s ) {
$("#ajaxloader").fadeOut();
});
A: Use the success callback in $.post instead:
$('#ajaxloader').show();
$.post(url, data, function() {
$('#ajaxloader').fadeOut();
});
http://api.jquery.com/jQuery.post/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What major ASIHTTPRequest features is AFNetworking missing? With work having recently stopped on ASIHTTPRequest, it seems like attention is shifting to AFNetworking.
However, I've not yet found a good comparison of the features of the two libraries, so I don't know what I might lose if/when I switch over.
Major differences I've spotted so far are:
*
*AFNetworking has a much smaller code size (which is good)
*AFNetworking is being rapidly improved (so it may not yet be mature, may not have a stable API yet?)
*Both seem to have caching, though I've seen hints that because AFNetworking uses NSURLConnection it won't cache objects over 50K
*ASIHTTPRequest has very good support for manual & automatic (PAC) http proxies; I can't find any information on what level of support AFNetworking has for proxies
*AFNetworking requires iOS 4+, whereas ASIHTTPRequest works right back to iOS 2 (not really an issue for me, but it is an issue for some people)
*AFNetworking doesn't (yet) have a built in persistent cache, but there's a persistent cache which has a pending pull request: https://github.com/gowalla/AFNetworking/pull/25
Has anyone seen any good comparisons of the two libraries or any documented experiences of switching from one to the other?
A: I loved ASIHTTPRequest and I was sad to see it go. However, the developer of ASI was right, ASIHTTPRequest has become so large and bloated that even he couldn't devote time to bring it to par with newest features of iOS and other frameworks. I moved on and now use AFNetworking.
That said, I must say that AFNetworking is much more unstable than ASIHTTP, and for the things I use it for, it needs refinement.
I often need to make HTTP requests to 100 HTTP sources before I display my results on screen, and I have put AFHTTPNetworkOperation into an operation queue. Before all results are downloaded, I want to be able to cancel all operations inside the operation queue and then dismiss the view controller that holds the results.
That doesn't always work.
I get crashes at random times with AFNetworking, while with ASIHTTPRequest, this operations were working flawlessly. I wish I could say which specific part of AFNetworking is crashing, as it keeps crashing at different points (however, most of these times the debugger points to the NSRunLoop that creates an NSURLConnection object). So, AFNetworking needs to mature in order to be considered as complete as ASIHTTPRequest was.
Also, ASIHTTPRequests supports client authentication, which AFNetworking lacks at the moment. The only way to implement it is to subclass AFHTTPRequestOperation and to override NSURLConnection's authentication methods. However, if you start getting involved with NSURLConnection, you will notice that putting NSURLConnection inside an NSOperation wrapper and writing completion blocks isn't so hard as it sounds and you will start thinking what keeps you from dumping 3rd party libraries.
ASI uses a whole different approach, since it uses CFNetworking (lower-level foundation frameworks based on C) to make downloading and file uploading possible, skipping NSURLConnection completely, and touching concepts most of us OS X and iOS developers are too afraid to. Because of this, you get better file uploading and downloading, even web page caches.
Which do i prefer? It's hard to say. If AFNetworking matures enough, I will like it more than ASI. Until then, I can't help but admire ASI, and the way it became one of the most used frameworks of all time for OS X and iOS.
EDIT:
I think it's time to update this answer, as things have changed a bit after this post.
This post was written some time ago, and AFNetworking has matured enough. 1-2 months ago AF posted a small update for POST operations that was my last complaint about the framework (a small line ending fault was the reason that echonest uploads failed with AF but were completed fine with ASI). Authentication is not an issue with AFnetworking, as for complex authentication methods you can subclass the operation and make your own calls and AFHTTPClient makes basic authentication a piece of cake. By subclassing AFHTTPClient you can make an entire service consumer in little time.
Not to mention the absolutely necessary UIImage additions that AFNetworking offers. With blocks and custom completion blocks and some clever algorithm, you can make table views with asynchronous image downloading and cell filling pretty easily, whereas in ASI you had to make operation queues for bandwidth throttling and mind yourself to cancel and resume the operation queue according to table view visibility, and stuff like that. Development time of such operations has been halved.
I also love the success and failure blocks. ASI has only a completion block (which is actually the completion block of NSOperation). You had to check whether you had an error on completion and act accordingly. For complex web services, you could get lost in all the "ifs" and "elses"; In AFNetworking, things are much more simple and intuitive.
ASI was great for its time, but with AF you can change the way you handle web services completely in a good way, and make scalable applications more easily. I really believe that there is no reason whatsoever to stick with ASI anymore, unless you want to target iOS 3 and below.
A: AFNetworking doesn't support clientCertificateIdentity and clientCertificates for TLS client authentication.
We can do that with the - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge method in a subclass of AFURLConnectionOperation but it's not as easy.
A: I've been using ASI* for a while now and I absolutely love the fileupload approach of ASI, and though I am excited to jump to AFNetworking, fileupload support in AfNetworking is not as easy to use compared to ASI*.
A: Until now I couldn't figure out how to set a timeout with AFNetworking when doing a synchronous POST request. UPDATE: I finally figured out: https://stackoverflow.com/a/8774125/601466
Now switching to AFNetworking : ]
==================
Apple overrides the timeout for a POST, setting it to 240 seconds (in case it was set shorter then the 240 seconds), and you can't change it. With ASIHTTP you just set a timeout and it works.
A code example with a synchronous POST request:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"doSomething", @"task",
@"foo", @"bar",
nil];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:baseURL]];
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:requestURL parameters:params];
[httpClient release];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NDLog(@"fail! %@", [error localizedDescription]);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
[queue addOperation:operation];
[queue waitUntilAllOperationsAreFinished]; // Stuck here for at least 240 seconds!
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
if (![[operation responseString] isEqualToString:@""]) {
return [operation responseString];
}
return nil;
I tried to set a timeout here, but nothing worked. This issue keeps me from migrating to AFNetworking.
See also here: How to set a timeout with AFNetworking
A: AFNetwork lacks the ability to upload large files. It assumes file content is in RAM.
ASI was smart enough to simply stream file content from disk.
A: Just finishing up a project where I'm using AFNetworking instead of ASI. Have used ASI on previous projects; it's been a great help in the past.
Here's what AFNetworking is missing (as of today) that you should know about:
*
*Nothing
ASI is going away. Use AF now. It's small, it works, and it's going to continue to be supported. It's also organized more logically, especially for API clients. It has a number of great classes for oft-used special cases like asynchronous loading of images in table views.
A: In ASIHTTP I loved that I could attach a userinfo dictionary to individual requests. As far as I see there is no direct support for this in AFHTTPRequestOperation. Has anyone come up with an elegant workaround yet? Apart from the trivial subclassing of course.
A: AFNetworking works with "blocks" which is more natural for me than working with delegates like ASIHTTPRequest does.
Working with blocks it's like working with Anonymous Function in javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "93"
} |
Q: Unable to access _POST values PHP Find below my form and the action page it submits to. The _POST array is empty. Not sure how. Please help.
index.php
<form method="post" action="track-them.php">
<input type="text" width="255" id="txt" />
<textarea id="ta" type="text" cols="25" rows="4"></textarea>
<input type="submit" id="check-button" value="Ok" />
</form>
track-them.php
<?php
include_once('../simple_html_dom.php');
print_r($_POST);
?>
Both fields txt & ta have values but the output I see when I click submit is:
Array ( )
A: Give your inputs a name. The browser passes the name attribute not the id.
A: Add name attribute to your form elements:
<form method="post" action="track-them.php">
<input type="txt" width="255" id="myurl" name="myurl" />
<textarea id="ta" name="ta" type="text" cols="25" rows="4"></textarea>
<input type="submit" id="check-button" value="Ok" />
</form>
A: If you put the print_r($_POST) above the inclution what is the result ?
A: Please add name attribute for each from element
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git global ignore not working I've created the file .gitignore_global and put it in my git install directory. When I run the command:
git config --global core.excludesfile ~/.gitignore
the rules in the ignore file do not get applied to my commits.
When I rename the file .gitignore and put it in my project root, the rules do apply.
What is wrong here?
A: The file must be in your home directory. On windows, it usually means:
C:\documents and settings\[user].
On linux it is:
/home/[user]
A: I had this problem because I had initially called 'git config core.excludefiles' without --global and with a wrong value, and hence it had stored the property locally. Looks like the local property hid the global one (which had the correct value), completely ignoring it.
A: Also I had a funny thing with encoding of this file. Somehow my Windows 10 (with Powershell) created the file with the encoding "UTF-16 LE" and somehow Git couldn't handle this. When I change the encoding to a much more sensible value of literally anything else it worked.
A: Adding another thing ppl might have missed, or at least where I went wrong.
I made the mistake of not copy-pasting the command and I spelled
excludefile (wrong)
instead of
excludesfile (right)
and lost definitely half an hour or so before I reevaluated the spelling, thinking it was something else.
You don't get a warning or error for setting an option that is not a valid option. You do get a warning/error message if the syntax is invalid, which is why I wrongly assumed that a spelling mistake would be caught the same way.
A: Maybe you need to do:
git config --global core.excludesfile ~/.gitignore_global
And to have some coffee.
A: Another reason a global git ignore may not be working: invisible characters in the path.
I only found out this was my problem when pasting the warning message from git-check-ignore into the address bar of Chrome, where it luckily became visible:
(It wasn't visible on the terminal. And this could have been a long rabbit hole of debugging...)
A: I found that when I had defined the global core.excludesfile like this:
git config --global core.excludesfile $HOME/.config/git/ignore
it didn't work. Changing it to not use the $HOME variable, like this:
git config --global core.excludesfile ~/.config/git/ignore
it immediately started working. Hope this helps someone else.
FYI:
$ git --version
git version 1.7.10.2 (Apple Git-33)
A: Thought I would chip in on this. There is another reason why the global ignore file appears not to be working. It's something that I don't think has been covered in earlier answers. It's so blindingly obvious that - of course - it's very easy to miss.
It is, that git will only ignore new files. If the file is already being tracked by git, then of course git will not ignore it! So whatever patterns in any gitignore or exclude file do not apply.
That makes sense. Why would git want to ignore modifications to files it is already tracking? If the file is to be ignored, you must first tell git not to track it, then git ignore it as described in the manual. For info on how to untrack files, see this answer.
This all leads me to ask, is it possible to ignore changes to tracked files? Again, git delivers. This answer; Git: Ignore tracked files gives us the command (replace file with the file you want to ignore):
git update-index --assume-unchanged file
Finally, here's some additional info on debugging git ignore.
The gitignore(5) Manual Page tells us:
Patterns which a user wants Git to ignore in all situations (e.g., backup or temporary files generated by the user's editor of choice) generally go into a file specified by core.excludesfile in the user's ~/.gitconfig. Its default value is $XDG_CONFIG_HOME/git/ignore. If $XDG_CONFIG_HOME is either not set or empty, $HOME/.config/git/ignore is used instead.
So, this is new and replaces the previous ~/.gitignore_global mentioned previously.
Next, and this is really useful, is that as of 1.8.2, we now have some excellent debugging tools. Have a look at:
Git Learns to Ignore Better - New in 1.8.2
This shows how to use the new check-ignore flag to verify that git is successfully ignoring your patterns, e.g.
git check-ignore bin/a.dll --verbose
A: Note: starting git1.7.12 (August 2012):
The value of:
*
*core.attributesfile defaults to $HOME/.config/git/attributes and
*core.excludesfile defaults to $HOME/.config/git/ignore respectively when these files exist.
So if you create a $HOME/.config/git/attributes file, you don't even have to set your core.excludesfile setting.
A: I was having the same problem (on Windows). I ended up checking my ~/.gitconfig file and found that my excludesfile was set to:
excludesfile = C:\\Users\\myUserName\\Documents\\gitignore_global.txt
but it should have been:
excludesfile = C:\\Users\\myUserName\\.gitignore_global
After I changed it, everything worked as it should.
A: Another hard to track reason why .gitignore(_global) appears not working could be leading spaces in the lines. The file is not forgiving for leading spaces. So make sure each line of your file doesn't have any unless it's blank line. It took me a while to figure out.
Just adding my two cents.
A: I recently made a mistake and run the following command
git config core.excludesfile tags
this changed the excludesfile path to a local file in the current repository, and this config has been written to the local config file under .git/config, so to fix that I just opened the .git/config file and deleted the line excludesfile tags and everything is back to normal.
A: A problem I was running into is that I tried putting INLINE comments in my global git ignore.
For example this does NOT work:
.DS_Store # from macOS Finder
This DOES work:
# from macOS Finder
.DS_Store
A: I had this problem when using Cygwin with Windows Git. I had forgotten to include Git from Cygwin. When I added Git to my Cygwin software base, the problem went away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "108"
} |
Q: recursion through hashes in ruby I'm doing a bit of recursion through hashes to build attr_accessor and class instances.
I get all of the value from a main hash.
I use it to describe an event (dance class and club) and I'd like to be able to store the info like this:
data = {:datetime => '2011-11-23', :duration => '90', :lesson => {:price => '£7', :level => 'all'}, :club => {:price => "4"}
so that I can easily retrieve lesson[:price] and club[:price].
With the recursion that I have in place, I check every item of the main hash to see if the value is a hash. If it is I restart the recursion and populate all of the values.
The problem is that I can't have 2 variables of the same name as lesson[:price] collides with club[:price].
This is the recursion:
class Event
#attr_reader :datetime, :duration, :class, :price, :level
def init(data, recursion)
data.each do |name, value|
if value.is_a? Hash
init(value, recursion+1)
else
instance_variable_set("@#{name}", value)
self.class.send(:attr_accessor, name)
end
end
end
It skip the lesson and club level and add all of their inner values to the instance list.
Is it possible to actually append the name of skipped level so that I can access it through my_class.lesson.price, myclass.club.price instead of myclass.price
A: You will have to change the API you use currently. Here is the corrected code:
class Event
#attr_reader :datetime, :duration, :class, :price, :level
def init(data, stack = [])
data.each do |name, value|
if value.is_a? Hash
init(value, stack << name.to_s)
stack.pop
else
new_name = stack.empty? ? name : stack.join("_") + "_" + name.to_s
instance_variable_set("@#{new_name}", value)
self.class.send(:attr_accessor, new_name)
end
end
end
end
It is the following idea:
*
*Replace recursion it is not used anyway with a stack for the keys used.
*Every time, you go into the recursion, the stack is appended the new key.
*Every time, the recursion is left, the stack is reduced (by using pop).
The code for appending the things together is ugly, but it works. The output after using your example data:
irb(main):042:0> e.init(data)
=> {:datetime=>"2011-11-23", :duration=>"90", :lesson=>{:price=>"7", :level=>"all"}, :club=>{:price=>"4"}}
irb(main):043:0> e
=> #<Event:0x2628360 @datetime="2011-11-23", @duration="90", @lesson_price="7", @lesson_level="all", @club_price="4">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to mimic skinned java swing with .net means? Question in short:
What is the easiest way to mimic a swing based (skinned, customized) java GUI with .NET means?
Question explained:
Our main app has a swing based skinned (and customized) java GUI.
Apart from that we are going to build some smaller GUI equipped tools. Some of them will be .NET based windows applications with a windows forms GUI.
Now, to get a uniform user experience the GUIs of these .NET tools should be as close to our java based GUI as possible in both appearence and handling.
What is the easiest way to accomplish this?
A:
What is the easiest way to accomplish this?
The easiest way to get a uniform Swing / Swing-like user interface is to implement everything in Java and Swing.
I've not heard of a Swing look-alike UI library for .NET. I guess it is theoretically possible, but it would be a lot of effort: probably orders of magnitude more work than implementing the tools the easy way.
So your practical alternatives are 1) implement the new tools in Java / Swing, 2) reimplement the old tools in .NET, or 3) forget about having a common UI look-and-feel.
This is not a joke answer ...
A: Try Windows Presentation Foundation (WPF) Themes instead WinForms as allow to change the controls Look & Feel. I think is not as easy and pluggable like Swing but could serve as an starting point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS SDK: Feed Dialog without authorize gets send to facebook home page I ran into an interesting bug and just want to know if anyone did experience the same problem (since I couldn't find anything about it after 2h of google):
I initalize the facebook SDK (newest Version 23. Sept 2011) like this:
facebook = [[Facebook alloc] initWithAppId:FACEBOOK_APP_ID andDelegate:self];
Afterwards, I want to send some information to the users Wall without the authorization dialog:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
FACEBOOK_APP_ID, @"app_id",
@"http://itunes.apple.com/de/app/idxyz", @"link",
@"http://example.com/app_icon90px_d_p_i_g.png", @"picture",
@"AppName", @"name",
@"awesome new App. Look at it. Yadda Yadda Yadda", @"caption",
@"Here's an even more interesting description", @"description",
nil];
[facebook dialog:@"feed"
andParams:params
andDelegate:self];
What happens: The Facebook dialog opens and asks for the user email and password. Cool, everythings fine till yet. But if I provide the system with my email and password it doesn't change back to the post-to-wall dialog but instead shows the facebook user/home page. If you abort the dialog now and recall the method above, it goes directly to the feed-dialoge. The workaround to authenticate the app with facebook first is no solution :-(
A: It's May 2012 now and I experienced similar problem where the user already authenticated via SSO but when I call the feed dialog, it pops up the web modal with a login page instead of the normal feed dialog.
Turn out it's Facebook server issue and I can't reproduce the issue again after that hair-pulling one day debug.
More details:
I don't request for offline_access because it is going to be deprecated in July. So at first I thought that's the reason why my session expired and I checked everything regarding automatic extending the token in applicationDidBecomeActive. But the problem still exists.
I then even print out the token and check the validity of the token using graph.facebook.com/me/permissions call on the browser!
A few times during that day, the dialog just return an error saying "There's error, try again later". So that's when I decided to leave it and try again the next day and it just worked!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to do SQL join effectively? I have two tables.
*
*Order
*Replication.
A single order record can have multiple Replication records. I want to join these two tables, such that i always retrieve a single record out of the join even if multiple records exist.
Sample data
Replication table:
ORDID | STATUS | ID | ERRORMSG | HTTPSTATUS | DELIVERYCNT
=========================================================
1717410307 1 JBM-9e92ae0c NULL 200 1
----------
1717410307 1 JBM-9fb59af1 NULL 400 -99
----------
1717410308 1 JBM-0764b091 NULL 403 1
----------
1717410308 1 JBM-0764b091 NULL 200 1
Order Table:
ORDID | ORDTYPE | DATE
----------
1717410307 CAR 22-SEP-2011
1717410308 BUS 23-SEP-2011
How can i make a join effectively so as , i will get as many records in order table and a replication table that should be dynamically selected on a priority basis.
The priority can be defined as :
*
*Any record with a delivery count of -99
*HTTPSTATUS != 200
Please guide me how can i proceed with this joining?
Please let me know if you need any clarification.
Your help is much appreciated!
A: Is it possible to use ORDER BY clause based on the HTTPSTATUS and DELIVERYCNT?
In that case you can write a specific ORDER BY and getting the TOP 1 from it (don't know which RDBMS do you use) or getting ROW_NUMBER() OVER (ORDER BY ... ) AS RowN WHERE RowN = 1
But this is the ugly (yet quick) solution.
The other option is to make a subquery where you add a new column which will make the priority calculation.
To make the query effective you should consider indexing (or using RDBMS specific solutions like included columns)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to widen up the sound wave in AS3? I am implementing this code for drawing the sound wave. It is in the adobe livedocs at soundmixer . My problem is how to widen up the sound wave? For example I would like it to be 655 pixels. I can change it to draw to different channels and also change the height of the drawing but cannot find how to change the width of the whole drawing
Any idea how to do that?
Thanks.
package {
import flash.display.Sprite;
import flash.display.Graphics;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.text.TextField;
public class SoundMixer_computeSpectrumExample extends Sprite {
public function SoundMixer_computeSpectrumExample() {
var snd:Sound = new Sound();
var req:URLRequest = new URLRequest("Song1.mp3");
snd.load(req);
var channel:SoundChannel;
channel = snd.play();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
}
private function onEnterFrame(event:Event):void {
var bytes:ByteArray = new ByteArray();
const PLOT_HEIGHT:int = 25;
const CHANNEL_LENGTH:int = 256;
SoundMixer.computeSpectrum(bytes, false, 0);
var g:Graphics = this.graphics;
g.clear();
g.lineStyle(0, 0x6600CC);
g.beginFill(0x6600CC);
g.moveTo(0, PLOT_HEIGHT);
var n:Number = 0;
for (var i:int = 0; i < CHANNEL_LENGTH; i++) {
n = (bytes.readFloat() * PLOT_HEIGHT);
g.lineTo(i * 2, PLOT_HEIGHT - n);
}
g.lineTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);
g.endFill();
g.lineStyle(0, 0xCC0066);
g.beginFill(0xCC0066, 0.5);
g.moveTo(CHANNEL_LENGTH * 2, PLOT_HEIGHT);
for (i = CHANNEL_LENGTH; i > 0; i--) {
n = (bytes.readFloat() * PLOT_HEIGHT);
g.lineTo(i * 2, PLOT_HEIGHT - n);
}
g.lineTo(0, PLOT_HEIGHT);
g.endFill();
}
private function onPlaybackComplete(event:Event):void {
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
}
}
A: change the x factor in your lineTo(x,y) calls.
for example, change:
g.lineTo(i * 2, PLOT_HEIGHT - n);
to something like:
var xfactor:Number = 655/256;
g.lineTo(i * xfactor, PLOT_HEIGHT - n);
since xfactor is fixed, calculate it before you enter your loops (not within them(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamic assembly selection and loading in runtime I have an application that has reference to Microsoft.Data.SqlXml.dll assembly (part of SQLXML). But on different machines, depending on whether it's live environment or test, or developers local PC, different versions of SQLXML are installed. This arises an issue: depending on destination machine I have to compile application against correct Microsoft.Data.SqlXml.dll assembly.
In Subversion I keep csproj and dll file that is used on live environment. When I have to test modules that take advantage of Microsoft.Data.SqlXml.dll locally, I change reference in project, and revert them back. But several times I forgot to rollback changes and I checked in csproj and Microsoft.Data.SqlXml.dll with version that didn't comply with SQLXML installed on live server. As a result, I received runtime errors.
My question is: is there any way to dynamically load assemblies in runtime? I can have switch statement somewhere in application that would load correct assembly depending on entry in app.config (eg. env="live|test|local") ? Or perhaps there is another way to address this issue?
Thanks,Pawel
A: From Microsoft page:
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
private Assembly MyResolveEventHandler(object sender,ResolveEventArgs args)
{
//This handler is called only when the common language runtime tries to bind to the assembly and fails.
//Retrieve the list of referenced assemblies in an array of AssemblyName.
Assembly MyAssembly,objExecutingAssemblies;
string strTempAssmbPath="";
objExecutingAssemblies=Assembly.GetExecutingAssembly();
AssemblyName [] arrReferencedAssmbNames=objExecutingAssemblies.GetReferencedAssemblies();
//Loop through the array of referenced assembly names.
foreach(AssemblyName strAssmbName in arrReferencedAssmbNames)
{
//Check for the assembly names that have raised the "AssemblyResolve" event.
if(strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(","))==args.Name.Substring(0, args.Name.IndexOf(",")))
{
//Build the path of the assembly from where it has to be loaded.
strTempAssmbPath="C:\\Myassemblies\\"+args.Name.Substring(0,args.Name.IndexOf(","))+".dll";
break;
}
}
//Load the assembly from the specified path.
MyAssembly = Assembly.LoadFrom(strTempAssmbPath);
//Return the loaded assembly.
return MyAssembly;
}
Naturally you have to change the part //Build the path of the assembly using what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to get a word count on word document in python? I am trying to get the word counts of .doc .docx .odt and .pdf type files.
This is pretty simple for .txt files but how can I go about doing a word count on the mentioned types?
I'm using python django on Ubuntu and trying to word count the documents words when a user uploads a file through the system.
A: First you need to read your .doc .docx .odt and .pdf.
Second, count the words (<2.7 version).
A: Given that you can do this for .txt files I'll assume that you know how to count the words, and that you just need to know how to read the various file types. Take a look at these libraries:
PDF: pypdf
doc/docx: this question, python-docx
odt: examples here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Telerik MVC grid problems Ok, Telerik has some good visual appealing controls, but it damn hard to use and too diferent from html programming.
My problem:
I had in my page a grid with ajax turned on. So sorting, paging.. are made with ajax calls to my controllers.
In this page there is a link to open a window (telerik one..), this windows is opened with this javascript code:
$(".bs-icon").live("click", function () {
var windowElement = $.telerik.window.create({
Name: "myWindow",
title: "Pesquisa",
modal: true,
resizable: false,
draggable: true,
scrollable: false,
visible: false,
width: 500,
height: 400,
onClose: function () { }
});
var w = windowElement.data("tWindow");
w.ajaxRequest("Alerts/IndexLookup/");
w.center().open();
});
In this window there is another grid, but I can´t get the ajax to work with this second grid. Something is turned off and I don´t know what it is.
Thanks.
Changed the javascript to this:
$.get("/AlertaGeral/IndexLookup",
function (response) {
$("#form-temp").html(response);
});
return false;
to get off telerik windows. Same problem.
The grid that comes from ajax request does not works properly. Maybe some setup is missing after including it in the page.
Here is AlertaGeralController:
public ActionResult IndexLookup(Consulta.FiltroPadrao filtro = null)
{
if (Session["token"] == null)
return RedirectToAction("Index", "Home");
if (filtro == null)
filtro = new Consulta.FiltroPadrao { Descricao = null };
ResultadoPadrao[] registros = consulta.Pesquisar(Session["token"].ToString(), "SamAlertageral", filtro);
Session["ultimoFiltro"] = filtro;
return PartialView("_GridPesquisaLookup", registros);
}
and the view _GridPesquisaLookup.cshtml:
@model Benner.Saude.Consulta.ResultadoPadrao[]
@(Html.Telerik().Grid(Model)
.Name("Grid")
.DataKeys(keys => keys.Add(c => c.Handle))
.DataBinding(dataBinding => dataBinding
.Ajax()
.Select("AjaxPesquisarLookup", "AlertaGeral")
)
.HtmlAttributes(new { @class = "grid-padrao" })
.ClientEvents(events => events
.OnDataBound("atualizarCss")
.OnRowSelect("selecionarRegistro")
)
.Columns(columns =>
{
columns.Bound("Descricao").Title("Descrição");
columns.Bound("Handle").Title("Código");
})
.Pageable()
.Sortable()
)
A: I think you have a conflic somewhere in your View. Here something you can do to find your problem:
Create a View that will only show your _GridPesquisaLookup.cshtml without any ajax. That way, you will be able to test ONLY this grid. Use Html.Partial("_GridPesquisaLookup") in your View.
*
*If the grid work, its because there's a conflic with the other View when you use two grids at the same time. Maybe the two grids have the same name. It happened to me a few months ago and i had the same problem as you.
*If the grid does'nt work, well you will know that your problem is from this grid. You will have to do more tests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL How To Use Main Select Value As Subquery Argument? I am trying to construct a query that is a bit more complicated than anything I've done in my limited experience with databases.
TABLE:
id - data - type - data3
1 - hello - 1 - 1
2 - goodbye - 1 - 1
3 - goodbye - 1 - 2
4 - goodbye - 2 - 1
5 - hello - 2 - 1
The goal is to do 4 things:
*
*GROUP the results by "data", but only return one result/row of each
data type.
*COUNT the total number of each "data GROUP and return this number.
*Do this for both "type"=1 and "type"=2, though I only need each
"data" GROUP item once.
*the ability to sort results based on each SELECT item.
So the final result returned should be (sorry to be confusing!):
data, COUNT(data["type"]=1), COUNT(data["type"]=2 AND data["data"] = data)
So, for the sample table above, desired results would be:
loop 1 - hello, 2, 1
loop 2 - goodbye, 3, 1
Then, ideally, I could sort results by any of these.
This is the query I was trying to construct before resorting to posting this, I don't think it's even close to being correct, but it may help illustrate what I'm trying to achieve a bit better:
SELECT
(
SELECT `clicks_network_subid_data`, COUNT(*)
FROM track_clicks
WHERE `clicks_campaign_id`='$id' AND `clicks_click_type` = '1'
) AS keywords,
(
SELECT COUNT(*)
FROM track_clicks
WHERE `clicks_campaign_id`='$id' AND `clicks_click_type` = '2' AND `clicks_network_subid_data` = keywords.clicks_network_subid_data
) AS offer_clicks
GROUP BY keywords.clicks_network_subid_data
ORDER BY keywords.COUNT(*) DESC
I also need to do a JOIN on another table to grab one more piece of data, but I think I can handle that once I get this part figured out.
A: You can use an IF-function for this
SELECT `clicks_network_subid_data`,
SUM(IF(clicks_click_type` == '1',1,0)) as keywords,
SUM(IF(clicks_click_type` == '2',1,0)) as offer_clicks,
FROM track_clicks
GROUP BY clicks_network_subid_data
ORDER BY clicks_network_subid_data DESC
A: You can do this using GROUP BY:
SELECT data, COUNT(*) AS cnt FROM `table` GROUP BY type ORDER BY COUNT(*)
Ordering might become a little slow, as this is a calculated field, but if you don't have a large result set then you are good to go.
A: First of all your question is bit not clear , However, check this query . what I suspect is that you need count results in columns (single ) instead of rows .
select * , count(type_one) as t1_count , count(type_two) as t2_count from (
select data,if(tmp.type=1,1,0) as type_one, if(tmp.type=2,1,0) as type_two from (
select 1 as id , 'hello' as data , 1 as type , 1 as data3 union
select 2 as id , 'goodbye' as data , 1 as type , 1 as data3 union
select 3 as id , 'goodbye' as data , 1 as type , 2 as data3 union
select 4 as id , 'goodbye' as data , 2 as type , 1 as data3 union
select 5 as id , 'hello' as data , 2 as type , 1 as data3
) tmp
) tmp2
group by tmp2.type_one ;
let me know if this works for you
cheers :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jQuery document ready after ajax request I'm having problems with updating elements that are not ready after an ajax request.
If I run my myFunction() function on page load like so:
$(function() {
myFunction();
}
I have no problems at all. But if I then use something like
$.ajax({
url: this.href,
dataType: "script",
complete: function(xhr, status) {
myFunction();
}
});
which returns $(".myElement").replaceWith("htmlHere"). The elements are simply not ready when the complete event fires. If I set a delay in there it works fine again.
Is there any other event that gets fired other than 'complete' when the DOM is ready?
Update:
Here's the actual code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
myFunction();
});
function myFunction() {
// Modify the dom in here
}
The missing ); was just a typo on my part.
Ive tried using success now instead of complete and it doesn't appear to make any difference.
A: I have set up a jsfiddle based on your code, and it seems to be working.
This is the current code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
});
function myFunction() {
$("span").replaceWith("<p>test</p>");
}
And it replaces span tag with a paragraph. Please check it and compare with your code. If it is the same, then your problem somewhere other than this function (maybe in myFunction?).
A: You can use $(document).ready(function() { ... }); to wrap up anything you want fired when the DOM has loaded. Your ajax request could be placed inside the document.ready if you want this to wait until the dom has loaded.
If you want to wait until the ajax has loaded its resource then you should use ajax.success rather than complete.
A: Just change complete: to success: in your $.ajax() call:
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
//make your DOM changes here
myFunction();
}
});
The success function will run once the AJAX request receives a successful response. So make your DOM changes within that function, and then run myFunction().
Edit
You seem to be trying to make the DOM changes using your myFunction(). But if you don't first insert the HTML received in the AJAX response into the DOM, then there will be nothing for myFunction() to modify. If this is indeed what's happening, then you have two options:
*
*Insert the response HTML into the DOM, then call myFunction() (and all of this should happen within the success callback function).
*Pass the AJAX response to myFunction() as an argument, so that myFunction() can handle the DOM insertion and then do the necessary modification.
A: There is a event that triggers after every ajax call. It is called ajaxComplete.
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
});
So you can
function Init(){
// stuff here
}
$(document).ready(function()
Init();
});
$(document).ajaxComplete(function()
Init();
});
A: You are missing the closing parenthesis of the document ready wrapper function.
$(function() {
myFunction();
});
Note the }); at the end.
A: $(function() {
myFunction();
}
should be
$(document).ready(function() {
myFunction();
});
Or incase you want the ajax to run on load. Do
$(document).ready(function() {
$.ajax();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I add these left and right arrows to my toolbar? I would like to layout a "photo" view in my app like the following:
Any idea where can I find these arrows in the bottom and how to add them the same way ?
Also any idea on how to disable for example the left arrow when there's no previous item like in this picture:
Thx for helping,
Stephane
A: Use simple UIView with background color black and alpha 0,8. Insert two custom UIButton with arrow images. You could do that in IB or prorgammaticly. Icons for arrows could be found in many free icon kits. Google for "free toolbar icon iPhone".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: unable to display the last visited date Following is the script that is meant to store the time,date the user last visited a webpage.But nothing happens when i run the HTML with the script.
window.onload = init;
function init() {
var now = new Date();
var last = new Date();
document.cookie = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toGMTString() + ";lastVisit=" + last.toDateString();
var lastVisit = document.cookie.split("=");
document.getElementById("lastVisitedOn").value = lastVisit[6];
}
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="lastVisitTester.js">
</script>
</head>
<body>
<form>
<label>Enter your name <input type="text" id="name_field" /></label> <br/>
<input type="submit" value="submit" />
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>
Why is the time/date not getting set for the h tag ? What is wrong with the script ?
A: window.onload = function () {
var now = new Date(),
expires = now,
lastVisit = document.cookie.match(/lastVisit=([^;]+)/),
userName = 'somebody';
// 1. You should set month in standalone way
expires.setMonth(now.getMonth() + 2);
// 2. For each cookie you set value individually: for username in 1st line, and for lastVisit in 2nd
document.cookie = "username=" + userName + ";path=/;expires=" + expires.toGMTString();
document.cookie = "lastVisit=" + now.toDateString() + ";path=/;expires=" + expires.toGMTString();
// 3. You should test and extract your cookie value BEFORE you set it (see above with cookie match)
// 4. You should test if it's not null also
if (null != lastVisit) {
// 5. You should use innerHTML property for set content
document.getElementById("lastVisitedOn").innerHTML = lastVisit[1];
}
// 6. But in general you should RTFM more :)
// 7. ps: And also use some standard frameworks for this -- not manual raw JS
}
A: Well there are some problems in your code.
As others has mentioned before:
*
*The function "toGMTString()" is deprecated.
Use "toLocaleString()" or "toUTCString()" instead of "toGMTString()" (see also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#toGMTString)
*You should use innerHTML and you had your index wrong.
*You cannot use document.cookie that way. Not sure way.
Example:
var now = new Date();
var last = new Date();
var cookieText = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toLocaleString() + ";lastVisit=" + last.toDateString();
document.cookie = cookieText;
var lastVisit = cookieText .split("=");
document.getElementById("lastVisitedOn").innerHTML = lastVisit[4];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Where can I find phpunit.sh after installation on Ubuntu 11.04? Like in subject I have installed phpunit but cant find phpunit.sh file to pass path to netbeans.
But I checked
phpunit -version
and recive
PHPUnit 3.5.15 by Sebastian Bergmann.
So i think the installation is ok.
A: There is just phpunit (in my system is in /usr/bin/phpunit).
In NetBeans in Tools > Options > PHP > Unit testing, just specify the output of which phpunit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery not working with the widgets I am using IGoogle interface kind of Jquery and Css for which im referring some Script tags at the bottom of my aspx page as below:
<script type="text/javascript" src="/IGUI Utilities/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="/IGUI Utilities/jquery-ui-personalized-1.6rc2.min.js"></script>
<script type="text/javascript" src="/IGUI Utilities/inettuts.js"></script>
Everything works perfect, but when i drop one more control which needs Jquery interaction again as below:
<script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$("#tabs").tabs("div.description", { event: 'mouseover' });
});
</script>
mouseover event doesn't work :( and if i drop the same control other than this page it works fine.... I tried changing the order of referring tags but no use...
Please help me on this...
A: What are you trying to do with "div.description"? That syntax doesn't look right.
$(function() {
$("#tabs").tabs({ event: 'mouseover' });
});
Should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to rewrite / proxy an Apache URI to an application listening on a specific port / server? They say that Apache's mod_rewrite is the swiss-army knife of URL manipulation, but can it do this?
Lets say I want to add a new application to my Apache webserver, where the only configurable option of the app is a port number.
I want to use & give out URLs of the form "http://hostname.example.com/app" rather than "http://hostname.example.com:8080". This would ensure that clients would be getting through the institution's firewall as well, and it's generally tidier.
My application includes absolute URIs in php, javascript and css, so I want to prepend my own root location to the URI in the applications internal links. I have no access to DNS records and so can't create another name-based virtual server.
Using Apache's mod_rewrite and mod_proxy modules, I can transparently redirect a client to the correct home-page of the application. But links within that homepage don't point a client to links relative to the new base URL.
So, what's the best way of proxying a request to an application that is listening on a specific port?
For example, if I had an application listening on port 8080, I could put this in my Apache configuration:-
<VirtualHost *:80>
SSLProxyEngine On
ServerName myhost.example.com
RewriteEngine On
UseCanonicalName On
ProxyVia On
<Location "/application">
RewriteRule ^/application/?(.*) http://localhost:8080/$1 [P,L]
</Location>
</VirtualHost>
This would work fine if the application didn't use absolute URLs, but it does. What I need to do is rewrite URLs that are returned by the application's css, javascript and php.
I've looked at the ProxyPass and ReverseProxyPass documentation, but I don't think these would work..?
I've also come across Nick Kew's mod_proxy_html, but this isn't included in the standard Apache Distribution, and my institution's webserver seems to have been fine for years without it.. Other than trawling manually (or using a grep -r | sed type expression) through the application's source code, or using this 3rd party add-on, are there any other ways to go about this?
Could I perhaps use some of the internal server variables in a mod_rewrite rule? For example a rewrite rule based on ’HTTP_REFERER'?
A: Using mod_proxy would work just fine. For instance, I mapped https://localhost/yalla/ to point to a subdirectory of my webserver:
LoadModule proxy_module modules/mod_proxy.so
ProxyRequests On
<Proxy *>
Order deny,allow
Allow from localhost
</Proxy>
ProxyPass /yalla/ http://yalla.ynfonatic.de/tmp/
If you implement this, you'll note that the pictues of the directory-listing aren't visible; this is because they're below the /tmp/ directory on the remote server, hence not visible.
So, in your case you'd do:
LoadModule proxy_module modules/mod_proxy.so
ProxyRequests On
<Proxy *>
Order deny,allow
Allow from localhost # Or whatever your network is if you need an ACL
</Proxy>
ProxyPass /app/ http://hostname.example.com:8080/
Like with everything in Apache configuration, watch those trailing slashes when referring to directories.
Good luck!
Alex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: PHP Case-insensitive equivalent of strtr Where I could find a case-insensitive version of strtr?
strtr is overloaded, I am talking about the following one
string strtr ( string $str , array $replace_pairs )
A: Use str_ireplace:
str_ireplace(array_keys($replace_pairs), array_values($replace_pairs), $str);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Similarity function for Mahout boolean user-based recommender I am using Mahout to build a user-based recommendation system which operates with boolean data.
I use GenericBooleanPrefUserBasedRecommender, NearestNUserNeighborhood and now trying to decide about the most suitable user similarity function.
It was suggested to use either LogLikelihoodSimilarity or TanimotoCoefficientSimilarity. I tried both and am getting [subjectively evaluated] meaningful results in both cases. However the RMSE rating for the same data set is better the LogLikehood. The number of "no recommendation" is similar in both case.
Can anyone recommend which of these similarity function is most suitable for this case?
A: (I'm the developer.) If I was stranded on a desert island with just one similarity metric for data without ratings/prefs, it would be log-likelihood. I would generally expect it to be the better similarity metric.
The problem with the test you're doing is that, perhaps not at all obviously, it's not meaningful for this kind of recommender / data. RMSE is root-mean-square-error, and it's comparing the actual vs predicted rating for held-out test data. But you have no ratings. They're all "1.0". Really, RMSE is always 0!
It's not, since to have anything to rank on, these recommenders will rank by some meaningful function of the similarities. But they are not estimating ratings / prefs at all. So, RMSE means squat here.
The only metric you can really use is a precision/recall test in this case, I think. Even that is problematic. This and more fun topics are covered in a book which I will shamelessly promote: Mahout in Action
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Thin client And Net programming i have built a clientServer application ( C# and VS 2008 ) for a LAN network consist of several PCs . it's working fine .
now we have a network consist of a server and thin clients . i do have no idea where and how to install my client application to work correctly .
any idea ?
A: Thin clients will connect to a server running terminal services. You will need to install your client program on that server (or servers). It's been a long since I had to play with terminal services for this, but back then when installing software for use with thin clients you also wanted to make sure you used the option to install a program from the Add/Remove Programs control panel applet.
A: Install your app on the server and test it out from the clients. In most costs the should work correctly.
If you're using Terminal Server then be sure to install the app using the Terminal Server Install Application on Terminal Server tool to make sure any reg entries etc are set-up correctly for a multi user machine. For earlier versions of Windows the preferred install route was via Add or Remove Programs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse helios Servlet creation wizard fields are blank Am trying to create a simple servlet using servlet creation wizard in helios(eclipse). A popup opens up and when I type the class-name, at the top of the popup I can view a red cross mark which says 'The Source folder cannot be empty'. There is Browse bttn available, so when I click and go there, a popup opens but do not allow me to select anything in it. Please help me in this. Thanks
A: Creating Servlets by wizard only work for projects of type Dynamic Web Project. Truncate your current project and recreate it using New > Project > Web > Dynamic Web Project wizard.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ServicePointManager Monitoring HTTP Requests I am working with an application that sends hundreds of HTTP requests a minute to different URIs. Is there any way to monitor the connections the application has created? I found that the ServicePointManager is great for inspecting a particular domain, but it requires a URI to narrow the scope. My problems would be solved if the ServicePointManager exposed a listing of all connections currently being made and their concurrent connection counts.
Uri uri = new Uri("http://www.google.com");
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
Why do I want to do this? I am trying to diagnose timeout exceptions on requests that have 30 seconds to complete and return simple JSON. (The timeout does not happen every on every request) It seems like there shouldn't be a reason for the timeout. Maybe I am running out of available connections because I've exceeded the 96 I have available from the ServicePointManager, and thats my bottleneck. While unlikely, thats the only thing I can come up with right now. Suggestions?
A: What are you currently using? Windows Performance Monitor?
JPSanders in his excellent blog post on ServicePointManager suggests using Netmon
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Iterating through elements of the same class in jquery I have a collection of div's belonging to the same class and
having form fields. I want to be able to iterate through the div's
of the same class and get the hidden form elements and store in array.
i have created and array object that adds to an array after each iteration
but i think where i am getting it wrong is the iteration through the div's
Here is the structure
<div class="parent_div">
<div class="child_div" id="child_div_1" number="1">
<div class="some_other_div">
</div>
<input id="name_1" type=hidden value="1.0"/>
<input id="name_2" type=hidden value="4.0"/>
</div>
<div class="child_div" id="child_div_2" number="2">
<div class="some_other_div">
</div>
<input id="name_2_1" type=hidden value="1.0"/>
<input id="name_2_2" type=hidden value="4.0"/>
</div>
<div class="child_div" id="child_div_3" number="3">
<div class="some_other_div">
</div>
<input id="name_3_1" type=hidden value="1.0"/>
<input id="name_3_2" type=hidden value="4.0"/>
</div>
</div>//end of parent div
I have written the jQuery code below to iterate through these div but I just don't know what I'm doing wrong. So PLEASE HELP!
function doSomething() {
var array = {};
var rowCount = $("div .child_div").length;
var rowNumber = 0;
for (i=0; i <= rowCount; i++) {
//doing something...
array[i] = arrayObj (val1,val2,val3,val4,val5,val6);
}
}
A: var values = [];
$(".child_div").each(function() {
$(this).find("input:hidden").each(function() {
values.push($(this).val());
});
});
Also you might get all the inputs and map them:
var values = $('.child_div input:hidden').map(function (index, el) { return $(el).val(); }).get();
A: You can use the each() method to do the looping.
var $items = $('.myClassName');
var myArray = new Array();
$items.each(function(){
var $hiddenItems = $(this).find('input:hidden');
$hiddenItems.each(function(){myArray.push($(this))});
});
Working example
A: If you just want an array of all hidden inputs that are within div's with the class "child_div", you can do this:
var array = $('.child_div input:hidden').get();
Edit: ... or, if you want to do more complex logic while creating your array, $().map() may be useful. E.g.,
var values = $('.child_div input:hidden').map(function(i, el) {
// return the value of each hidden input
return $(this).val();
}).get();
A: $('div .child_div').each(function(i){
// do something
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Gettext: Different path for message catalogs In a Python application that uses gettext to provide support for internationalization, I would like to change the path of the *.mo message catalogs to po/language.mo instead of the default localedir/language/LC_MESSAGES/domain.mo, as I would like to use Launchpad's translation interface, which requires this naming scheme (at least as far as I understood [1]).
However, after reading the module documentation, I can't seem to find a way to do this without monkey-patching the gettext module. Is there an 'official' way to do it?
[1] https://help.launchpad.net/Translations/YourProject/Exports
edit:
Thinking about it for a while, changing the path is not actually necessary for Launchpad-integration, as it only cares about the *.po files, not the compiled *.mo files.
My question still remains, though, as it would be nice if the application messed around with system directories as little as possible (especially considering that it's a multi-platform app that runs on *nix, Windows and OS X).
A: I asked the same question for PHP, but the answer lies in the underlying gettext api. It's not possible to change the path for catalogs.
The directory structure is fixed by gettext.
Because many different languages for many different packages have to be stored we need some way to add these information to file message catalog files. The way usually used in Unix environments is have this encoding in the file name. This is also done here. The directory name given in bindtextdomains second argument (or the default directory), followed by the name of the locale, the locale category, and the domain name are concatenated:
dir_name/locale/LC_category/domain_name.mo
See: PHP Gettext: how to change the default MO path after setting the path of the domain?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Serializing Begets Deep Cloning? I was reading an article written by an ASF contributor, and he briefly mentioned that an "old Java trick" to deep clone an object is to serialize it and then deserialize it back into another object. When I read this I paused, and thought "hey, that's pretty smart." Unfortunately neither deep cloning, nor serialization, were the subject of the article, and so the author never gave an example of what he was talking about, and online searches haven't pulled back anything along these lines.
I have to assume, we're talking about something that looks like this:
public class Dog implements Serializable
{
// ...
public Dog deepClone()
{
Dog dogClone = null;
try
{
FileOutputStream fout = new FileOutputStream("mydog.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(this);
oos.close();
FileInputStream fin = new FileInputStream("mydog.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
dogClone = (Dog)ois.readObject();
ois.close();
return dogClone;
}
catch(Exception e)
{
// Blah
}
}
Provided that I might be off a little bit (plus or minus a few lines of code), is this a generally-accepted practice for deep cloning an object? Are there any pitfalls or caveats to this method?
Are there synching/concurrency/thread-safety issues not addressed?
Because if this is a best-practices way of deep cloning objects, I'm going to use it religiously.
A: This is one common practice for deep-clonging. The drawbacks are:
*
*It is generally slow to do a serialization/deserialization. Custom cloning is faster.
*It only clones serializable objects, obviously
*It is difficult to know what you serialize. If your dog has an upwards pointer to some larger structure (pack of dogs), cloning a dog may clone a hundred other dogs if you don't pay attention. A manual clone of Dog would probably simply ignore the pack reference, creating a new individual dog object with the same properties, perhaps referencing the same pack of dogs, but not cloning the pack.
Thread safety is not different from doing a manual clone. The properties will most likely be read sequentially from the source object by the serializer, and unless you take care of thread safety you may clone a dog that is partially changed while cloning.
So I'd say it is probably not advisable to use this all the time. For a really simple object, making a simple manual clone/copy-constructor is simple and will perform much better. And for a complex object graph you may find that this runs the risk of cloning things you didn't intend to. So while it is useful, it should be used with caution.
By the way, in your example I'd use a memory stream rather than a file stream.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Force WinForms to regenerate .designer.cs files We have a controls project that contains many controls used throughout our applications. There are many old and many redundant properties on these controls, and almost none of them have attributes specified on them (such as DefaultValue() in particular).
As part of the effort to clean them up, we have added attributes to the properties, and are looking to remove the redundant ones.
What we would like to do as part of this is to clean the generated code from the winforms designer (the xxxxxx.designer.cs and xxxxxx.designer.vb files). Some of the properties are straight removal, for which we were able to use Grep and Sed to remove the offending lines, but we are looking for a way to make Visual Studio (or something) to regenerate the files.
As we have 100's of forms, it is infeasible to manually open each one and modify them to do this.
Does anyone know of a way to do this?
Edit:
To clarify, what I mean is not to remove the properties straight away, but to apply the DesignerSerializationVisibity() attribute to them to tell the designer to not write them. Then once we have updated all the designer files, we can delete the properties.
See Also:
Automatic regenerate designer files
A: Not possible, you can't get the designer to parse InitializeComponent() when it contains property assignments for properties that you have removed or renamed. It has to parse it before it can regenerate the code.
The only real approach is to first apply the [DesignerSerializationVisibility] attribute to the old property so it no longer writes the property assignment. Then load each form and make a trivial edit to get it to regenerate InitializeComponent(), now without the property assignment. Then you can remove them. Directly editing the method could be quicker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to avoid page scroll-up when a link gets clicked I have a div which is half way down the page. After I click a button, I load an image in that div. What happens is, that the page scrolls all the way up. How to avoid this ?
A: you have to edit your click event. the simplest thing would be to return false. you could also preventDefault f.e. if you are using jquery.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there easier way to work with F# mutable structures How I do it now is really weird. And the sad thing is I've got many structures and use them often.
Here is how I'm acting for a moment :
[<type:StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)>]
type OneDevice = {
mutable id : UInt16
mutable typeDev : byte
mutable portNum : byte
mutable Parity : byte
mutable StopBits : byte
mutable BaudRate : byte
mutable addr1 : byte
mutable addr2 : byte
mutable useCanal : byte
mutable idGroup1 : byte
mutable idGroup2 : byte
mutable idGroup3 : byte
mutable idGroup4 : byte
mutable idGroupSos1 : byte
mutable idGroupSos2 : byte
mutable idGroupSos3 : byte
mutable idGroupSos4 : byte
mutable idSosReserv : byte
mutable addrModbus : byte
mutable offsetModbus : System.UInt16
[<field: MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)>]
mutable pwd : byte array
mutable offsetInModbus : UInt16
mutable reserv : UInt16 }
Here is how I define structures. "type str = struct ... " works really different ! I need exactly my variant of structure. But writing this is just a half of my trouble, second half is how I create new element of this structure. let mutable dev = new OneDevice() doesn't work ! So I need to make this :
let mutable dev = {
id = 0us
typeDev = 0x00uy
portNum = 0x00uy
Parity = 0x00uy
StopBits = 0x00uy
BaudRate = 0x00uy
addr1 = 0x00uy
addr2 = 0x00uy
useCanal = 0x00uy
idGroup1 = 0x00uy
idGroup2 = 0x00uy
idGroup3 = 0x00uy
idGroup4 = 0x00uy
idGroupSos1 = 0x00uy
idGroupSos2 = 0x00uy
idGroupSos3 = 0x00uy
idGroupSos4 = 0x00uy
idSosReserv = 0x00uy
addrModbus = 0x00uy
offsetModbus = 0us
pwd = Array.zeroCreate 17
offsetInModbus = 0us
reserv = 0us }
And that is weirdest part here. Can I make it somehow easier ?
Thank you !
A: The problem is these are not structures. They're record types. Use type [<Struct>] MyStruct = ....
See http://msdn.microsoft.com/en-us/library/dd233233.aspx and http://msdn.microsoft.com/en-us/library/ee340416.aspx
Record types: http://msdn.microsoft.com/en-us/library/dd233184.aspx
Structs are value types. Records are reference types, like classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding onclick event to li element in IE6 So I have a list, and I want to dynamically add an event via JavaScript. I have it working great in Firefox, but I also need it to work in IE6 (ugh), but it's required. It doesn't have to be pretty, just needs to work. The event that triggers simply removes the item from the list. I am not sure what I need to do to get it working. Here is small piece of what I have so far. The ids are unique, I just put that one in as an example. It works great in all newer browsers.
var id = "123456";
var list = document.createElement("ul");
var listElement = document.createElement("li");
listElement.setAttribute("id", id);
listElement.setAttribute("onclick", "removeFromList('" + id + "')");
listElement.appendChild(document.createTextNode(content));
list.appendChild(listElement);
document.getElementById('myElement').appendChild(list);
A: Pure javascript, should work in IE6 :
var id = "123456";
var list = document.createElement("ul");
var listElement = document.createElement("li");
listElement.setAttribute("id", id);
listElement.appendChild(document.createTextNode(content));
list.appendChild(listElement);
document.getElementById('myElement').appendChild(list);
if( listElement.addEventListener ) {
listElement.addEventListener("click", function(e) {
removeFromList( id );}, false );
} else {
listElement.attachEvent( "onclick", function(e) {
removeFromList( id );});
}
A: i don't have an IE6 to test this, but replacing the onclick-line:
listElement.setAttribute("onclick", "removeFromList('" + id + "')");
with this might work:
listElement.onclick = function(){ removeFromList(id); };
you also could use attachEvent for IE and stick to you old solution (or better use addEventListener) on the newer ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reading text file, matlab I am reading a text file 'mytext.text' in matlab. Data file looks like:
1 -4436.6910 415.1843 -3019.7497 1,3,4,5,21,23
2 -4366.4541 1353.9975 -3085.1166 1,3,4,23
....
I don't know the length of Col5. How can I read it in matlab?
fid=fopen( 'mytext.text','r');
Grdata = textscan(fid, '%d %f %f %f (Col 5 what should be)% This line is
problem%
fclose(fid);
Any help.
A: One possibility is to read the last column as string, then convert it to numbers afterward.
fid = fopen('file.dat','r');
C = textscan(fid, '%f %f %f %f %s', ...
'Delimiter',' ', 'MultipleDelimsAsOne',true, 'CollectOutput',true);
fclose(fid);
C = [num2cell(C{1}) cellfun(@str2num, C{2}, 'UniformOutput',false)]
The resulting cell-array:
C =
[1] [-4436.7] [415.18] [-3019.7] [1x6 double]
[2] [-4366.5] [ 1354] [-3085.1] [1x4 double]
with:
>> C{1,end}
ans =
1 3 4 5 21 23
>> C{2,end}
ans =
1 3 4 23
A: To read a single line do
% Read at most 4 elements
data1234 = fscanf (fid, '%d %f %f %f', 4);
% Read as many elements as possible, stop when no ',' is found
data5 = fscanf (fid, '%d,');
Continue reading lines until you reached the end of the file (save the data from each line before doing that). So you need some loop that continues doing this untill the file ends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to improve Spring MVC performance? Are there best practises how to improve the performance of spring webapps?
I use ehcache for static content, try to load JavaScript at the end of my app but the app doesn't run smooth yet. For a simple registration only the GET-request to map the url and initalize session and bean lastet over 7 sec.
Sure you can optimize a lot for specific, but I'd like to know about generell performance issues and how to handle those.
Patterns, best practises and so on are very wellcome here.
A: In general, I recommend:
*
*build a test environment where you can execute the application and
get at the inside
*Write repeatable performance testing scripts, focusing both on absolute performance (e.g. "how long does it take to render this page") and performance at scale (e.g. "how does performance degrade under load?")
*glue a profiler into your test environment. It's been a while since I worked on Java apps, but there are lots of them available.
*run performance test whilst running your profiler. Work out what the bottleneck is. Fix the bottleneck. Rinse. Repeat.
I generally recommend NOT to have the test rig be similarly specified to production, because it makes it very hard to create enough load to stress the system. It's also very expensive.
If you have a "production-like" environment to test on, do it now - ideally, you'll get similar results as on the test environment, but not always; if at all possible, install the profiler and see where the bottleneck is.
Once you've done that, you can deploy the optimized app to your production environment.
A: Create performance-tests (like with jmeter). Profile your application, either with a full-blown profiler or by instrumentation. If you are using spring (and spring-configured datasources), I like javamelody a lot which is a simple plug-in that instruments and compiles performance-statistics of your application.
Run the test, check the profiling information, identify bottlenecks, optimize the worst offenders. Repeat until satisfied.
There is no inherent performance problem with Spring MVC. Performance issues comes from other areas. Bad SQL queries, slow external integrations, excessive JSTL crazyness in your views etc etc.
A: VisualVM is very useful for analyzing. Can be downloaded from link. Memory Pools and Visual GC plugins which are not installed by default, also useful to monitor memory usage and GC activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to run the instance of SQL Server Express 2008 How to run the SQL Server 2008 Express edition, when I go to start menu, the SQL Server 2008 R2 Configuration tools there is only one option SQL Server installation center.
When I open it there I cannot find any option how to run it, there is no option like configuration manager in configuration tools.
Did I miss something during installation, if it is so how can I get the configuration manager? :(
I have installed Visual Studio 2010, I cannot figure this thing out how to run to server, also I am new in this field Please somebody help me at this..
A: You have not selected management studio while installation
A: If you're absolutely brand new, a lot of the documentation will be overwhelming, but it's too broad a question to answer here fully. There are just too many variables - Did you get the Management Studio Express, for example? What are you trying to do, etc?
However, there is a nice video here that may be a good starting point for you: http://www.youtube.com/watch?v=9_3qgAxplW0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get future dates How to get a few future dates with Wednesdays and Fridays using NSDateComponents? Answers will be greatly appreciated. Thanks in advance.
A: This is actually a bit of a tricky problem if you want it to be totally bullet-proof. Here's how I would do it:
NSInteger wednesday = 4; // Wed is the 4th day of the week (Sunday is 1)
NSInteger friday = 6;
NSDate *start = ...; // your starting date
NSDateComponents *components = [[NSDateComponents alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
for (int i = 0; i < 100; ++i) {
[components setDay:i];
NSDate *target = [gregorian dateByAddingComponents:components toDate:start options:0];
NSDateComponents *targetComponents = [gregorian components:NSUIntegerMax fromDate:target];
if ([targetComponents weekday] == wednesday || [targetComponents weekday] == friday) {
NSLog(@"found wed/fri on %d-%d-%d", [targetComponents month], [targetComponents day], [targetComponents year]);
}
}
[gregorian release];
[components release];
A: To get the correct day of the week, you must create a suitable instance of NSCalendar, create an NSDate object using dateFromComponents: and then use components:fromDate: to retrieve the weekday.
A: If you have NSDate instance for concrete weekday (f.e. Wednesday), you can get new future dates by using following code:
NSDate *yourDate = ...
NSDateComponents* components = [[NSDateComponents alloc] init];
components.week = weeks;
NSDate* futureDate = [[NSCalendar reCurrentCalendar] dateByAddingComponents:components toDate:yourDate options:0];
[components release];
P.S. Agree with Brian, try researching before asking.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do i access a edittext box on a listview row I have a list view with edittext on each row. If a user clicks on a rowhowcan i access that particular edittext?
A: You should initialize EditText's onClickListener() inside your adapter's getView() method, right where you inflate this EditText. Hope this helps.
A: If the EditText boxes were created during runtime, you can use setId(int) when creating them. Then, through your ListView, you can use findViewById(int id) to retrieve it in the future. So the full call would be like EditText myEditText = (EditText) myListView.findViewById(1) would retrieve the box who's ID you set to 1.
If you create them through XML, then you can assign the ID to them in the xml that you can easily remember. Afterwards, you can use findViewById(int id) the same way as before but use the ID references in the generated R file.
A: I want you to use listAdapter class.
You must make your own class which extends the BaseAdapter class.
Then make a listItem class which contains a EditText Control.
And deal events of EditText in the class.
Then you must add the class as the arrays of class into the listAdapter class.
And override the getView function of BaseAdapter class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fade out parent DIV - but not the children I have this HTML code :
<div id="espacePub">
<div id="menu">
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
<li>Link 5</li>
<li>Link 6</li>
</ul>
</div><!-- End Div menu -->
</div><!-- End Div espacePub -->
I want to select the div #espacePub but not the div #menu to fade out, change background and then fade in. With documentation found on http://api.jquery.com/not/, I tried this :
var imgs = [
'img/pub.jpg',
'img/pub2.jpg',
'img/pub3.jpg'];
var cnt = imgs.length;
$(function() {
setInterval(Slider, 2000);
});
function Slider() {
$('#espacePub').not(document.getElementById('menu')).fadeOut("slow", function() {
$(this).css('background-image', 'url("'+imgs[(imgs.length++) % cnt]+'")').fadeIn("slow");
});
}
My problem is that the entire #espacePub is fading, including #menu but I don't want #menu fading... What I'm doing wrong?
A: give the #escapePub position: relative;
Create a div #slider inside the #escapePub with position: absolute; width: 100%; height: 100%; and apply jquery to it.
$('#espacePub #slider').fadeOut("slow",
function() {
$(this).css('background-image', 'url("'+imgs[(imgs.length++) % cnt]+'")')
.fadeIn("slow");
});
A: You can't leave the nested element with the opacity 100% when you change it's parent opacity. Probably you need get #menu div from the #espacePub and position it absolute over #espacePub.
A: The problem is the espacePub div contains the menu div so when you fade it everything inside has to be hidden. To do what you want they will need to be separate elements.
Here is a quick fiddle showing you an example. Note I changed the images to colors so it was easier to set up on jsFiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Pythonic way to mix two lists I have two lists of length n and n+1:
[a_1, a_2, ..., a_n]
[b_1, b_2, ..., b_(n+1)]
I want a function giving as a result a list with alternate elements from the two, that is
[b_1, a_1, ..., b_n, a_n, b_(n+1)]
The following works, but does not look smart:
def list_mixing(list_long,list_short):
list_res = []
for i in range(len(list_short)):
list_res.extend([list_long[i], list_short[i]])
list_res.append(list_long[-1])
return list_res
Can anyone suggest a more pythonic way of doing this? Thanks!
A: >>> long = [1, 3, 5, 7]
>>> short = [2, 4, 6]
>>> mixed = []
>>> for i in range(len(long)):
>>> mixed.append(long[i])
>>> if i < len(short)
>>> mixed.append(short[i])
>>> mixed
[1, 2, 3, 4, 5, 6, 7]
A: mixing two lists is a job for zip:
res = []
for a,b in zip(list_long, list_short):
res += [a,b]
for lists of differing lengths, define your own function:
def mix(list_long, list_short):
result = []
i,j = iter(list_long), iter(list_short)
for a,b in zip(i,j):
res += [a,b]
for rest in i:
result += rest
for rest in j:
result += rest
return result
using the answer given by Mihail, we can shorten this to:
def mix(list_long, list_short):
i,j = iter(list_long), iter(list_short)
result = [item for sublist in zip(i,j) for item in sublist]
result += [item for item in i]
result += [item for item in j]
return result
A: I would use a combination of the above answers:
>>> a = ['1', '2', '3', '4', '5', '6']
>>> b = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> [i for l in izip_longest(a, b, fillvalue=object) for i in l if i is not object]
<<< ['1', 'a', '2', 'b', '3', 'c', '4', 'd', '5', 'e', '6', 'f', 'g']
A: more-itertools has roundrobin which exactly does the job:
from more_itertools import roundrobin
l1 = [1, 3, 5]
l2 = [2, 4, 6, 8, 10]
print(list(roundrobin(l1,l2)))
# [1, 2, 1, 3, 4, 3, 5, 6, 5, 8, 10]
A: >>> import itertools
>>> a
['1', '2', '3', '4', '5', '6']
>>> b
['a', 'b', 'c', 'd', 'e', 'f']
>>> list(itertools.chain.from_iterable(zip(a,b)))
['1', 'a', '2', 'b', '3', 'c', '4', 'd', '5', 'e', '6', 'f']
zip() produces a iterable with the length of shortest argument. You can either append a[-1] to the result, or use itertools.zip_longest(izip_longest for Python 2.x) with a fill value and delete that value afterwards.
And you can use more than two input sequences with this solution.
For not appending the last value, you can try this dirty approach, but I don't really recommend it, it isn't clear:
>>> a
[1, 2, 3, 4, 5]
>>> b
['a', 'b', 'c', 'd', 'e', 'f']
>>> [a[i//2] if i%2 else b[i//2] for i in range(len(a)*2+1)]
['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f']
(For Python 2.x, use single /)
A: IMHO the best way is:
result = [item for sublist in zip(a,b) for item in sublist]
It's also faster than sum and reduce ways.
UPD Sorry missed that your second list is bigger by one element :)
There is another crazy way:
result = [item for sublist in map(None, a, b) for item in sublist][:-1]
A: Use izip_longest filling the gaps with something you don't have in your lists, or don't want to keep in the result. If you don't want to keep anything resolving to False, use the defaults for izip_longest and filter:
from itertools import chain, izip_longest
l1 = [1,3,5]
l2 = [2,4,6,8,10]
filter(None, chain(*izip_longest(l1,l2)))
the result is: [1, 2, 3, 4, 5, 6, 8, 10]
Using None for filling the gaps and removing them with filter:
filter(lambda x: x is not None, chain(*izip_longest(l1,l2, fillvalue=None)))
For better efficiency, when l1 or l2 are not short lists but e.g. very long or infinite iterables, instead of filter use ifilter, which will give you an iterable instead of putting all in memory in a list. Example:
from itertools import chain, izip_longest, ifilter
for value in ifilter(None, chain(*izip_longest(iter1,iter1))):
print value
A: Another answer for different lengths and more lists using zip_longest and filtering out None elements at the end
from itertools import zip_longest
a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']
c = ['A', 'B', 'C', 'D', 'E']
[item for sublist in zip_longest(*[a,b,c]) for item in sublist if item]
returns
[1, 'a', 'A', 2, 'b', 'B', 3, 'c', 'C', 'd', 'D', 'E']
A: You could do something like the following (assuming len(list_long)==len(list_short)+1:
def list_mixing(list_long,list_short):
return [(list_long[i/2] if i%2==0 else list_short[i/2]) for i in range(len(list_long)+len(list_short)]
Where I am using / for integer division (exactly what the operator is for that depends on the language version).
A: sum([[x,y] for x,y in zip(b,a)],[])+[b[-1]]
Note: This works only for your given list lengths, but can easily be extended to arbitrary length lists.
A: This is the best I've found:
import itertools
l1 = [1, 3, 5]
l2 = [2, 4, 6, 8, 10]
result = [
x # do something
for x in itertools.chain.from_iterable(itertools.zip_longest(l1, l2, l1))
if x is not None
]
result
# [1, 2, 1, 3, 4, 3, 5, 6, 5, 8, 10]
To make it extra clear, zip_longest groups the elements together per index:
iter = list(itertools.zip_longest(l1, l2, l1))
iter[0]
# (1, 2, 1)
iter[1]
# (3, 4, 3)
iter[-1] # last
# (None, 10, None)
After, itertools.chain.from_iterable flattens them in order.
The reasons why it is the best:
*
*filtering None is not recommended anymore, use a list comprehension
*a list comprehension also allows you to immediately "do something" with x
*it does not throw away items when some lists are longer than the shortest one
*it works with any amount of lists
*it is actually super easy to reason what is happening contrary to all the "cleverness" out there
A: Use zip. That will give you a list of tuples, like:
[('a_1', 'b_1'), ('a_2', 'b_2'), ('a_3', 'b_3')]
If you want to clean that up into a nice list, just iterate over the list of tuples with enumerate:
alist = ['a_1', 'a_2', 'a_3']
blist = ['b_1', 'b_2', 'b_3']
clist = []
for i, (a, b) in enumerate(zip(alist, blist)):
clist.append(a)
clist.append(b)
print clist
['a_1', 'b_1', 'a_2', 'b_2', 'a_3', 'b_3']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: php-ews class library always returns null I am trying to make SOAP calls to our Exchange server using the classes I found here:
http://code.google.com/p/php-ews/
I have coded up a few examples, starting with the basic example as below and no matter what I try and do this always returns null.
$ews = new ExchangeWebServices('exchange.example.com', 'user', 'password');
$request = new EWSType_FindFolderType();
$request->Traversal = EWSType_FolderQueryTraversalType::SHALLOW;
$request->FolderShape = new EWSType_FolderResponseShapeType();
$request->FolderShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;
$request->IndexedPageFolderView = new EWSType_IndexedPageViewType();
$request->IndexedPageFolderView->BasePoint = 'Beginning';
$request->IndexedPageFolderView->Offset = 0;
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
$response = $ews->FindFolder($request);
var_dump($response);
Has anyone else encountered this error, or can maybe shed some light on it for me?
A: Your request looks fine, it should work. Did you set up services.wsdl with your EWS server address? (see http://ewswrapper.lafiel.net/basic-info/working-with-ewswrapper/ for some more info)
Try looking at the actual call before it is send and the response before it is interpreted.
To do so in NTMLSoapClinet.php print $request at the top of __doRequest() function and end script execution (ie. die()) and then try printing $response befor it is returned in __doRequest() function and end script execution. This should give you some more insight on what's going on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PropertyUtils.getProperty fails when trying to get a simple property value I've a strange issue with the PropertyUtils.getProperty(bean, fieldName) method, where I got a java.lang.NoShuchMethodException.
Suppose we have a simple java class called pojo:
public class Pojo {
public java.util.Date aDate;
public java.util.Date theDate;
public Pojo(){}
}
and a caller class like
public class TestPojo{
public static void main(String[] args){
Pojo p = new Pojo();
p.setADate(new Date());
p.setTheDate(new Date());
PropertyUtils.getProperty(p, "theDate");
PropertyUtils.getProperty(p, "aDate");
}
}
The first PropertyUtils.getProperty call works fine, and the second one will throw the NoSuchMethodExeption.
I would like to know if I'm missing something stupid or it's really a bug :)
A: Take a look at this bug report
The Java Bean Specification states in section "8.8 Capitalization of
inferred names" that when the first character is converted to
lowercase unless the first two characters are both uppercase then the
property name is "unchanged".
Adapting the rest for you (in italics):
So when you have a getter method named "getADate" this is
translated into property name "ADate" and not "aDate".
So to resolve your issue you have two choices:
*
*use property name "ADate" instead or
*change you method names to "getaDate" and "setaDate"
A: I don't understand how PropertyUtils.getProperty(p, "TheDate"); could work since the name of the property is not correct.
Try this:
public class TestPojo{
public static void main(String[] args){
Pojo p = new Pojo();
p.setADate(new Date());
p.setTheDate(new Date());
PropertyUtils.getProperty(p, "theDate");
PropertyUtils.getProperty(p, "aDate");
}
}
Link to the PropertyUtils method
To Solve your problem, two solutions:
*
*use property name "ADate" instead
*change your accessors method names to getaDate() and setaDate(Date dateToSet)
As Xavi said it is a reported bug
A: Try
PropertyUtils.getProperty(p, "ADate");
instead of
PropertyUtils.getProperty(p, "aDate");
A: May be you need using:
PropertyUtils.getProperty(p, "ADate");
where A in UPPERCASE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: xCode simulator won't show keyboard If I start up a blank app (single view application) and simply put a UITextField into the NIB, everything is fine: a keyboard will show up once I click the UITextField in the simulator.
If I start up the app I'm working on at the moment, the keyboard will not show up (as if I had turned on simulate Hardware keyboard) and I am not able to enter any text at all. If I run the same app on my phone, however, the keyboard will show up and I can enter text as usual.
I'm sure it has to do with my code as the blank app will show a keyboard on the simulator. My set up is as follows: I have a RootViewController and then add another ViewController. In this ViewController I add yet another ViewController (where I want the UITextField to be) like so:
if (self.addNotebook == nil) {
NSLog(@"create...");
AddNotebookViewController *avc = [[AddNotebookViewController alloc]
initWithNibName:nil bundle:nil];
self.addNotebook = avc;
[avc release];
}
[self.view addSubview:addNotebook.view];
There is hardly anything in this new ViewController:
#import <Foundation/Foundation.h>
@interface AddNotebookViewController : UIViewController <UITextFieldDelegate>
{
}
...
The xib is set up as follows:
One simple UITextField
File's Owner Class = AddNotebookViewController
File's Owner Outlet view = view
Text Field delegate = File's owner
So I don't understand why the keyboard doesn't pop up in the simulator while it does on my phone... any suggestions would be very much welcome!
A: Ok, I think I found the problem. It has to do with iOS 5, so I guess we can't really discuss this here. If I run the app on iOS 5, I won't see the keyboard on the phone or on the simulator.
If I rung the app on iOS 4 or on Simulator iOS 4 everything is fine and everyone happy.
I still don't know why this is so... I guess I need to head over to the apple discussion forum for these kind if questions?
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Remembering the state of the tree view menu on refreshing the page in ruby I have a tree view menu in ruby.
I am expanding the tree and it works well.
On refreshing the page it collapsesand my expansion is not seen.
Please let me know if there is a way to rember the state of the tree view.
my view code:
%table.treeTable
%thead
%th
All:
= link_to "Expand", "#", :class => "all_action_expand"
= "/"
= link_to "Collapse", "#", :class => "all_action_collapse"
%th
= link_to "Check", "#", :class => "check_all"
= "/"
= link_to "Uncheck", "#", :class => "uncheck_all"
%tbody
- Ic.make_tree(@ics).values.each do |root|
%tr{:id => root.tree_id, :class => "root"}
%td= root.root_name
- if show_check_boxes
%td= check_box_tag "ic_glob", root.tree_id, false, :class => "ic_parent"
- root.suites.each do |suite|
%tr{:id => suite.tree_id, :class => "child-of-#{root.tree_id}"}
%td= suite.suite_name
- if show_check_boxes
%td= check_box_tag "ic_glob", suite.tree_id, false, :class => "ic_parent"
- suite.children.each do |case_item|
%tr{:id => case_item.tree_id, :class => "child-of-#{suite.tree_id}"}
%td= case_item.case_name
- if show_check_boxes
%td= check_box_tag "ic_glob", case_item.tree_id, false, :class => "ic_parent"
- case_item.children.each do |ic|
%tr{:id => ic.id, :class => "child-of-#{case_item.tree_id}"}
%td= link_to ic.name, edit_ic_path(ic.id)
- if show_check_boxes
%td= check_box_tag "ic_ids[]", ic.id, false
/Execute the tree table javascript (hackish)
= javascript_tag "$('.treeTable').treeTable({persist:true})"
/ Need some Ic javascript to (cascading selects, etc.)
= javascript_include_tag "pages/ic"
= javascript_include_tag "jquery.cookie"
A: You can use a cookie to store the actual state of your tree. When you reload the page, read the cookie and restore the expansion.
EDIT:
You need the jquery-cookie plugin, then use the persist parameter to restore the tree expansions after reload automagically:
$(".example").treeTable({
persist: true
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate JPA configurations not working I am configuring hibernate with JPA annotations. I have file called country.java with JPA annotations. I have a client file to insert value in country table. while the program runs, it is showing error like "'hibernate.dialect' must be set when no Connection avalable" I have hibernate.cfg.xml is placed in src folder. please help me to solve this
A: It's a path issue; the class loader can't find your .cfg.xml.
You're probably running in an IDE where you haven't told it how to find that file. The answer depends on your IDE.
The problem is that you assume that all is well and feel outrage that the JVM isn't behaving badly. What this tells you is that the JVM is doing exactly what it should; it's your assumptions that need to be checked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the best way to check for duplicate keys in Querystring/Post/Get requests I'm writing a small API and need to check for duplicate keys in requests. Could someone recommend the best way to check for duplicate keys. I'm aware I could check the key.Value for commas in the string, but then I have another problem of not allowing commas in API requests.
//Does not compile- just for illustration
private void convertQueryStringToDictionary(HttpContext context)
{
queryDict = new Dictionary<string, string>();
foreach (string key in context.Request.QueryString.Keys)
{
if (key.Count() > 0) //Error here- How do I check for multiple values?
{
context.Response.Write(string.Format("Uh-oh"));
}
queryDict.Add(key, context.Request.QueryString[key]);
}
}
A: QueryString is a NameValueCollection, which explains why duplicate key values appear as a comma separated list (from the documentation for the Add method):
If the specified key already exists in the target NameValueCollection
instance, the specified value is added to the existing comma-separated
list of values in the form "value1,value2,value3".
So, for example, given this query string: q1=v1&q2=v2,v2&q3=v3&q1=v4, iterating through the keys and checking the values will show:
Key: q1 Value:v1,v4
Key: q2 Value:v2,v2
Key: q3 Value:v3
Since you want to allow for commas in query string values, you can use the GetValues method, which will return a string array containing the value(s) for the key in the query string.
static void Main(string[] args)
{
HttpRequest request = new HttpRequest("", "http://www.stackoverflow.com", "q1=v1&q2=v2,v2&q3=v3&q1=v4");
var queryString = request.QueryString;
foreach (string k in queryString.Keys)
{
Console.WriteLine(k);
int times = queryString.GetValues(k).Length;
if (times > 1)
{
Console.WriteLine("Key {0} appears {1} times.", k, times);
}
}
Console.ReadLine();
}
outputs the following to the console:
q1
Key q1 appears 2 times.
q2
q3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: If array is thread safe, what the issue with this function? I am totally lost with the things that is happening with my code.It make me to think & get clear with Array's thread Safe concept. Is NSMutableArray OR NSMutableDictionary Thread Safe ?
While my code is under execution, the values for the MainArray get's changes although, that has been added to Array.
Please try to execute this code, onyour system its very much easy.I am not able to get out of this Trap.
It is the function where it is returning Array.
What I am Looking to do is :
-(Array) (Main Array)
-->(Dictionary) with Key Value (Multiple Dictionary in Main Array)
-----> Above dictionary has 9 Arrays in it.
This is the structure I am developing for Array.But even before
#define TILE_ROWS 3
#define TILE_COLUMNS 3
#define TILE_COUNT (TILE_ROWS * TILE_COLUMNS)
-(NSArray *)FillDataInArray:(int)counter
{
NSMutableArray *temprecord = [[NSMutableArray alloc] init];
for(int i = 0; i <counter;i++)
{
if([temprecord count]<=TILE_COUNT)
{
NSMutableDictionary *d1 = [[NSMutableDictionary alloc]init];
[d1 setValue:[NSString stringWithFormat:@"%d/2011",i+1] forKey:@"serial_data"];
[d1 setValue:@"Friday 13 Sep 12:00 AM" forKey:@"date_data"];
[d1 setValue:@"Description Details " forKey:@"details_data"];
[d1 setValue:@"Subject Line" forKey:@"subject_data"];
[temprecord addObject:d1];
d1= nil;
[d1 release];
if([temprecord count]==TILE_COUNT)
{
NSMutableDictionary *holderKey = [[NSMutableDictionary alloc]initWithObjectsAndKeys:temprecord,[NSString stringWithFormat:@"%d",[casesListArray count]+1],nil];
[self.casesListArray addObject:holderKey];
[holderKey release];
holderKey =nil;
[temprecord removeAllObjects];
}
}
else {
[temprecord removeAllObjects];
NSMutableDictionary *d1 = [[NSMutableDictionary alloc]init];
[d1 setValue:[NSString stringWithFormat:@"%d/2011",i+1] forKey:@"serial_data"];
[d1 setValue:@"Friday 13 Sep 12:00 AM" forKey:@"date_data"];
[d1 setValue:@"Description Details " forKey:@"details_data"];
[d1 setValue:@"Subject Line" forKey:@"subject_data"];
[temprecord addObject:d1];
d1= nil;
[d1 release];
}
}
return temprecord;
[temprecord release];
}
What is the problem with this Code ? Every time there are 9 records in Array, it just replaces the whole Array value instead of just for specific key Value.
A: Firstly, Cocoa immutable collections are thread-safe. Their mutable counterparts are not thread-safe. Making your code thread-safe depends on the design of your application. A good practice in a multithreaded program is to use as many immutable data as possible.
Secondly, in:
NSMutableDictionary *holderKey = [[NSMutableDictionary alloc]initWithObjectsAndKeys:temprecord,[NSString stringWithFormat:@"%d",[casesListArray count]+1],nil];
[self.casesListArray addObject:holderKey];
[holderKey release];
holderKey =nil;
[temprecord removeAllObjects];
you have the following:
*
*temprecord points to a mutable array
*you create a mutable dictionary called holderKey that contains a single object, namely the same temprecord as above
*you add this mutable dictionary to self.casesListArray
*you release holderKey, which doesn’t get deallocated because it was added to an array in the previous step
*you remove all objects from temprecord. Since temprecord is the same array as the one in holderKey, it’ll be an empty array in that dictionary, too. Since holderKey was added to self.casesListArray, the corresponding array element is the same dictionary, with the same (now empty) array.
Since you send -removeAllObjects to temprecord during the execution of that method, you probably want to store a copy (either mutable or immutable) of the current values of the array instead:
NSMutableArray *tempRecordCopy = [temprecord mutableCopy];
NSMutableDictionary *holderKey = [[NSMutableDictionary alloc]initWithObjectsAndKeys:tempRecordCopy,[NSString stringWithFormat:@"%d",[casesListArray count]+1],nil];
[tempRecordCopy release];
I’m not really sure whether you need the array to be mutable. If you don’t, change that to NSArray and -copy and you’ll have an immutable copy.
Lastly, you’re using an odd pattern that results in memory leaks in a managed memory setting. For example, in:
d1= nil;
[d1 release];
since you’re assigning nil to d1, the following instruction, [d1 release], is effectively a no-operation. This means that d1 doesn’t point to the original object anymore, and this object hasn’t been released. Don’t do this. Instead:
[d1 release];
is enough in most cases and, if you truly need to nil out the variable, do it after release:
[d1 release];
d1 = nil;
Edit: A further note: in:
return temprecord;
[temprecord release];
temprecord doesn’t get released because the method ends upon returning. That attempt at releasing temprecord is unreachable code and never gets executed. You want this instead:
return [temprecord autorelease];
Another edit: Note that -setObject:forKey: is the canonical method for adding objects to a dictionary. You’re using -setValue:forKey:, which is a KVC method that has a peculiar behaviour when used on dictionaries. Unless you’re familiar with KVC, I suggest you use -setObject:forKey:.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Default return value of a boolean type return function in c++
Possible Duplicate:
Why can you return from a non-void function without returning a value without producing a compiler error?
According to the c++ standard what should be the return value of the following function.
bool done()
{
// no return value
}
A: This would be undefined behavior - anything can happen.
A: Although it returns a value, it is undefined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add custom validate method for viewmodel I tried to add custom validator for ViewModel class:
[Serializable]
public class UserViewModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
yield return new ValidationResult("Fail this validation");
}
}
Unfortunately this is not triggered when Action method gets called, e.g.
[HttpPost]
public ActionResult Edit(UserViewModel user)
How can I add custom validation logic? ValidationAttribute does not provide easy enough solution. I am unable to find clear information on MVC2 validation mechanisms.
A: IValidatableObject is not supported in ASP.NET 2.0. Support for this interface was added in ASP.NET MVC 3. You could define a custom attribute:
[AttributeUsage(AttributeTargets.Class)]
public class ValidateUserAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
UserViewModel user = value as UserViewModel;
// TODO: do some validation
ErrorMessage = "Fail this validation";
return false;
}
}
and then decorate your view model with this attribute:
[Serializable]
[ValidateUser]
public class UserViewModel
{
}
A: Your syntax looks right. The validation isn't "triggered" until you try to validate your model. Your controller code should look like this
[HttpPost]
public ActionResult Edit(UserViewModel user)
{
if(ModelState.IsValid)
{
// at this point, `user` is valid
}
// since you always yield a new ValidationResult, your model shouldn't be valid
return View(vm);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I find out if window animations are enabled in settings I know, I can start the Settings-Activity with
Intent intent = new Intent(Settings.ACTION_DISPLAY_SETTINGS);
startActivityForResult(intent,1);
But how do I know if the animations are enabled in the first place?
I have an animation inside a custom view and only want to show it, if the animations are enabled in the settings. If they are disabled, I'd like to ask the user to enable them the first time he starts the application.
A:
Settings.System.TRANSITION_ANIMATION_SCALE and Settings.System.ANIMATOR_DURATION_SCALE are deprecated from API 17.
So I use this method to find out.
private boolean areSystemAnimationsEnabled() {
float duration, transition;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
duration = Settings.Global.getFloat(
context.getContentResolver(),
Settings.Global.ANIMATOR_DURATION_SCALE, 1);
transition = Settings.Global.getFloat(
context.getContentResolver(),
Settings.Global.TRANSITION_ANIMATION_SCALE, 1);
} else {
duration = Settings.System.getFloat(
context.getContentResolver(),
Settings.System.ANIMATOR_DURATION_SCALE, 1);
transition = Settings.System.getFloat(
context.getContentResolver(),
Settings.System.TRANSITION_ANIMATION_SCALE, 1);
}
return (duration != 0 && transition != 0);
}
Or, you can check only for ANIMATOR_DURATION_SCALE...
private float checkSystemAnimationsDuration() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
return Settings.Global.getFloat(
context.getContentResolver(),
Settings.Global.ANIMATOR_DURATION_SCALE,
0);
} else {
return Settings.System.getFloat(
context.getContentResolver(),
Settings.System.ANIMATOR_DURATION_SCALE,
0);
}
}
and set your valueAnimator.setDuration() accordingly.
ValueAnimator alphaFirstItemAnimator = new ValueAnimator();
alphaFirstItemAnimator.setObjectValues(0.8F, 0F);
alphaFirstItemAnimator.setDuration((long)(DURATION_ANIMATION_MILLIS * checkSystemAnimationsDuration()));
alphaFirstItemAnimator.setInterpolator(new DecelerateInterpolator());
alphaFirstItemAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
}
});
I hope it helps someone.
A: Check out http://developer.android.com/reference/android/provider/Settings.System.html.
You can read the flags:
*
*TRANSITION_ANIMATION_SCALE
*WINDOW_ANIMATION_SCALE
If they are 0, then animations are disabled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7529435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.