text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Converting 32 bit hexadecimals to decimal in java for an assignment I have to write a program that will take in an 8 character string(hexadecimal) and then convert it to base 10. I am not allowed to use any outside classes to do this. I'm pretty sure I have it working properly... for positive numbers only. My problem is how to show negative numbers.
an example is that FFFFFFFA should print out as -6
This is my code so far
package hexconverter;
import java.util.*;
/**
*
* @author Steven
*/
public class Main {
Scanner scanner = new Scanner(System.in);
public void doWork() {
System.err.println("Please enter the internal representation: ");
String hex;
hex = scanner.next();
hex = hex.toUpperCase();
long count = 1;
long ans = 0;
for (int i = 7; i >= 0; i--) {
Character c = hex.charAt(i);
if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
int num = fixLetters(c);
ans = ans + (num * count);
count = count * 16;
} else {
String s = c.toString(c);
long num = Integer.parseInt(s);
ans = ans + (num * count);
count = count * 16;
}
}
if (ans > 2147483647) {
System.out.println("is negative");
} else {
System.out.println(ans);
}
}
public int fixLetters(Character c) {
if (c.equals('A')) {
return 10;
} else if (c.equals('B')) {
return 11;
} else if (c.equals('C')) {
return 12;
} else if (c.equals('D')) {
return 13;
} else if (c.equals('E')) {
return 14;
} else if (c.equals('F')) {
return 15;
} else {
return 0;
}
}
public static void main(String[] args) {
// TODO code application logic here
Main a = new Main();
a.doWork();
}
}
I think my test for a negative integer is correct... since that is the highest value 32 bits can hold, anything over that will be an overflow so that means it should be negative.
From here I have no idea how to go about this. Any pointers or tips would be greatly appreciated. If there is no way to do it mathematically I feel like I am going to have to convert the hex into binary and then perform twos complements on it, but again I dont know where to start.
Thanks in advance
A: If the number is negative (> 2147483647) in your code, just subtract 2^32 (4294967296) from it. Then print it out.
if (ans > 2147483647) {
System.out.println(ans - 4294967296L);
} else {
System.out.println(ans);
}
A: In 32-bit 2's complement binary representation, the value of a negative is exactly 2 ^ 32 less than the value of the same bit pattern in unsigned representation. You have already identified that the number might be negative; all that's left to do is subtract 2 ^ 32.
Of course, 2 ^ 32 (4294967296 in decimal, or 0x100000000 in hex) is a value that can't be represented by Java's "int" type, so you'll need to use a "long":
if (ans > 2147483647) {
// System.out.println("is negative");
ans = ans - 0x100000000L;
System.out.println(ans);
} else {
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to use these sql scripts in oracle? I have a sql-script like:
@tables\run.sql;
@sequences\run.sql;
@views\run.sql;
@functions\run.sql;
@procedures\run.sql;
And I have two questions:
*
*Do I need to imply all the related script-files into the db?
*I execute the SQL script above in the PL/SQL developer but unfortunately it prompts ORA-00900 problem. Why so?
A: The sql script you indicate is trying to run several other sql scripts it expects to find in a directory structure like this
run.sql (your script above)
/tables
run.sql
/sequences
run.sql
/views
run.sql
/functions
run.sql
/procedures
run.sql
You dont mention if you are on a windows machine or unix/linux. If you are on unix/linux, normally you would use the sqlplus command line to run this script from the directory containing the top level run.sql (the one containing the commands you listed above).
PLSQL developer will run on windows so I assume it will use whichever directory is set as the "location" on the windows properties that you use to start plsql developer (probably something like c:\Program Files\plsqldev as a default so to find the scripts, it would expect the subdirectories (procedures/tables/view/sequences etc..) to be under that directory.
You will need all the scripts and to keep the subdirectory structure on either your windows client machine where plsql developer is running or on the database server where the Oracle database resides in order to run the script you have indicated above.
A:
"I execute the SQL script above in the PL/SQL developer but
unfortunately it prompts ORA-00900 problem. Why so?"
One of the, er, charms of PLSQL Developer is that it has many different types of windows which can do different things. It sounds like you are trying to run this script in a SQL window. Run it in a Command window instead, which is basically a SQL*Plus emulator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Iphone, Obtaining a List of countries from MonoTouch Is it possible to replicate what the code in here does in MonoTouch?
Here is what I've tried so far:
foreach(string countryCode in NSLocale.ISOCountryCodes){
// How to convert this objective-c code to c#?
// [[NSLocale currentLocale] displayNameForKey:NSLocaleCountryCode value:countryCode]
}
A: Sadly a quick look shows that displayNameForKey:value: to be (currently as of 4.2.x) missing from MonoTouch (and MonoMac) bindings. I'll look into implementing it and will update this entry once done.
UPDATE : Source code to work around the missing binding
public void DisplayCountryCodeNames ()
{
NSLocale current = NSLocale.CurrentLocale;
IntPtr handle = current.Handle;
IntPtr selDisplayNameForKeyValue = new Selector ("displayNameForKey:value:").Handle;
foreach (var countryCode in NSLocale.ISOCountryCodes) {
using (var key = new NSString ("kCFLocaleCountryCodeKey")) {
using (var nsvalue = new NSString (countryCode)) {
string ret = NSString.FromHandle (MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (handle, selDisplayNameForKeyValue, key.Handle, nsvalue.Handle));
Console.WriteLine ("{0} -> {1}", countryCode, ret);
}
}
}
}
Adapt to your liking and have fun with MonoTouch!
p.s. I'll update the bindings so it will be included in future releases for MonoTouch in a more proper API ;-)
A: Yes, it is certainly possible. MonoTouch wraps the iOS API in C# classes so that you can do anything in C# that you can do in Objective-C. Unfortunately you have to download the trial version to get the documentation. I imagine the code would look something like this:
foreach(string countryCode in NSLocale.ISOCountryCodes){
string CountryName = NSLocale.displayNameForKey(NSLocaleCountryCode, countryCode);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: old function don't work in php 5.35 function goto($herf) {
echo ("<script>window.location.href='".$herf."'</script>");
}
the above function work well before php 5.3.5, after i upgrade my php to 5.3.5, the following error displayed.
Parse error: syntax error, unexpected T_GOTO, expecting T_STRING or '(' in C:\xampp\htdocs\directory\directory\directory\directory\file.php on line 9
what is that error refer?
A: They added goto to the php language, which makes it a reserved word and no longer available as a function name.
The goto operator is available as of PHP 5.3.
A: So solution is:
function location($herf) {
echo ("<script>window.location.href='".$herf."'</script>");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IE9 Double Form Submit Issue I am just wondering if anyone have some info or feedback about the situation I am in.
Currently I am facing a "Double Form Submit" issue, where I click the "Submit" button once, and it submit the form twice. This only happens in IE9, but I have only tested against Safari, Chrome (Latest), FF (Ver 5/6), IE8, and IE9.
Here is the code:
<!DOCTYPE html>
<html lang="en-us" dir="ltr">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<title>IE9 test</title>
</head>
<body>
<h1>Testing</h1>
<form method="POST" id="submit_form">
<input type="text" name="x" value="xxxx" />
<input type="text" name="y" value="yyyy" />
<button type="submit" class="btn_sign_in" id="btn_logon" onclick="this.disabled=true;document.forms[0].submit();">Submit</button>
</form>
</body>
</html>
The problematic part is:
onclick="this.disabled=true;document.forms[0].submit();"
The code has been in my site for ages, and this is the first time I have encountered double submit problem since IE9 only releases this year, and probably these days more and more people using IE9, and hence I have received users complaints about this problem.
The hardest part is that the double submit problem is not always reproducible. Sometimes it will double submit, sometimes it will submit once.
My current work around is change from:
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
and change to:
<meta http-equiv="X-UA-Compatible" content="IE=8" >
This forces IE9 to use IE8 compatibility and it will execute the Javascript properly for for submission.
I have called Microsoft support, and they claim this is a "Javascript compatibility issue", so we will need to fine tune our Javascript to have our site work properly under IE9..(Duh!)
Anyway, is my code:
onclick="this.disabled=true;document.forms[0].submit();"
is already wrong to begin with? Because even though other browsers are not complaining, but probably this is not right to be begin with?
I am hoping if someone also faces similar issues have some more info or feedback.
Currently if I don't change X-UA-Compatible to IE=8, I can change my code to:
onclick="this.disabled=true;"
This will also solve the double submit issue, but is there also a list of IE9 compatibility issues that we should take note on?
Thanks!
A: Abstracting out the complexity, the issue seems to be that IE9 submits forms twice with
one button click when the submit event is fired in javascript.
In general, I found doing this fixes the IE9 double
form submission problem:
(failing IE9 double submission HTML):
<input type="submit" />
(IE9 html double submission fix):
<input type="submit" onclick="return false; " />
So basically, I am handling the form submission in javascript ( not shown) with an event listener ( click ) , but returning false on the old school event handler ( onclick) which IE9 seems to call automatically even if you have already handled it through an event listener.
I'm guessing you could do the same in pure javascript:
inputElement.onclick = function(){ return false; };
but I did not test it.
A: This code is wrong:
onclick="this.disabled=true;document.forms[0].submit();"
The onclick Javascript does not guarantee that the normal submit will not execute as well. For that it needs to return false, like this:
onclick="this.disabled=true;document.forms[0].submit(); return false;"
Is this change in behavior an IE9 bug? It depends, this could depend on legal behavior that is the result of timing issues. It's only a bug if the DOM/Javacript standard guarantees that the document.submit() is the end of all execution in a document. I doubt that this is the case.
A: since you already have the code to perform .submit(), why not change the button type to simple button instead of submit?
A: I don't know for sure that this is the problem, but, translated to plain english, your code appears to be saying "On clicking the submit button, turn the disabled attribute to true, and then submit the form."
But, since clicking the submit button already submits the form, maybe your browser is receiving two requests to submit - once when you click the button, and the second time when your javascript tells it to submit.
If you are not doing ajax, just a regular submit, you should be able to return true instead of calling submit - essentially, tell the browser to go ahead and do the default action (which is submit).
Or really, kill the whole submit() portion entirely, since it's redundant.
A: Part of the problem is that I believe you're submitting twice. You need to stop the first event before you start the second. See this post for more information on stopping events using inline javascript: How to stop event propagation with inline onclick attribute?
A: When you use
onclick="document.forms[0].submit();"
on the submit button, write input type="button" instead of type="submit",
A: we had the same problem in IE9 and we solved the issue by setting cancelBubble and returnValue flags of event to true and false respectively.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How to replace a word in a String? I'm using a String like:
String message = "%%NAME is inviting you";
I am using message.replaceAll("%%NAME", me); where me is a String. This line of code is not working for me. I was wondering what I was doing wrong?
A: I would suggest using the format method instead of replaceAll in this case.
UPDATE - Example
String template = "%s is inviting you";
String name = "Bob";
String result = String.format(template, name);
A: String message = "%%name is inviting you";
String uname = "Keyser Sose";
message.replaceAll("%%name", uname);
...will not modify 'message' because Strings (in java) are immutable
String message = "%%name is inviting you";
String uname = "Keyser Sose";
message = message.replaceAll("%%name", uname);
..WILL work. (Note the re-assignment of 'message')
A: Rythm a java template engine now released with an new feature called String interpolation mode which allows you do something like:
String result = Rythm.render("@name is inviting you", "Diana");
The above case shows you can pass argument to template by position. Rythm also allows you to pass arguments by name:
Map<String, Object> args = new HashMap<String, Object>();
args.put("title", "Mr.");
args.put("name", "John");
String result = Rythm.render("Hello @title @name", args);
Note Rythm is VERY FAST, about 2 to 3 times faster than String.format and velocity, because it compiles the template into java byte code, the runtime performance is very close to concatentation with StringBuilder.
Links:
*
*Check the full featured demonstration
*read a brief introduction to Rythm
*download the latest package or
*fork it
A: Code looks more or less OK, though there may be some syntax issues. Here's a working example:
String message = "%%NAME is inviting you.";
String name = "Diana";
String result = message.replaceAll("%%NAME", name);
A: To replace a string character with another string using StringUtil.Replace, I tried following and it's working fine for me to replace multiple string values from a single string.
String info = "[$FIRSTNAME$][$LASTNAME$][$EMAIL$]_[$ADDRESS$]";
String replacedString = StringUtil.replace(info, new String[] { "[$FIRSTNAME$]","[$LASTNAME$]","[$EMAIL$]","[$ADDRESS$]" }, new String[] { "XYZ", "ABC" ,"abc@abc.com" , "ABCD"});
This will replace the String value of info with newly provided value...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Using pandas, how do I subsample a large DataFrame by group in an efficient manner? I am trying to subsample rows of a DataFrame according to a grouping. Here is an example. Say I define the following data:
from pandas import *
df = DataFrame({'group1' : ["a","b","a","a","b","c","c","c","c",
"c","a","a","a","b","b","b","b"],
'group2' : [1,2,3,4,1,3,5,6,5,4,1,2,3,4,3,2,1],
'value' : ["apple","pear","orange","apple",
"banana","durian","lemon","lime",
"raspberry","durian","peach","nectarine",
"banana","lemon","guava","blackberry","grape"]})
If I group by group1 and group2, then the number of rows in each group is here:
In [190]: df.groupby(['group1','group2'])['value'].agg({'count':len})
Out[190]:
count
a 1 2
2 1
3 2
4 1
b 1 2
2 2
3 1
4 1
c 3 1
4 1
5 2
6 1
(If there is an even more concise way to compute that, please tell.)
I now want to construct a DataFrame that has one randomly selected row from each group. My proposal is to do it like so:
In [215]: from random import choice
In [216]: grouped = df.groupby(['group1','group2'])
In [217]: subsampled = grouped.apply(lambda x: df.reindex(index=[choice(range(len(x)))]))
In [218]: subsampled.index = range(len(subsampled))
In [219]: subsampled
Out[219]:
group1 group2 value
0 b 2 pear
1 a 1 apple
2 b 2 pear
3 a 1 apple
4 a 1 apple
5 a 1 apple
6 a 1 apple
7 a 1 apple
8 a 1 apple
9 a 1 apple
10 a 1 apple
11 a 1 apple
which works. However, my real data has about 2.5 million rows and 12 columns. If I do this the dirty way by building my own data structures, I can complete this operation in a matter of seconds. However, my implementation above does not finish within 30 minutes (and does not appear to be memory-limited). As a side note, when I tried implementing this in R, I first tried plyr, which also did not finish in a reasonable amount of time; however, a solution using data.table finished very rapidly.
How do I get this to work rapidly with pandas? I want to love this package, so please help!
A: I tested with apply, it seems that when there are many sub groups, it's very slow. the groups attribute of grouped is a dict, you can choice index directly from it:
subsampled = df.ix[(choice(x) for x in grouped.groups.itervalues())]
EDIT: As of pandas version 0.18.1, itervalues no longer works on groupby objects - you can just use .values:
subsampled = df.ix[(choice(x) for x in grouped.groups.values())]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: cache required serialized object I try to store (List-> with many pojo objects) into memcache. the requirement is the value(object) need to implements serializable. is there any technique to use memcache.put(value) , without required to implement serializable for (List-> with many pojo objects) ?
will java outputList= Collection.singletonList(inputList); memcache(key, outputList); will this work?
A: No, I do not think it will. The List collection knows how to serialize itself, but not how to serialize the objects it contains. Thus, the job of serialization falls on to the individual objects, and rightfully so since the object is really the only thing that can know its full state.
Implementing Serializable is pretty trivial, unless there are some unstated circumstances?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tag friends in a Photo This is my code. It does not show any errors but only the first 2 friends are tagged!
for ($i=0;$i<count($friendsID);$i++)
{
$post_url = "https://graph.facebook.com/".$upload_photo['id']."/tags/".$friendsID[$i]."?access_token=".$token."&x=80&y=".$y."&method=POST";
$response = file_get_contents($post_url);
$post_url = urlencode($post_url);
$response = file_get_contents($post_url);
$y = $y + 53;
}
I'm not receiving any error, but the code just does not tag all the people supposed to be tagged !
A: According to the "Publishing" section in the Facebook Developer API docs, writes to the graph must be POST'ed. Your request as written uses GET. See this question for how to convert your request to a POST.
As an aside, note that urlencode should only be applied to the parameters of a URL, not the entire URL. Otherwise the colons & slashes in the base part of your URL will get encoded as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Close Animation will not run In my iPhone app there is a window that appears over the main window. Here is the code for my close button;
-(IBAction)cancel{
[UIView beginAnimations:@"Animation" context:nil];
[UIView setAnimationDuration:0.75];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
[self.view removeFromSuperview];
//[_window addSubview:view2];
[UIView commitAnimations];}
The window closes correctly but the animation will not execute. I do not understand why.
thanks
A: I think it is because you are removing the view from the superview during the animation. The animation does not occur because the view is gone. You should wait until after the animation finishes to remove to view, which you can do by setting a delegate and selector which is called when the animation is finished.
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
And then in
-(void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
[self.view removeFromSuperview];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get all zip code using google map api which are lies in between sourece and destination pa I have a requirement to implement google map direction.User will supply source and destination.Then the full path will be shown in google map.It also show all the zip code which are lies on this path.
I dig around Google but could not found any solution to get zip code.
Please help me if you have any advise.
A: You could use the geocoder service to get the address information for your various points along your path. The GeocoderResults object has an address array, which has a postal_code type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PowerPoint - How to attach a label to a line graphic When you add a polygon shape to PowerPoint, you can attach/embed a textbox inside it. When you move or rotate the polygon shape, the text adjusts with it.
How can I do this with a line shape?
In the example below, I rotated and moved both boxes, and the text and lines updated automatically. The label didn't move and is no longer associated with the line.
How can I "attach" the label to the line?
Thanks.
A: Most shapes have a text frame; that's the "container" for any text in the shape. Lines don't have a text frame, so can't hold text.
So you cheat.
Simplest dodge would be to create a separate text box and group it with the line.
Or you can draw a rectangle, give it no outline, make its fill the color you want your line to be, then set its height to whatever line width you want. The rectangle can hold text. By default, the text will sit atop the line, which isn't what you want here, so add a line feed to the beginning or end of the text to bump it below or above the line slightly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Bit wise operations in C I'm working on a C programming assignment, I need to simulate the operation of a 3 bit decoder. My compiler is complaining, this Wikipedia article gives a list of C operators, but my code still seems not to be working.
Wikipedia: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Bitwise_operators
Compiler error:
logic.c: In function βthree_bit_decoderβ:
logic.c:33: warning: statement with no effect
logic.c:33: error: expected β;β before β~β token
logic.c:34: warning: statement with no effect
logic.c:34: error: expected β;β before βb0β
logic.c:35: warning: statement with no effect
logic.c:35: error: expected β;β before β~β token
logic.c:36: warning: statement with no effect
logic.c:36: error: expected β;β before βb0β
logic.c:38: warning: statement with no effect
logic.c:38: error: expected β;β before βb0β
logic.c:39: warning: statement with no effect
logic.c:39: error: expected β;β before βb0β
logic.c:40: warning: statement with no effect
logic.c:40: error: expected β;β before β~β token
logic.c:41: warning: statement with no effect
logic.c:41: error: expected β;β before βb0β
logic.c:43: warning: return makes integer from pointer without a cast
logic.c:43: warning: function returns address of local variable
make: *** [logic.o] Error 1
Code:
int three_bit_decoder(BIT b0, BIT b1, BIT b2) {
/* Returns an 8 bit number, by 2^3
*
*/
int myIntDecoder[8];
myIntDecoder[0] ~b0 + ~b1 + ~b2;
myIntDecoder[1] b0 + ~b1 + ~b2;
myIntDecoder[2] ~b0 + b1 + ~b2;
myIntDecoder[3] b0 + b1 + ~b2;
myIntDecoder[4] b0 + ~b1 + ~b2;
myIntDecoder[5] b0 + ~b1 + b2;
myIntDecoder[6] ~b0 + b1 + b2;
myIntDecoder[7] b0 + b1 + b2;
return myIntDecoder;
}
A: If those are assignment statements you're missing equal signs.
myIntDecoder[0] = ~b0 + ~b1 + ~b2;
myIntDecoder[1] = b0 + ~b1 + ~b2;
myIntDecoder[2] = ~b0 + b1 + ~b2;
myIntDecoder[3] = b0 + b1 + ~b2;
myIntDecoder[4] = b0 + ~b1 + ~b2;
myIntDecoder[5] = b0 + ~b1 + b2;
myIntDecoder[6] = ~b0 + b1 + b2;
myIntDecoder[7] = b0 + b1 + b2;
The next problem you'll encounter is that int myIntDecoder[8] declares an array of 8 ints, which is not the same as an 8-bit int. A char is 8 bits wide on (almost) all platforms; or you can be more explicit and use one of the standard typedefs:
#include <stdint.h>
uint8_t myIntDecoder;
So as not to leave you hanging, I should mention that assigning to individual bits in a variable is not as simple as byte[5] = 1. Doing it requires some clever use of shifting and other bitwise operations.
A: The bitwise operators are not your problem, you have syntax errors in your code. Think about how to do assignment of variables and the solution should come to you.
A: Presumably you're after something like:
myIntDecoder[0] = ~b0 + ~b1 + ~b2;
// and likewise for the other 7 lines
That won't help with trying to return myIntDecoder though. For that, you'd probably want to move the array outside the function and (for one example) pass its address into the function.
A: you are missing the equals operator.
myIntDecoder[7] = b0 + b1 + b2;
Also the not operator in c is ! not ~
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Using htaccess Files for Pretty URLS - Opencart how to write htaccess if my opencart home page is http://www.stico.com.my/index.php?route=product/category&path=20_59 , i want url to be like this
http://www.stico.com.my
My client want page product category set as homepage.
i hope someone can help me.
A: Add this to your .htaccess below the existing RewriteRules
RewriteCond %{QUERY_STRING} =""
RewriteRule ^index.php$ index.php?route=product/category&path=20_59 [L]
Optional, if you want Pretty URLs
You should be able to use SEO URLs to get pretty URLs for your products.
Admin > System > Settings > Edit YOUR_STORE > Server:
Make sure Use SEO URLs is checked and make sure the htaccess.txt file has been renamed to .htaccess.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Enforcing development cycle through Bugzilla I work on a project with a pretty formal development process: there's a list of required documents, from requirements to design to testing to user documentation. We're trying figure out how to make sure all feature development goes through all the stages.
One idea is to use Bugzilla's Status field to capture the workflow; we'd add the following status entries and make bugs go through all of them before being resolved:
UNCONFIRMED
NEEDSREQUIREMENTS
NEEDSUIDESIGN
NEEDSDESIGN
NEEDSIMPLEMENTATION
NEEDSDOC
NEEDSTEST
RESOLVED
CLOSED
Has anyone tried capturing a development process through Bugzilla like this? Is there another approach or tool that would be a better fit?
A: You should use requestable flags. For example: a flag called "ui-design." Then you set it to "?" to mean "needs UI design" and "+" to mean "has UI design" or "-" to mean "doesn't need UI design".
A: I think you would be better off using flags for capturing this workflow. Having a busy state transition diagram through which you try to enforce workflow would sometimes be annoying when there's some valid reason for handing one bug a little bit differently.
For example, you could have two flags needs-ui-design and ui-design-complete to describe the status of UI design. UI designers could easily search for bugs that have needs-ui-design set to + but that do not have ui-design-complete set to +.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Overriding method with generic return type in Java When using generics in the return type, I'm having trouble extending a parent class
like following example.
As you know, without generics, the following example will be compiled normally, but it won't be type safe because it's type should be Object.
Is there any clear solution (or pattern, or advice, anything will be helpful!) that I can refer to?
class AbstractReader<T>{
public abstract T readNext();
}
class ByteArrayReader extends AbstractReader<byte[]>{
@Override
public byte[] readNext(){ /*...*/ }
}
class StringReader extends ByteArrayReader {
@Override
public String readNext() {
/* The return type is incompatible
with ByteArrayReader.readNext()! */
return new String(bytes);
}
}
A: The problem here is that there it doesn't make sense for StringReader to extend ByteArrayReader. You have confused inheritance with composition.
When StringReader inherits from ByteArrayReader you are saying that it will fulfill a contract that says it has a readNext method that returns a byte[].
What you really want to do is use composition rather than inheritance:
class StringReader extends AbstractReader<String> {
private AbstractReader<byte[]> downstream;
public StringReader(AbstractReader<byte[]> downstream) {
this.downstream = downstream;
}
public String readNext() {
return new String(downstream.readNext());
}
}
This StringReader fulfills the AbstractReader<String> contract, and is implemented in terms of a downstream AbstractReader<byte[]>. Note that it does not explicitly require a ByteArrayReader - any old AbstractReader<byte[]> will work.
A: You could use the Decorator Design Pattern instead of inheritance:
class StringReader {
private ByteArrayReader bar;
public StringReader(ByteArrayReader bar) {
this.bar = bar
}
public String readNext() {
return new String(this.bar.readNext());
}
}
A: What your problems are trying to tell you is that this isn't a good use of inheritance. A StringReader definitely doesn't have an is-a relationship to a ByteArrayReader. If there's some functionality in common between them, that's merely an implementation detail. Any such common code should be pushed up to AbstractReader from which both should extend directly. Then the abstract class correctly contains code common to its subclasses and StringReader and ByteArrayReader are correctly unrelated besides being implementations of the same thing (presumably a Reader).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AutoSuggest component in standard JSF 2.0 component set Is there a Google-like autosuggest input component in standard JSF 2.0 component set?
A: The standard JSF <h:xxx> component set doesn't have such a component. All it offers are just basic HTML elements. An autosuggest field is basically a combination of an <input type="text"> and an <ul><li> of items which is created and positioned by JavaScript and filled by Ajax and styled by a good shot by CSS. This is not a single basic HTML element.
Implementing your own isn't exactly trivial if you're new to JSF. Simplest would be to create a composite component with a <h:inputText> and add the necessary JS/CSS code yourself. Fortunately, there exist JSF component libraries which adds just that extra on top of the standard JSF components and often already provides such a component out the box. For example:
*
*RichFaces: <rich:autocomplete>
*PrimeFaces: <p:autoComplete>
*OpenFaces: <o:suggestionField>
*IceFaces: <ice:selectInputText>
(note: all tags above are clickable and show you the online demo)
A: If you don't wish to add a component library to your JSF project, you could instead integrate the jQuery autocomplete widget. This is a client-side JavaScript solution which is agnostic to the server-side technology. Adding this widget will therefore have little on no impact on your server-side code.
http://jqueryui.com/demos/autocomplete/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Maps markers with directions renderer So I want to plot a route using directions renderer and at the same time have Origin as an "A" marker, all the way through the destination as the final marker, with all waypoints also being marker.
By default it looks like renderer only sets markers for origin and destination, so I plotted markers for all the waypoints.
However, the directionsrenderer markers are "A" for origin and "B" for destination, meanwhile my second waypoint is also "B".
How do I get all the waypoints on chronological order of the route to show the correct marker with correct letter? Here's an image of the problem:
Thanks
A: You should be able to inspect DirectionsRoute.waypoint_order to get an array of which order the waypoints are ordered in. Then I'd say use that to work out which letters to assign to each waypoint marker
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Additional bytes received by a DatagramPacket I have a problem that I see for the first time ever, I'm using java DatagramSocket (s) for sending and receiving data in my app.
this is how I send the data:
byte[] buffer = "my data".getBytes();
senderPacket = new DatagramPacket(buffer, 0, buffer.length, remoteAddress, remotePort);
socket.send(senderPacket);
now when I sent the byt[] buffer, it's size was 275.
but when I received the packet on the receiving app and got the byte[] from the receiverPacket, like this:
buffer = new byte[2048];
receiverPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receiverPacket);
I found that the received bytes count where 278 bytes that's additional 3 bytes.
This might seem like not a big problem, but actually it is for me, please any idea why is this happening, and how to solve it, any logical explanation would be helpful.
thanks
A: The 3 extra bytes could be a length marker. I know that when I do sockets in C/C++, I typically dedicate the first 4 bytes to sending the length of my message, and then I use that data to determine how much to read in order to read the entire message.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change the brightness on iPhone (using private APIs) I want to make an app similar to SBSettings (a quick settings application on Cydia) because developers can't jailbreak their devices. Can someone tell me how to change the screen brightness? It doesnt need to be approved by Apple, so it can use private APIs if needed. Any help would be appreciated.
A: You can use [[UIScreen mainScreen] setBrightness:0.1] in iOS 5.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Passing IndexPath between views I am trying to pass the indexpath of my subview over to my main view. I am doing this through delegates and protocols that I have alread set up, I have just slightly edited the method I call to accept the indexpath.. so everything seems to work correctly however when I do the NSLog from both views I get the output below in my terminal.. I would like to know what dose the "0x4e1fdc0" represent in the output? is that a memory pointer or something?
Also now that I have the selected indexpath in my mainview, if the user decides to go back to the subview how can i pass it back to the subview? do I need to make a new delegate/protocol to pass the information forward? or can I do it another way..
2011-09-28 15:02:13.672 Code[14139:207] First View <NSIndexPath 0x4e1fdc0> 2 indexes [0, 0]
2011-09-28 15:02:13.673 Code[14139:207] Second View <NSIndexPath 0x4e1fdc0> 2 indexes [0, 0]
A: Yes that is the memory pointer, a NSIndexPath is just a path to a node in a tree of nested array collections, so 0, 0, means position 0 in array 1 and then position 0 in array 2.
NSIndexPath reference
You can pass it to the subview using Dependency Injection so basically just declare this on your subview:
"MyFile.h"
@property (nonatomic, retain) NSIndexPath *myPath;
"MyFile.m"
@synthesize myPath;
"MainView.m"
// After allocating the subview, or whenever you are going to show the subView
[mySubView setIndexPath:myPath];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get (-8)^0.333333 = -2 in MATLAB? Using MATLAB exponential function:
(-8)^0.333333
ans = 1.0000 + 1.7320i
How to get (-8)^0.333333 = -2 instead?
x=-10:-1;
x.^0.333333
How to get real value?
How to redefine ^:
x.^y
to
sign(x).*abs(x.^y))
A: There are 3 possible answers for the cube root of -8: -2, 1+/- sqrt(3)
You probably want nthroot(-8,3) --> -2
A: MATLAB 7.0 provides the NTHROOT function, which returns the real roots of a number. So your formula becomes NTHROOT(-8, 3) = -2
If you are using a version prior to MATLAB 7.0 (R14), please read the following:
To obtain the real cube root of a negative real number "x", rather than executing:
x.^(1/3)
use the command:
sign(x).*abs(x.^(1/3))
This will find the absolute value of the root and modify it by the sign of the argument.
See this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to embed an executable program in another as if the iframe does in HTML I have an existing GUI program named A.
How can I write another program in Visual C++ which hosts A as a CView or something similar.
Just like a html inside another html using iframe.
Thank you.
A: Yes it is possible to do that, However you would have to provide a container control on the hosting application. I embedded Google Earth into a tracking app I was developing in C# with a similar method.
Method
*
*Use Windows Hook to capture program "A" on process start.
*Use spy++ to find out the window handle for "A"
*Use SetWindowPosEx function to make your host container the parent for "A"
*NB The windows hook will be a global hook so the code has to be bullet proof, and the hooking code must reside in a .dll file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display sidebar on main page only be default, other places can optionally override I want my main page to display a side bar, and then for all other pages it should not display anything unless I explicitly want to.
How can I do this?
A: If you have in your _Layout.cshtml
@RenderSection("sidebar", required: false);
it will do what you want.
You can then display the sidebar section on any page where it makes sense but it won't be required to be there.
A: I'd suggest using a common view model from which your other models derive. Store the information needed for the sidebar (or to load the sidebar via AJAX) in the common view model. Part of the model can also be a flag that indicates whether to show the sidebar or not. Have your layout strongly-typed to the common model and insert the sidebar into the HTML if the model indicates that it should be shown.
You can either populate the model in each action or in OnActionExecuted in your controller.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Emacs truncate lines in all buffers What can I put in my .emacs file so that all lines an any kind of buffer always truncate if too long. I do this mostly because I tend to open many frames and it gets hard to read on a small screen if my 80 char lines get wrapped 2 or 3 times over.
A: Try M-x toggle-truncate-lines on a per buffer basis, to see if it does what you want.
In .emacs you'd put this, to make it default for all buffers.
(setq-default truncate-lines t)
You may also like:
(setq-default global-visual-line-mode t)
Which you can try out with M-x visual-line-mode (it also toggles.)
EmacsWiki references: visual-line-mode truncate-lines
A: In your .emacs or .emacs.el or .emacs.d/init.el (depends where you locate your main emacs config file), write :
(custom-set-variables
'(truncate-lines t))
the block custom-set-variables may already exist, so just add '(truncate-lines t) to the list. This way your configuration file keeps clean.
Alternatively you could hook a keybinding, like that :
(local-set-key (kbd "C-x w") 'toggle-truncate-lines)
So you can truncate when the lines are bothering the visual
A: If the (setq-default truncate-lines t) didn't work, it's possible that you are in another major mode, ie markdown-mode, etc. In that case, this worked for me. (I tested it on Emacs v28.1 / Doom Emacs on Mac)
;; in init.el, etc...
;; word-wrapping off
(setq-default truncate-lines t)
;; for markdown-mode
(add-hook 'markdown-mode-hook (lambda () (setq truncate-lines t)))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Parallel wget in Bash I am getting a bunch of relatively small pages from a website and was wondering if I could somehow do it in parallel in Bash. Currently my code looks like this, but it takes a while to execute (I think what is slowing me down is the latency in the connection).
for i in {1..42}
do
wget "https://www.example.com/page$i.html"
done
I have heard of using xargs, but I don't know anything about that and the man page is very confusing. Any ideas? Is it even possible to do this in parallel? Is there another way I could go about attacking this?
A: You can use -b option:
wget -b "https://www.example.com/page$i.html"
If you don't want log files, add option -o /dev/null.
-o FILE log messages to FILE.
A: Just running the jobs in the background is not a scalable solution: If you are fetching 10000 urls you probably only want to fetch a few (say 100) in parallel. GNU Parallel is made for that:
seq 10000 | parallel -j100 wget https://www.example.com/page{}.html
See the man page for more examples:
http://www.gnu.org/software/parallel/man.html#example__download_10_images_for_each_of_the_past_30_days
A: Adding an ampersand to a command makes it run in the background
for i in {1..42}
do
wget "https://www.example.com/page$i.html" &
done
A: Much preferrable to pushing wget into the background using & or -b, you can use xargs to the same effect, and better.
The advantage is that xargs will synchronize properly with no extra work. Which means that you are safe to access the downloaded files (assuming no error occurs). All downloads will have completed (or failed) once xargs exits, and you know by the exit code whether all went well. This is much preferrable to busy waiting with sleep and testing for completion manually.
Assuming that URL_LIST is a variable containing all the URLs (can be constructed with a loop in the OP's example, but could also be a manually generated list), running this:
echo $URL_LIST | xargs -n 1 -P 8 wget -q
will pass one argument at a time (-n 1) to wget, and execute at most 8 parallel wget processes at a time (-P 8). xarg returns after the last spawned process has finished, which is just what we wanted to know. No extra trickery needed.
The "magic number" of 8 parallel downloads that I've chosen is not set in stone, but it is probably a good compromise. There are two factors in "maximising" a series of downloads:
One is filling "the cable", i.e. utilizing the available bandwidth. Assuming "normal" conditions (server has more bandwidth than client), this is already the case with one or at most two downloads. Throwing more connections at the problem will only result in packets being dropped and TCP congestion control kicking in, and N downloads with asymptotically 1/N bandwidth each, to the same net effect (minus the dropped packets, minus window size recovery). Packets being dropped is a normal thing to happen in an IP network, this is how congestion control is supposed to work (even with a single connection), and normally the impact is practically zero. However, having an unreasonably large number of connections amplifies this effect, so it can be come noticeable. In any case, it doesn't make anything faster.
The second factor is connection establishment and request processing. Here, having a few extra connections in flight really helps. The problem one faces is the latency of two round-trips (typically 20-40ms within the same geographic area, 200-300ms inter-continental) plus the odd 1-2 milliseconds that the server actually needs to process the request and push a reply to the socket. This is not a lot of time per se, but multiplied by a few hundred/thousand requests, it quickly adds up.
Having anything from half a dozen to a dozen requests in-flight hides most or all of this latency (it is still there, but since it overlaps, it does not sum up!). At the same time, having only a few concurrent connections does not have adverse effects, such as causing excessive congestion, or forcing a server into forking new processes.
A: wget version 2 implements multiple connections.
https://github.com/rockdaboot/wget2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: after fork/execvp control does not return to parent when i run my code below and type in "ls" at the prompt it runs ls in the terminal but then just sits there and doesnt print my prompt again. How do I get control to go back to the parent process?
Thanks
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char* argv[]){
while(1){
print_the_prompt();
char user_text[100];
if( fgets(user_text, sizeof(user_text), stdin) != NULL ){
char* nl_char = strchr(user_text, '\n');
if( nl_char != NULL ){
*nl_char = '\0';
}
}
//printf("user_text = \"%s\"\n", user_text);
if( is_command_built_in(user_text) ){
//run built in command
}
else{
//run regular command
execute_new_command(user_text);
}
}
return 0;
}
void print_the_prompt(){
printf("!: ");
}
int is_command_built_in(char* command){
return 0;
}
void execute_new_command(char* command){
pid_t pID = fork();
if(pID == 0){
//is child
char* execv_arguments[] = { command, (char*)0 };
execvp(command, execv_arguments);
}
else{
//is parent
printf("im done");
}
}
A: The answer is probably that the parent prints "im done" immediately after starting the child (remember it's a separate process and therefore runs in parallel), and then loops back around to print the prompt before the child even starts listing files. If you scroll back you'll probably find your next prompt.
To have the parent wait for the child to finish, you will have to use one of the wait() family of functions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linux start-up script for java application I have Jar file to run in Linux using this command:
java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13
Can anyone let me know how to create script and implement this process automatically while we restart our computer? In windows we use services but how about linux?
Can u provide to me the script and step to do that since i am really new in Linux...
Linux : RHat, Ubuntu
Thanks
A: I would start with this template for a startup script rename the SCRIPT_HOME to proper path and call this file without any extensions, then in SSH run this command.
chkconfig βadd javaserver
Note the javaserver in the chkconfig is how you called the file below, (no extensions or it wont work).
#!/bin/bash
#
# javaserver: Startup script for Any Server Application.
#
# chkconfig: 35 80 05
# description: Startup script for Any Server Application.
SCRIPT_HOME=/var/java_server;
export SCRIPT_HOME
start() {
echo -n "Starting Java Server: "
$SCRIPT_HOME/run.sh start
sleep 2
echo "done"
}
stop() {
echo -n "Stopping Java Server: "
$SCRIPT_HOME/run.sh stop
echo "done"
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo $"Usage: javaserver {start|stop|restart}"
exit
esac
Now here is the script the run.sh (this can be used instead of the template but I find it easier to make the template script small and unchangeable link to my main script so I never have to touch it again.
The script below is one of a very few scripts I found that actually can restart a java program without turning off all the java programs you currently have running, this one only targets the program it opened in the first place so it will never make any mistakes, never had it fail on me, run on user root no problem.
Runs your program in the background forever too (no need to keep SSH opened).
This is the run.sh
#!/bin/bash
#
# chkconfig: 345 99 05
# description: Java deamon script
#
# A non-SUSE Linux start/stop script for Java daemons.
#
# Set this to your Java installation
JAVA_HOME=/usr/bin/
scriptFile=$(readlink -fn $(type -p $0)) # the absolute, dereferenced path of this script file
scriptDir=$(dirname $scriptFile) # absolute path of the script directory
serviceNameLo="javaserver" # service name with the first letter in lowercase
serviceName="JavaServer" # service name
serviceUser="root" # OS user name for the service
serviceGroup="root" # OS group name for the service
applDir="/var/java_server" # home directory of the service application
serviceUserHome="/home/$serviceUser" # home directory of the service user
serviceLogFile="/var/log/$serviceNameLo.log" # log file for StdOut/StdErr
maxShutdownTime=15 # maximum number of seconds to wait for the daemon to terminate normally
pidFile="/var/run/$serviceNameLo.pid" # name of PID file (PID = process ID number)
javaCommand="java" # name of the Java launcher without the path
javaArgs="MyJavaAppClass" # arguments for Java launcher
javaCommandLine="$JAVA_HOME$javaCommand $javaArgs" # command line to start the Java service application
javaCommandLineKeyword="MyJavaAppClass" # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others
# Makes the file $1 writable by the group $serviceGroup.
function makeFileWritable {
local filename="$1"
touch $filename || return 1
chgrp $serviceGroup $filename || return 1
chmod g+w $filename || return 1
return 0; }
# Returns 0 if the process with PID $1 is running.
function checkProcessIsRunning {
local pid="$1"
if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi
if [ ! -e /proc/$pid ]; then return 1; fi
return 0; }
# Returns 0 if the process with PID $1 is our Java service process.
function checkProcessIsOurService {
local pid="$1"
if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi
grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline
if [ $? -ne 0 ]; then return 1; fi
return 0; }
# Returns 0 when the service is running and sets the variable $pid to the PID.
function getServicePID {
if [ ! -f $pidFile ]; then return 1; fi
pid="$(<$pidFile)"
checkProcessIsRunning $pid || return 1
checkProcessIsOurService $pid || return 1
return 0; }
function startServiceProcess {
cd $applDir || return 1
rm -f $pidFile
makeFileWritable $pidFile || return 1
makeFileWritable $serviceLogFile || return 1
cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile"
# Don't forget to add -H so the HOME environment variable will be set correctly.
#sudo -u $serviceUser -H $SHELL -c "$cmd" || return 1
su --session-command="$javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile" $serviceUser || return 1
sleep 0.1
pid="$(<$pidFile)"
if checkProcessIsRunning $pid; then :; else
echo -ne "\n$serviceName start failed, see logfile."
return 1
fi
return 0; }
function stopServiceProcess {
kill $pid || return 1
for ((i=0; i<maxShutdownTime*10; i++)); do
checkProcessIsRunning $pid
if [ $? -ne 0 ]; then
rm -f $pidFile
return 0
fi
sleep 0.1
done
echo -e "\n$serviceName did not terminate within $maxShutdownTime seconds, sending SIGKILL..."
kill -s KILL $pid || return 1
local killWaitTime=15
for ((i=0; i<killWaitTime*10; i++)); do
checkProcessIsRunning $pid
if [ $? -ne 0 ]; then
rm -f $pidFile
return 0
fi
sleep 0.1
done
echo "Error: $serviceName could not be stopped within $maxShutdownTime+$killWaitTime seconds!"
return 1; }
function startService {
getServicePID
if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi
echo -n "Starting $serviceName "
startServiceProcess
if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
echo "started PID=$pid"
RETVAL=0
return 0; }
function stopService {
getServicePID
if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi
echo -n "Stopping $serviceName "
stopServiceProcess
if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
echo "stopped PID=$pid"
RETVAL=0
return 0; }
function checkServiceStatus {
echo -n "Checking for $serviceName: "
if getServicePID; then
echo "running PID=$pid"
RETVAL=0
else
echo "stopped"
RETVAL=3
fi
return 0; }
function main {
RETVAL=0
case "$1" in
start) # starts the Java program as a Linux service
startService
;;
stop) # stops the Java program service
stopService
;;
restart) # stops and restarts the service
stopService && startService
;;
status) # displays the service status
checkServiceStatus
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit $RETVAL
}
main $1
A: If you want to run the app as linux daemon (service) checkout Java Wrapper: http://wrapper.tanukisoftware.com/doc/english/download.jsp
Check this answer too (is for windows, but for linux changes a little bit): How to install a Java application as a service
A: While it is not recommended to sudo items like this, it can be accomplished by the following:
sudo crontab -e
Place the following in the cron:
@reboot java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13
A: Uhh first you might want to edit out your local ip thats more information that your giving out. Anyhow just open up a new document type this
#!/bin/bash
#put your commands in here
Save then open up terminal and type chmod +x nameofscript
Im not sure about ubuntu but on arch we have a place to run commands on startup.
My advice is to goto system->prefernces->start up applications or something along that line its in that menu I know.
Type the path to the script ie
/home/username/scrips/myawesomescript
A: Basically, you need to create a little shell script in /etc/init.d and make symlinks to /etc/rc2.d and /etc/rc5.d. The contents could be like this:
#!/bin/sh
if [ "$1" = start ] ; then
cd /put_your_workdir_here
/usr/bin/java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13 &
fi
Notice that you start your program in background (& at the end of the commandline)
A: you need to create a unix shell script file, that will automate the job for you.
Here are the steps to create the script file:
http://www.linuxquestions.org/questions/linux-general-1/shell-script-for-jar-utility-769461/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting up Sinatra to run in a subdirectory Now I am pretty new to Sinatra/Ruby/Apache but have inherited a Sinatra application to deploy.
Currently Apache is set up to run from a document root (httpdocs) and I need to run a ruby application underneath a folder subdirectory such as: /httpdocs/webapp
What do I need to do to get this up and running under a subdirectory?
A: This link might be helpful, it explains how to deploy a Sinatra app with Apache using Passenger (mod_rack):
Deploying a Sinatra App with Apache and Phusion Passenger
The part of particular interest to you is the RackBaseURI option in the virtual host configuration. The official documentation is available here:
Phusion Passenger users guide - Deploying Rack to Sub URI
A: I just ran into the same issue. Since there was no answer here for how to do this without Passenger, I'm going to document the solution for Apache + CGI or FastCGI.
The trick is to rewrite PATH_INFO for Rack, and everything will fall into place:
*
*Set up .htaccess:
RewriteEngine On
RewriteRule ^(.*)$ sinatra_app.cgi [QSA,L,E=PATHINFO:/$1]
*In your Sinatra code, before anything else:
ENV['PATH_INFO'] = ENV['REDIRECT_PATHINFO']
Now all URLs like /subfolder/resource/123 will hit the correct route in the Sinatra app.
In the above case get '/resource/:id' will work correctly, assuming the Sinatra app was put into /subfolder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Service with AsyncTask I have heard that it isnt good to have an async task in a service.
Is it really necessary for an AsyncTask or just onStartCommand()?
I am wondering because I have a Service with an AsyncTask that is launched by an alarm. And it launches the Service more than once; it's only supposed to launch once.
Could this be the reason?
EDIT:
Here is how i set up the alarm.
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager)getSystemService(alarm);
Intent Aintent = new Intent("REFRESH_THIS");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, 9);
calendar.add(Calendar.MINUTE, 0);
calendar.add(Calendar.SECOND, 0);
calendar.add(Calendar.MILLISECOND, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pi);
A: There is no bad thing if you want to use AsyncTask in service.
It is good if you are using asynctask in service because service runs on Main Thread so that if you are using long process from service it can slow your UI.
You can also create Thread and work in that.
A: If you have a long-running operation in a service, consider using IntentService, it will launch and manage a background thread for you. And it has the added benefit that it shuts itself down when finished automatically. You could achieve something similar with an AsyncTask, but an IntentService will do the right thing.
As for your other question, the service being launched multiple times has nothing to do with the AsyncTask. If your alarm runs multiple times, it will launch multiple instances of your service. There is, AFAIK, really no way to make a singleton service automatically. You could check if it's running before launching, or set a preferences flag (error prone), but the preferred way is to have short-lived services launched every time you need to do something, and shut themselves when done. IntentService fits this pattern nicely.
A: There is a way to having more control around threads and tasks, specially if you need to perform different ones in a certain order. There is a nice approach to manage the whole system by using queues, thread pool executors, runnables/callables and a service.
http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Purpose of Constructor chaining? After reading this Constructor chaining question I am just curious to know why would any one do constructor chaining?
Could some one please shed some light on type of scenarios where this might be useful.
Is this a good programming practice?
A: It's absolutely a good practice for two main reasons:
To avoid code duplication
class Foo
{
public Foo(String myString, Int32 myInt){
//Some Initialization stuff here
}
//Default value for myInt
public Foo(String myString) : this(myString, 42){}
//Default value for both
public Foo() : this("The Answer", 42){}
}
To enforce good encapsulation
public abstract class Foo
{
protected Foo(String someString)
{
//Important Stuff Here
}
}
public class Bar : Foo
{
public Bar(String someString, Int32 myInt): base(someString)
{
//Let's the base class do it's thing
// while extending behavior
}
}
A: The main reason is to be able to reuse code between constructors. Instead of duplicating initialization, you can put all of the initialization code in a single constructor, and call that one from other constructors.
A: βConstructor Chainingβ is an approach whereby a constructor calls another constructor in the same class. This is particularly useful when we have a class that defines multiple constructors. For example, we are creating a class called Person in the example below. We also have three fields that we can use; Age, Name and HairColour. This class has three constructors. If we did not use the βConstructor Chainingβ approach, the code would be something like below:
Not Using Constructor Chaining:
public class Person
{
private int Age;
private string Name;
private string HairColour;
public Person(int theAge)
{
Age = theAge;
}
public Person(int theAge, string theName)
{
Age = theAge;
Name = theName;
}
public Person(int theAge, string theName, string theHairColour)
{
Age = theAge;
Name = theName;
HairColour = theHairColour;
}
}
As you can see, in each constructor we are assigning a value to Age, which duplicates code. We have also assigned a value to Name in two of the constructors, so again more duplication. To eliminate this problem, we can assign all the values to Age, Name and HairColour in the constructor with the most parameters. We can then call that constructor when the other two constructors are called. See the code below to see this βChainingβ approach.
Using Constructor Chaining:
public class Person
{
private int Age;
private string Name;
private string HairColour;
public Person(int theAge):this(theAge, "", "")
{
//One parameter
}
public Person(int theAge, string theName):this(theAge, theName, "")
{
//Two Parameters
}
public Person(int theAge, string theName, string theHairColour)
{
//Three parameters
Age = theAge;
Name = theName;
HairColour = theHairColour;
}
}
Hope that helps - it saves on duplication.
A more 'extreme' example with lots of fields (and so lots of potential duplications) is shown here:
An example where it will definitely save on duplication
A: I've seen it when you've got some heavy lifting being done at construction time, and you've got lots of different ways of creating the object. (So handful of ctors with different parameter signatures).
You can just have a private member function which does the common work across ctors. You don't really need to have one ctor call another in the same class. (Which isn't even allowed in most languages).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Why isn't AJAX working in IE? Anything I'm missing with the code below? I'm a bit overwhelmed.
$("a[id^='submitspam']").click(function () {
var thisForm = $(this).attr('id');
var com_id = $(this).attr('id').substring(11);
var thisFormFull = '#' + thisForm;
$.ajax({
type: "POST",
url: "/songs/spam.php",
data: "command=mark_spam&cid=" + com_id,
complete: function(data){
messageList = 'contentspam-' + com_id;
$('span#' + messageList).html(data.responseText);
$(thisFormFull).hide();
$('span#' + messageList).fadeIn();
}
});
return false;
});
A: Works for me. I created a jsfiddle with your code, and clicking the link in IE 8 generates a request. I used Fiddler to inspect the HTTP request:
POST /songs/spam.php HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-US,en;q=0.7,es;q=0.3
Referer: http://fiddle.jshell.net/josh3736/Ghy5C/show/
Accept: */*
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Zune 4.0; .NET CLR 1.1.4322; .NET4.0C; InfoPath.3)
Host: fiddle.jshell.net
Content-Length: 23
Connection: Keep-Alive
Pragma: no-cache
command=mark_spam&cid=1
Even though the AJAX request 404s (there's no spam.php on jsfiddle's server), the link is hidden after the request completes. As an aside, you should make your callback function the success callback rather than the complete callback, so that your UI does not report that an operation succeeded when in fact there was an error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Taking input for fstream::seekp and fstream::put How would I go about taking input for seekp and put for use with hex? Something like this?
Cin>>hex>>mychar;
How about printing the correct value in hex?
Say at 0x16 the byte is FF or 255 unsigned 8bit(decimal?) when I do this
fstream mystream;
mystream.seekp(0x16);
long myvar;
myvar=mystream.tellp();
cout<<"Value at offset 0x16: "<<myvar;
It prints 22 im assuming since I opened the file in binary mode thats why its printing 22 as the value of FF in binary is like 2222222 etc.
Is there a correct data type for printing the value at a certain offset(I've tried long and char and int but it still yields 22.) or am I printing them wrong? I've searched on google but couldnt find any help in this regard however I did note that opening the file in binary is recommended for editing with hex.
A: There are a couple of problems with your code:
*
*ostream::seekp sets the "put" pointer, i.e. the location at which one writes data, not the position at which one reads data. Use istream::seekg to set the "get" pointer
*ostream::tellp doesn't perform any I/O. It merely reports the value of the 'put' pointer, it doesn't actually fetch the data stored there. You mean to use istream::get.
Your program is printing the decimal number 22, which is equal to the hexadecimal number 0x16. That is because seekp sets the put pointer to 0x16, and tellp merely reports the value of the put pointer -- 0x16!
Try this code:
fstream mystream;
mystream.seekg(0x16);
int myvar;
myvar=mystream.get();
cout<<"Value at offset 0x16: "<<myvar << "\n";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: asp.net wizard control I have a Wizard control with 5steps.
After the user selects his values from the Drop Downlist, TextBoxes, I have a submit_click event to insert all the selected values in the DB.
Here's what I have in the Submit_Click
try
{
int result = new objBLL.PostProfile
{
ProfileId = 1,
CasteId = Convert.ToInt32(casteDropDown.SelectedValue),
MMBId = iMMBID,
UserId = UserId,
FullName = Full_Name.Text,
Gender = genderDropDown.SelectedValue,
Age = Convert.ToInt32(Age.Text),
Height = HeightDropDown.SelectedValue,
Complexion = ComplexionDropDown.SelectedItem.ToString()
}.Save(Operation.Insert);
public class PostProfile
{
PostProfileDAL objProfileDAL = new PostProfileDAL();
public int ProfileId { get; set; }
public int CasteId { get; set; }
public int MMBId { get; set; }
public Guid UserId { get; set; }
public string FullName { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Height { get; set; }
public string Complexion { get; set; }
public int Save(Operation opr)
{
int result = 0;
SqlParameter[] parms = {
new SqlParameter("@Profile_Id", ProfileId),
new SqlParameter("@Caste_Id", CasteId),
new SqlParameter("@MMB_Id", MMBId),
new SqlParameter("@User_ID", UserId),
new SqlParameter("@Full_Name", FullName),
new SqlParameter("@Gender", Gender),
new SqlParameter("@Age", Age),
new SqlParameter("@Height", Height),
new SqlParameter("@Complexion", Complexion)
};
try
{
if (opr == Operation.Insert)
{
result = DALBASE.SetData("InsertProfileDetails", parms);
}
catch (Exception ex)
{
result = 1;
throw ex;
}
So this is where I am having trouble.
While sending all the data into the .cs file, it is able to retain all the textbox values, but none of the selected values in the Drop Downlists, listboxes are retained.
For Eg: For DropDownlist complexion, if I select a value "VeryFair" in the wizard control,
on sending it to the class file to the Save Operation, the value of the Complexion Drop Down is still "Please select a value"
Any help is appreciated
Thanks
Sun
A: Check for the ViewStateMode property of your Wizard.
It should be enabled instead of inherit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to create an Jsoup Selector with an AND operation? I want to find the following tag in a html.
<a href="http://www.google.com/AAA" class="link">AAA</a>
I know I can use a selector like a[href^=http://www.google.com/] or a[class=link].
But how can I combine this two conditions?
Or is there a better way to do this? Like regex? and how?
Thanks!
A: Just combine them in a single CSS selector.
Elements links = document.select("a[href^=http://www.google.com/][class=link]");
// ...
or
Elements links = document.select("a.link[href^=http://www.google.com/]");
// ...
Considering regex makes no sense with such a world class HTML parser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the effect of calling sleep(0) on a UNIX system? I see people doing this in some parts of heavily multi-threaded, multi-process application systems I work with. It seems to be done around debug lines:
std::cerr << "DEBUG: Reaching: " << __FUNCTION__ << " @ " << __LINE__ << std::endl;
sleep(0);
If I macro out sleep(0); (i.e. change it to ""), the debug output from the system seems to come in different order (less predictable), so I figure it makes the line come out sooner - but I thought std::cerr was unbuffered, and std::endl calls std::flush() anyway, so why would this be?
A: It perturbs the scheduler in a difficult-to-predict way.
Typically the result will be similar to a call to pthread_yield() - you give up your timeslice. The result of this is that, under heavy debug print load, you'll be less likely to be preempted in the middle of writing to cerr (ie, between those <<s), since you'll be at the start of a timeslice after the last debug print, and thus you're less likely to have multiple threads overwriting each other's output (ie, getting something like DEBUG: REACHING: foo() @ DEBUG: REACHING bar()17 @ 24).
That said, this method is unreliable - it's perturbing the scheduler, not asking for specific semantics. It's also slow - unconditionally entering the kernel to yield (and possibly bouncing control among multiple threads too frequently). And it's less likely to work properly on a multicore CPU.
It would be better to put a mutex over all debug output like this. That said, since this is debug code, it's not surprising that the author may have used a quick-and-dirty hack to get it working just well enough to debug whatever problem they were having.
A: Basically, it yields control back to the scheduler, and lets you be re-scheduled instantly. That said, it's basically a hack to try and fool the operating system into doing something.
And it's never a good idea to fool the operating system.
If the system is suitably underloaded, then going to sleep will mean the OS gets control and lets the I/O queue flush, so it would have that effect. Sometimes. Depending.
Exactly what it's doing depends on details of the implementation that, frankly, you can't depend upon.
A: On most platforms, sleep(0) causes the scheduler to treat the current thread more or less as if it had used up its timeslice. Typically this means that, if possible, another thread in the same process will be scheduled on that core if one is ready-to-run. As you noted, it tends to make scheduling slightly more predictable. To me, that seems counter-productive when debugging.
I agree with Nemo's comment that it's much the same as pthread_yield. It does have some legitimate uses, but it's sometimes used erroneously as a way to provide more fairness or reduce latency. Typically it just makes performance worse because a context switch blows out the caches.
I've looked at the other answers and I agree with the general sense of befuddlement. My bet is that there is no good reason for it other than that someone thought that more predictable scheduling was a good thing. (It's not. Flexibility is good. The more requirements you put on the scheduler, the more it has to sacrifice to meet those requirements. If you impose requirements that aren't actually required, you trade performance for nothing at all.)
A: You use this as a way of letting other processes run that may be waiting for some cpu time, but without forcing a particular delay if no other processes are waiting to run.
A: As others have mentioned, sleep(0) is a system call that causes the current thread to relinquish control of the CPU.
The only legitimate reason for using this that I can think of is when implementing one's own synchronization primitive such as a spin lock using assembler instructions such as LOCK (x86) and; LDREX and STREX (ARMv7). In such a case, if we encounter a lock we might as well relinquish control immediately in the hope that another thread will do its thing and unlock our lock. This is definitely spinning away until our time slice is up.
Having said that, you really need to know what you are doing when implementing your own synchronization primitive. Specifically, you may need to put in memory barriers to enforce ordering of reads and writes. You are probably much better off using the primitives provided on the platform.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Critique my Python Package Structure I'm in the process of finishing up a Python package I've been writing. However, before I release it I'd like to get some feedback on the overall structure of the package as well as the __init__.py file.
This should give an idea of what my __init__.py file looks like.
'''
A docsting describing the package.
'''
__author__ = myname
__copyright__ = mycopyright
__credits__ = listofcredits
__license__ = mylicense
__version__ = 0.0
__maintainer__ = me
__email__ = myemail
__status__ = indevelopment
# This contains a module with directories as strings (for file reference)
import mypath
# some modules
import this
import that
# some gui widget classes
from windowmodule import windowwidget
from widgetmodule import someguiwidget
from someothermodule import someotherguiwidget, andanotherguiwidget
def __demo__ () :
# a demo of the package
if __name__ == '__main__' :
__demo__()
This should give a decent idea of the overall package structure.
mypackage/
mypath.py
__init__.py
license.txt
readme.txt
modules/
this.py
that.py
windows/
windowmodule.py
widgets/
widgetmodule.py
images/
imagefiles.whatever
tools/
tools.py
A: You should use absolute imports instead of relative imports, e.g. import mypackage.mypath as mypath.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any good choice of Wifi-Transfer(OTA) kit for iOS?(Like cocoawebresource) I have tried cocoawebresource(which is based on cocoahttpserver). It's quite functional , but I wonder is there any other better choice?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# google login I'm maintaining some code that I want to add a chat feature to. I already have a client/server/database setup, but what I would like to do is use Google accounts for logins, instead of people having to create new accounts and such.
Could anyone point me in the right direction?
I've already downloaded this http://code.google.com/p/google-gdata/ Am I on the right track?
Just to clarify as well, this isn't an asp project, it's a desktop project.
A: After lots tinkering around, I was able to come up with this solution. It looks so easy, yet I wasn't able to find any proper documentation on it. I'm sure people will find this extremely helpful.
Just get the Google API from http://code.google.com/p/google-gdata/
and add Google.GData.Client.dll as a reference(it's under the redist folder)
using Google.GData.Client;
public bool Google_Login(string email,string password, string captcha,string captchatoken)
{
String AppName = "MyCompany-MyApp-1.0.0.0";
Service s = new Service("code", AppName); //Can use any service, I just happened to want to use GoogleCode
s.setUserCredentials(email, password);
if(captcha != null && captchatoken != null) //If we already tried to log in, but we needed to captcha
{
if(!String.IsNullOrWhiteSpace(captcha) || !String.IsNullOrWhiteSpace(captchatoken))
{
s.Credentials.CaptchaToken = captchatoken;
s.Credentials.CaptchaAnswer = captcha;
}
}
try
{
string ret = s.QueryClientLoginToken();
//If we end up here, then the credentials are correct.
}
catch(Google.GData.Client.CaptchaRequiredException ce)
{
//ce.Url is the full url of the Captcha image
//If you would rather handle the captcha from
//a webpage, you can make your user go here "https://www.google.com/accounts/DisplayUnlockCaptcha"
//TODO Some way to display the captcha image and get user feedback
//we'll just say you did that and returned a string named retCaptcha
return Google_Login(email,password, retCaptcha,ce.Token);
}
catch(Google.GData.Client.AuthenticationException re)
{
//re.Message is the specific message google sends back about the login attempt.
return false;
}
catch(WebException e)
{
//Haven't ended up here yet, but I'm sure it's possible.
return false;
}
//If we somehow end up here
return false;
}
This isn't the exact code I used, I just pulled the skeleton of it out and rewrote it in a more generic way.
A: For a desktop application, have a look at Google's documentation on OAuth 1.0 for Installed Applications. Your application will (obviously) need the capability of launching a browser so the user can authenticate with Google.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Delphi XE2 dbExpress MySQL connection No matter what I've tried, I couldn't make XE2 to connect to a MySQL with dbExpress. The problem has actually many faces. First, target MySQL is either 32- or 64-bits, which affects the libmysql.dll that comes with the MySQL installation, which seems to be misleading because XE2 IDE is a 32-bit application and it only accepts 32-bit DLLs. So I needed to use a 32-bit installation libmysql.dll, put it under Windows\System32 (or to the project's folder itself), and then set the Target compile platform to 32-bit in my project (so that it won't try to use 64-bit dbxmys.dll, just in case), still with no luck. All the combinations I tried resulted with this error: "DBX Error: Driver could not be properly initialized. Client library may be missing......."
Anyone who's able to make XE2 dbExpress connect to a MySQL server? I need your help. Thanks in advance.
Windows 7 64-bit (dev platform with XE2), MySQL 5.5.16 32-bit (installed on a remote XP 32-bit) / MySQL 5.1.54 64-bit (installed on a remote XP x64) (tried with both, by using their libmysql.dlls)
A: the answer to your question is simple, install your mysql and copy libmysql.dll from your mysql bin as shown eg.(C:\Program Files\MySQL\MySQL Server 5.1\bin) and then go to the xe2 directory and open the bin too eg (C:\Program Files\Embarcadero\RAD Studio\9.0\bin) and paste it there over running the already libmysql.dll in it.
A: As it seems you have x64 Windows, then you should put x32 libmysql.dll not into Windows\System32, but into Windows\SysWOW64. Or you can put x32 libmysql.dll into XE2\Bin folder.
If you will build x64 application, then x64 libmysql.dll you should put into Windows\System32 or into your EXE folder.
A: The answer for this question is found at WiltonSoftware.com.
What I did was:
*
*I downloaded the a zip file containing libmysql.dll version 5.1.59
*I created the folder C:\Program Files (x86)\MySQL\MySQL Connector 5.1.59\lib
*I copied the DLL to the just created folder
*I added that folder in the Windows Path environment variable
It worked fine to me!
A: A bit late, but I hope it helps:
*
*Install the latest Updates for Delphi XE2
*Install SQL Server 2008 native client
*Uninstall everything old like SQL Server Express 2005 (if installed)
I was not able to pinpoint the exact reason why this works. Could be the usage of sqlncli.dll instead of oledb.dll.
A: Hrmm, apparently the question I asked was a bug in XE2 and supposedly fixed with Update 1 http://docwiki.embarcadero.com/RADStudio/en/Release_Notes_for_XE2#Please_Install_XE2_Update_1
I'll try and see if it really fixed the issue.
A: The only version works with XE2 was 5.1.54 i had the same problem and being solved by this
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Radial gradient mixin in LESS isn't working? If you are familiar with less, could you help me with this problem?
I am creating a radial gradient mixin for just a quick test case.
However both are not working?
.radialGradient(@posX:center @posY:center, @shape:circle @size:closest-side, @from:white, @to:black){
background-image: -webkit-radial-gradient(@arguments);
}
or
.radialGradient(@posX:center @posY:center, @shape:circle @size:closest-side, @from:white, @to:black){
background-image: -webkit-radial-gradient(@posX @posY, @shape @size, @from, @to);
}
Reasons?
Thanks!
Ah! I figured out.
I have forgotten to add in "," in the parameters.
.radialGradient(@posX:center, @posY:center, @shape:circle, @size:closest-side, @from:white, @to:black){
background-image: -webkit-radial-gradient(@posX @posY, @shape @size, @from, @to);
}
This is the right way.
A: Ah, I've discovered the solution. You forgot to add a comma after your first parameter ;P
.radialGradient(@posX:center, @posY:center, @shape:circle, @size:closest-side, @from:white, @to:black){
background-image: -webkit-radial-gradient(@posX @posY, @shape @size, @from, @to);
}
A: They changed LESS PHP to match LESS JS in regards to parameter syntax. Values used to be separated by ; now they are separated by ,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: I am having a problem i to connect different users when user logs in string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;"
+ "data source=" + Page.Server.MapPath("MyConnectionString");
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString);
// System.Data.OleDb.OleDbCommand cmd = conn.CreateCommand();
SqlDataSource ads = new SqlDataSource();
ads.SelectParameters.Add("UserName", this.TextBox1.Text);
ads.SelectParameters.Add("Password", this.TextBox2.Text);
ads.SelectCommand = "SELECT * FROM [Users] WHERE [UserName]= @UserName AND [Password] = @Password";
//retrieve required data
//conn.Open();
DataView dv = (DataView)ads.Select(DataSourceSelectArguments.Empty);
//diplay error message if record is not found
if (dv.Count == 0)
{
this.Label1.ForeColor = System.Drawing.Color.Red;
this.Label1.Text = "Login failed. The username or password you have entered isn't valid";
return;
}
//create Session variables
this.Session["Username"] = dv[0].Row["Username"].ToString();
this.Session["UserType"] = dv[0].Row["UserType"].ToString();
//Redirect to respective page based on user
if (this.Session["UserType"].ToString().Equals("patient"))
Response.Redirect("Patient.aspx");
else if (this.Session["UserType"].ToString().Equals("doctors"))
Response.Redirect("Doctor.aspx");
else if (this.Session["UserType"].ToString().Equals("nurse"))
Response.Redirect("Nurse.aspx");
A: You are initializing connection and connection string but not assigning to source to use it with the command.
A: Try,
SqlDataSource ads = new SqlDataSource();
ads.ConnectionString=connectionString;
I dislike the SqlDatasource personally. I suggest the use of provider classes.
Demo:
/***** Please check/verify the path of database file *****/
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;"
+ "data source=" + Page.Server.MapPath("MyConnectionString");
/***********************************************************/
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection(connectionString);
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand();
cmd.Connection=conn;
cmd.CommandText="SELECT * FROM [Users] WHERE [UserName]= @UserName AND [Password] = @Password";
cmd.Parameters.Add("@UserName",System.Data.OleDb.OleDbType.VarChar,40).Value=TextBox1.Text;
cmd.Parameters.Add("@Password",System.Data.OleDb.OleDbType.VarChar,40).Value=TextBox2.Text;
System.Data.OleDb.OleDbDataReader dr;
conn.Open();
dr=cmd.ExecuteReader();
bool Found=false;
string username="";
string uesrtype="";
if(dr.Read())
{
Found=true;
username=dr.getString("username");
usertype=dr.getString("usertype");
}
conn.Close();
if (!Found)
{
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "Login failed. The username or password you have entered isn't valid";
return;
}
Session["Username"] =username;
Session["UserType"] = usertype;
if(usertype.equals("patient"))
{
}
else
if(usertype.equals("doctor"))
{
}
else
if(usertype.equals("nurse"))
{
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RQRcode error for Ruby on Rails I'm getting the following error from Ruby on Rails in my EquipmentController#show
uninitialized constant EquipmentController::RQRCode
controller
def show
@equipment = Equipment.find(params[:id])
@equipment_statuses = EquipmentStatus.all
@equipment_bookings = EquipmentBooking.find_all_by_equipment_id(params[:id])
@qr = RQRCode::QRCode.new( 'my string to generate', :size => 4, :level => :h )
respond_to do |format|
format.html # show.html.erb
format.json { render json: @equipment }
end
end
view -- show
<div class="qr">
<table>
<% @qr.modules.each_index do |x| %>
<tr>
<% @qr.modules.each_index do |y| %>
<% if @qr.dark?(x,y) %>
<td class="black"/>
<% else %>
<td class="white"/>
<% end %>
<% end %>
</tr>
<% end %>
</table>
</div>
gemfile
gem 'rqrcode-rails3'
I'm running Rails 3.1.0
Any ideas what the problem might be?
A: I think your code needs
require 'rqrcode'
in your environment.rb or your controller
A: I think this is one of those 'restart your server' moments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# synchronous TCP client socket unexplained missing data I'm using TCP over an unreliable mobile data connection, which may drop packets due to interference or whatever may be going wrong with the signal strength.
What complicates matters is that I'm using Modbus TCP and the mobile router on the other end converts this into Modbus RTU (Serial) in order to communicate with a serial based device (slave).
Furthermore, whenever a read request is sent to the serial device its internal pointer will be incremented to the next chunk of data as soon as the response has been sent. The serial device will have no idea whether the mobile connection is still OK; if the response does not make it all the way back to the server it will already have incremented its internal pointer anyway.
In other words take the following scenario:
*
*Server sends modbus read request over TCP.
*Router receives request and passes it to serial device.
*Serial device responds to router.
*Serial device increments data pointer.
*Router fails to send TCP packet back to server.
*Server sends read request again.
*Serial device responds to router.
*Serial device increments data pointer.
*Router send data back to server successfully.
In the above scenario you will see that the problem in step 5 causes a whole data chunk to be missed, because the serial device has no idea that the previous read operation actually failed. It has already moved on to the next chunk! Normally what I would do is detect this problem and use the "request previous data chunk" operation to re-request the previously missed data chunk from the serial device.
Here is my problem: I'm not getting any exceptions or errors from the TCP code even though I have everything enclosed in a SystemException try-catch block and I'm checking the return value.
I looked through my log file carefully and noticed that the time between a request and a response is about 1 second, however at the time of the suspected missed data chunk, the time gap was between 2 and 3 seconds. This would suggest that a send occured, but no data was received so it tried again. But of course when it tried again, the serial device would have already incremented its data pointer to the next set of data.
For some reason the serial device received the read request, however the data never made it back to the server.
I'm not an expert on TCP/IP, so does anyone out there know what could have happened? Is it possible for TCP to resend packets "under the hood" without causing exceptions and without me knowing?
In my code I'm simply doing something like this:
_log.Debug(string.Format("[{0}]: Sending sync response ({1}).",
this._IP.ToString(), CoreUtils.PayloadToString(write_data)));
tcpSynCl.Send(write_data, 0, write_data.Length, SocketFlags.None);
int result = tcpSynCl.Receive(tcpSynClBuffer, 0,
tcpSynClBuffer.Length, SocketFlags.None);
byte function = tcpSynClBuffer[7];
byte[] data;
if (result == 0) throw SystemException("No data received");
// ... process log buffer ...
_log.Debug(string.Format("[{0}]: Got sync response ({1}).",
this._IP.ToString(), CoreUtils.PayloadToString(data)));
return data;
There were no exceptions thrown, which would suggest that something happened between Send() and Receive() under the hood. The time between the two debug log entries was twice as long than all the others. Possible or not possible?
A: First of all: Receiving 0 bytes do not mean that you haven't received anything. It means that the connection has been closed.
Second: It's likely that you'll receive two messages at the same time due to Nagle algorithm. You need to go through the received bytes and see how messages there are in there. TCP is not message based but stream based.
A: The whole point of TCP is to make the stream transparent to the application. Lost packets are handled by TCP and not the application. If TCP does not get an ACK for a given packet, it will attempt to resend the packet. It will eventually stop sending any other packets and continue to resend that lost packet until it receives and ACK or the connection times out.
Similar on the receiving side. If a packet is lost, the TCP stack will not send any data to the application until it receives the missing packet. TCP also guarantees packet order. A lost packet will cause the receiver to stop until it either gets the missing packet or times out.
The receiver will accept and buffer some of the packets that came after the dropped packet and "play them back" once the missing packet is received.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trouble Deserializing JSON into Object Stack Overflow:
I am using JSON.NET and have done so successfully before, however I am now running into a nasty bit of JSON that I cannot seem to deserialize. Clearly the problem lays in how the class is constructed, and so I kindly ask for someone to help me plan a class that JSON.NET can successfully deserialize into.
Here is the structure of the JSON string:
[
{
"name":"",
"cost":"",
"cmc":"",
"loyalty":"",
"supertype":"",
"type":"",
"subtype":"",
"power":"",
"toughness":"",
"hand":"",
"life":"",
"rule":"",
"multi":"",
"set":
[ // Note: there could be an infinite number of sets
{
"setcode":"",
"rarity":"",
"number":"",
"artist":"",
"flavor":""
},
{ "setcode":"",
"rarity":"",
"number":"",
"artist":"",
"flavor":""
},
]
}
]
Thank you very much, Stack Overflow
A: You'll want to have a class with properties for all those names. When it comes to the array, it's really an array of objects so you need to create another class with same named properties. Something like:
public class MainObject
{
public string name { get;set; }
// rest of the names as properties
public List<SetObject> @set { get;set; }
}
public class SetObject
{
public string setcode { get;set; }
// rest of your sets names as properties
}
Also, from your JSON it looks like it's an array already so you'll want to deserialize it as an array:
var objects = JsonConvert.DeserializeObject<MainObject[]>(/* your json here */);
That will give you an array of your deserialized MainObject just like your JSON is an array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ASP.Net - Handling session data in a load balanced environment? How does ASP.Net deal with session data in a load balanced environment?
Let's say a user makes multiple requests while navigating through a couple of pages?
Do all requests go to the same server in the load balancer?
What can I do if they don't all point to the same server? how do I deal with my session data?
A: You need to ensure that your NLB has the ability to enable "Sticky" sessions.
If this isn't an option, then you need to look at using the ASP.Net Session Modes to configure either a Session Server, or some backing store like SQL Server.
A: In general most load balancers try to have persistent connections but for your purposes you can't guarantee it. You're best off either using something like an SQL backend to maintain state or create a separate class to manage your session data. In either case you can then rebuild the session data if it happens to be null when you expect it to be otherwise. I tend to use the getters to check for null and rebuild when necessary. In practice I haven't done any metrics to see how often it is rebuilt but I'd guess not very often. Better to be safe than sorry, as they say.
A: Load balancers usually can be configured with something the infrastructure guys call sticky session or sticky bit. On this type of environment, once a request has been assigned to a server; it stays with that server throughout the session.
When Load Balancers are not configured in such a way, ASP.NET offers several session state providers. One very popular is the SQL Server State Provider, which allows session information to be stored in a database. In order for this to work, all objects placed in the Session object must be Serializable so that they can be stored in a table.
As I said, there are several more alternatives; for example, some people prefer to use a different approach such as memcached or similar products.
A: You can use NLB from Windows or other products such as BIG-IP F5,HA Proxy, there tons of options.
Use Out-of-Proc (State Server) and make sure your machinekey settings are the same on all your servers. Also make sure you are doing IO on a shared disk drive such as a NAS.
Here is a link with some more tips:
Load Balancing and ASP.NET
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Python3 print statement doesn't work as expected I am using Python 3.2.2
>>> s = 'hhh'
>>> print s
SyntaxError: invalid syntax
>>> print(s)
hhh
>>> print 2*2
SyntaxError: invalid syntax
>>> print(2*2)
4
Why do I have to use print("...") to print something? If I dno't it complains with 'SyntaxError'.
A: As of python 3.0, print is a function. See:
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Ruby on Rails: How do detect if access by JSON? I got a GET URL that calls a controller method getInfo. It can be called by mydomain.com/getInfo.json?params=BLAHBLAH or mydomain.com/getInfo?params=BLAHBLAH
In the controller, is there a way to detect how the user called it?
A: As easy as do:
request.path_parameters[:format] == 'json'
A: If you need to check if it was an Ajax request you can check for a header[X-Requested-With] using request.xhr?
Example code snippet
if request.xhr?
# Do the ajax stuff
else
# Do normal stuff
end
A: Yes. Within the controller you can call the request.format method to determine the format requested by the user.
If you need more than just the format, you can look at request.url for the full URL. More details about the request object can be found here.
A: Within your controller's specific method, you can respond to different formats - for example:
respond_to do |format|
format.html
format.json { render :json => @user }
end
You can respond to various formats (xml, js, json, etc) - you can get more information about respond_to and how to use it in your controller here:
http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to
A: A list of ways to check for json
request.format == 'json'
request.format == :json
request.format.json?
request.path.match('json')
request.url.match('json')
respond_to do |format|
format.json { render json: [] }
end
You can also check if request was an ajax request
request.xhr?
A: Here is an actual somewhat contrived working example, that answers the question of how to detect if the call is JSON / XML API call vs an "HTML" call. (Accepted answer doesn't answer that question, just tells you how to respond to various formats)
# We can use this in a before_filter
skip_before_action :verify_authenticity_token, if: :api_request?
# Or in the action
def show
@user = if api_request?
User.where(api_token: params[:token]).first
else
User.find(params[:id])
end
respond_to do |format|
format.html
format.json { render :json => @user }
end
end
private
def api_request?
request.format.json? || request.format.xml?
end
Using a respond_to sets different types of responses, but it doesn't tell your application how the call was made unless you add some extra code that does it (see below for a crude example, just to illustrate the point.)
I wouldn't recommend this, interrogating request is much safer, and 10x times more useful, as the approach below is only useful much later in the request lifecycle ( right before the response is sent back to the client). If you have any logic in your before filters this wouldn't work at all.
# Have no way of using it in a before_filter
# In your controller
def show
# I want to know if the call was JSON API - right here
# This approach wouldn't help at all.
@user = User.find(params[:id])
respond_to do |format|
format.html { @api_request = false}
format.json { @api_request = true; render :json => @user }
end
end
def api_request?
@api_request
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: c# update current time,days,date protected void Page_Load(object sender, EventArgs e)
{
todayDate.Text=DateTime.Now.toString();
}
Output
10:28AM 9/28/2011
the current time is never update, the result is static, how do i set a interval in c# in order to update current time?
updated information
this is my ajax updated timer code
<ajax:ToolkitScriptManager ID="scriptmanager1" runat="server">
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
and i called it by using
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString() + " "+DateTime.Today.DayOfWeek.ToString();
}
output is exactly what i want, but the effect not exactly what i want, cause when user clicked on some button,the label will blink, this like telling the user the page is reloading, so i wondering is that any idea can deliver update time from server? or just refresh partial pages?
A: the reason it doesn't update is because the ASP.Net is server code that is generating HTML which is presented in the browser.
The browser sends a request to your server, the server executes your page logic on one of it's threads, your code generates output (which in your case, setting the today.Data.Text is creating html in the output buffer), the response is sent to the client and the browser shows that html. You're done. The request was fulfilled.
You either need to keep refreshing that page (bad - old full refresh server generated page model) or have javascript code that runs in the browser. Checkout Ajax patterns for that.
Hope that gives insight as to why :)
A: Use Ajax Extension controls (UpdatePanel, Timer).
A: As has been suggested you need to use a client-side script to update the values in realtime, if this is your intention. Searching for 'JavaScript clock' or 'Ajax clock' should give you some cut-n-paste code, or look into some Ajax examples in their toolkit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C#: Globally alias a generic class name? in some project we are using Generics, and we get a lot of lines like this:
Line<SomeTClass,SomeCClass> myLine =
(Line<SomeTClass,SomeCClass>)LineFactory.CreateLine(...)
We can declare local alias, with using X = Line<SomeTClass,SomeCClass>.
Then we can write, X myLine = (X)LineFactory.CreateLine(...).
We have a lot a combination of <T,C> but we often use the same. Is it possible de declare the using globally, so that we won't have to declare the alias in each file?
A: No, you cannot create a global alias.
A: No such thing as a global alias. What you can do is use type inference to simplify your declarations:
var myLine = (Line<SomeTClass, SomeCClass>)LineFactory.CreateLine(...);
and if that's not specific enough for the inference system, you can make the CreateLine() method generic to enforce it:
var myLine = LineFactory.CreateLine<Line<SomeTClass, SomeCClass>>(...);
and given the name of the LineFactory type, maybe even simplify it some more:
var myLine = LineFactory.CreateLine<SomeTClass, SomeCClass>(...);
This last option feels "right" to me in some way I can't fully articulate. Just in case you need a little help, the method declaration would look like something this:
public static class LineFactory
{
public static Line<T,C> CreateLine<T,C>(...) { ... }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to get the average of the last X values? If I have a table with two columns - value and time_stamp - how can I use SQL to get the average of the last X values?
One statement or several, it doesn't matter.
Maybe something like SELECT value FROM table ORDER BY time_stamp DESC LIMIT x ? Then in my program, I could get each value, total them and average them? That's my best guess so far as I am a SQL beginner.
I am aware that SQL can total / average, but I am unsure how to combine that with a request to apply it to the latest X values...
Note to anyone else seeking to do this: in addition to the accepted answer for the last X values, I also found by googling that it is easy to do for a time period, such as a minute or hour, by using something like SELECT AVG(somefield) FROM sometable WHERE datefield BETWEEN '2003-08-10' AND '2003-08-26'.
A: You use the AVG() aggregate on the result of a subselect which does the initial LIMIT. Just be sure to substitute the correct LIMIT value for n on the inner query.
SELECT AVG(a.value) AS the_average
FROM (SELECT value FROM tbl ORDER BY time_stamp DESC LIMIT n) a;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: org.xml.sax.SAXException: Parser configuration problem: I am stuck with this error
org.xml.sax.SAXException: Parser configuration problem: namespace reporting is not enabled
at net.sf.saxon.event.ReceivingContentHandler.getNameCode(ReceivingContentHandler.java:383)
at net.sf.saxon.event.ReceivingContentHandler.startElement(ReceivingContentHandler.java:289)
while running the following code
xmlHandler.startElement("D:\XmlFiles\XmlFromRhapsody.xml", "", qName, atts);
xmlHandler is --> TransformerHandler xmlHandler;
I am not sure of enabling namespace.
A: You can fix this by supplying the localname when calling the startElement method. This means that you to make the same calls to the ContentHandler that a namespace-aware XML parser would make.
So, you have ..
xmlHandler.startElement("D:\XmlFiles\XmlFromRhapsody.xml", "", qName, atts);
You need to add the local name as the 2nd parameter instead of leaving it blank.
Also, If you don't want to make these changes you can use saxon-8.9.0.4.jar which should work without any errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: delete a row in android sqlite table i want to delete a row in the database table
i using a listview and after longclick the listitem you will get alert dialog to show edit and delete method
when i click the edit method the emulator goes fine, but when i click the delete method, there comes the force close notification,.im new to android programming,
can you explain what is the problem with my code
this is my code
for database helper:
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
class PuraHelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
public final String TABLE_NAME = "pura";
public final String TABLE_ROW_ID = "_id";
public final String NAMA_PURA = "nama_pura";
public final String KABUPATEN = "kabupaten";
public final String JALAN = "jalan";
public final String LONGITUDE = "longitude";
public final String LATITUDE = "latitude";
public final String KETERANGAN = "keterangan";
private static final String DATABASE_NAME="PPB.db";
private static final int SCHEMA_VERSION=1;
public PuraHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CreateTablePura="create table"+TABLE_ROW_ID+"INTEGER PRIMARY KEY AUTOINCREMENT,"+ NAMA_PURA + "TEXT," + KABUPATEN + "TEXT,"+ JALAN + "TEXT," +LONGITUDE + "TEXT," + LATITUDE + "TEXT," + KETERANGAN + "TEXT";
db.execSQL(CreateTablePura);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// no-op, since will not be called until 2nd schema
// version exists
}
public Cursor getAll() {
String SelectAll = "SELECT _id, nama_pura, kabupaten, jalan, longitude, latitude, keterangan FROM pura ORDER BY nama_pura";
return(getReadableDatabase()
.rawQuery(SelectAll,
null));
}
public Cursor getById(String id) {
String SelectById = "SELECT _id, nama_pura, kabupaten, jalan, longitude, latitude, keterangan FROM pura WHERE _ID=?";
String[] args={id};
return(getReadableDatabase()
.rawQuery(SelectById, args));
}
public void insert(String nama_pura, String kabupaten, String jalan, String longitude, String latitude, String keterangan) {
ContentValues cv=new ContentValues();
cv.put("nama_pura", nama_pura);
cv.put("kabupaten", kabupaten);
cv.put("jalan", jalan);
cv.put("longitude", longitude);
cv.put("latitude", latitude);
cv.put("keterangan", keterangan);
getWritableDatabase().insert("pura", "nama", cv);
}
public void update(String id, String nama_pura, String kabupaten, String jalan, String longitude, String latitude, String keterangan) {
ContentValues cv=new ContentValues();
String[] args={id};
cv.put("nama_pura", nama_pura);
cv.put("kabupaten", kabupaten);
cv.put("jalan", jalan);
cv.put("longitude", longitude);
cv.put("latitude", latitude);
cv.put("keterangan", keterangan);
getWritableDatabase().update("pura", cv, "_ID=?", args);
}
public void deleteRow(long rowId)
{
// ask the database manager to delete the row of given id
//db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowId, null);
db.delete(TABLE_NAME, TABLE_ROW_ID + "="+rowId,null);
}
public String getId(Cursor c) {
return(c.getString(0));
}
public String getNama(Cursor c) {
return(c.getString(1));
}
public String getKab(Cursor c) {
return(c.getString(2));
}
public String getJalan(Cursor c) {
return(c.getString(3));
}
public String getLong(Cursor c) {
return(c.getString(4));
}
public String getLat(Cursor c) {
return(c.getString(5));
}
public String getKet(Cursor c) {
return(c.getString(6));
}
for my java class:
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;
public class db_list extends ListActivity {
protected static final String ID_EXTRA = "com.jigler.ppb._ID";
PuraHelper helper=null;
Cursor model=null;
PuraAdapter adapter=null;
EditText etNama, etKabupaten,etJalan, etLong, etLat, etKeterangan;
Button bSave, bCancel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_list);
helper=new PuraHelper(this);
etNama = (EditText)findViewById(R.id.etNama);
etKabupaten = (EditText)findViewById(R.id.etKabupaten);
etJalan = (EditText)findViewById(R.id.etJalan);
etLong = (EditText)findViewById(R.id.etLong);
etLat = (EditText)findViewById(R.id.etLat);
etKeterangan = (EditText)findViewById(R.id.etKeterangan);
model=helper.getAll();
startManagingCursor(model);
adapter=new PuraAdapter(model);
setListAdapter(adapter);
ListView lv = getListView();
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> list, View view,
int position, long id) {
// TODO Auto-generated method stub
alert_editlist(id);
return true;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
helper.close();
}
@Override
public void onListItemClick(ListView list, View view, int position, long id) {
Intent i=new Intent(db_list.this, db_new_man.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
private void alert_editlist(final long id) {
// TODO Auto-generated method stub
final CharSequence[] items = {"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("What do you want to do?");
builder.setIcon(R.drawable.ic_setting_36);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item]=="Edit") {
Intent i=new Intent(db_list.this, db_new_man.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
else if(items[item]=="Delete"){
//this is where my app force close
helper.deleteRow(id);
model.requery();
}
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
return(super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.add) {
//startActivity(new Intent(db_list.this, db_new.class));
alert_db_new();
return(true);
}
return(super.onOptionsItemSelected(item));
}
private void alert_db_new() {
// TODO Auto-generated method stub
final CharSequence[] items = {"Auto", "Manual"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Use Your Configuration Setting By");
builder.setIcon(R.drawable.ic_setting_36);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item]=="Auto") {
startActivity(new Intent(db_list.this, db_new_auto.class));
}
else if(items[item]=="Manual"){
startActivity(new Intent(db_list.this, db_new_man.class));
}
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
helper.insert
(
etNama.getText().toString(),
etKabupaten.getText().toString(),
etJalan.getText().toString(),
etLong.getText().toString(),
etLat.getText().toString(),
etKeterangan.getText().toString()
);
model.requery();
}
};
*/
class PuraAdapter extends CursorAdapter {
PuraAdapter(Cursor c) {
super(db_list.this, c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c) {
// TODO Auto-generated method stub
PuraHolder holder=(PuraHolder)row.getTag();
holder.populateFrom(c, helper);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
PuraHolder holder=new PuraHolder(row);
row.setTag(holder);
return(row);
}
}
static class PuraHolder {
private TextView nama=null;
private TextView alamat=null;
private ImageView icon=null;
PuraHolder(View row) {
nama=(TextView)row.findViewById(R.id.nama_pura);
alamat=(TextView)row.findViewById(R.id.jalan);
icon=(ImageView)row.findViewById(R.id.icon_pura);
}
void populateFrom(Cursor c, PuraHelper helper) {
nama.setText(helper.getNama(c));
alamat.setText(helper.getJalan(c));
icon.setImageResource(R.id.icon_pura);
}
}
}
thank you for the attention
A: I think you didn't instantiate "db" in your code.
using
getWritableDatabase().delete(TABLE_NAME, TABLE_ROW_ID + "="+rowId,null)
instead of
db.delete(TABLE_NAME, TABLE_ROW_ID + "="+rowId,null)
may help.
A: Set this as the ListView LongClickListener. You also might want to try making a DBAdapter helper class like the one here http://www.devx.com/wireless/Article/40842/1954
private OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final long ITEM = id;
// Ask the user if they want to delete
AlertDialog.Builder confirmation = new AlertDialog.Builder(view.getContext());
confirmation.setIcon(android.R.drawable.ic_dialog_alert);
confirmation.setButton(POSITIVE_BUTTON, "Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
db.open();
db.deleteItem(ITEM);
updateList();
} catch (Exception ex) { }
finally {
db.close();
}
});
confirmation.setButton(NEGATIVE_BUTTON, "Do nothing", null);
confirmation.setButton(NEURTRAL_BUTTON, "Edit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(view.getContext(), EditActivity.class);
intent.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(intent);
}
});
confirmation.show();
return false;
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hibernate Mapping same Column twice How can fix this thing
Repeated column in mapping for entity: com.abc.domain.PersonConnect
column: PERSON_ID (should be mapped with insert="false"
update="false")
this is snippet from my hbm file
<class name="com.abc.domain.PersonConnect" table="PERSON_CONNECT">
<composite-id>
<key-many-to-one name="Parent" class="com.abc.domain.Person" column="PARENT_PERSON_ID"/>
<key-many-to-one name="Child" class="com.abc.domain.Person" column="CHILD_PERSON_ID"/>
</composite-id>
<many-to-one class="com.abc.domain.Person" fetch="select" name="parent" lazy="false" >
<column length="20" name="PERSON_ID" not-null="true"/>
</many-to-one>
<many-to-one class="com.abc.domain.Person" fetch="select" name="child" lazy="false" >
<column length="20" name="PERSON_ID" not-null="true"/>
</many-to-one>
</class>
and the table goes like this
Person_Connect
*
*PK - PARENT_PERSON_ID
*PK - CHILD_PERSON_ID
Person
*
*PK - PERSON_ID
*FNAME
*LNAME
A: Your mapping is wrong, this is the correct mapping. On the many-to-one side the column name is the column in the same table which is a foreign referring the primary key of Person.
<class name="com.abc.domain.PersonConnect" table="PERSON_CONNECT">
<composite-id>
<key-many-to-one name="Parent" class="com.abc.domain.Person" column="PARENT_PERSON_ID"/>
<key-many-to-one name="Child" class="com.abc.domain.Person" column=" CHILD_PERSON_ID"/>
</composite-id>
</class>
A: Well, for one, it seems unlikely that both "Parent" and "Child" should be mapped to the same column. That's probably a problem. Otherwise, do what the error says, and add insert="false" update="false" to one of the column mappings. A column can only "belong" to a single property. Otherwise you can get into unresolvable situations where one property says the value should be x and the other says it should be y.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Hadoop MAC OS installation woes So I'm trying to install hadoop on MAC OS X Leopard following the steps in this note: Running Hadoop on a OS X Single Node Cluster.
I reached Step 4: Formatting and running Hadoop, where I entered the following:
hadoop-*/bin/hadoop namenode -format
This produced the following unpleasant output:
Macbook009:~ Hadoop$ hadoop-*/bin/hadoop namenode -format
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:676)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:317)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375)
Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:676)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:317)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:280)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:375)
I did some googling, and learned that JAVA_HOME may be set incorrectly. I created a .bash_profile file like this:
export JAVA_HOME=/system/Library/Frameworks/JavaVM.framework/Versions/1.6/Home
export HADOOP_HOME=~/Users/Hadoop/hadoop-0.20.203.0
export PATH=$HADOOP_HOME/bin:$PATH
No go. Same freaking error.
What am I doing wrong?
A: I suspect that the JVM that's actually running Hadoop is not the expected one, but an older one (Java 5). Verify this by running ps (or any Mac equivalent) and examining the command line.
Try to set JAVA_HOME in $HADOOP_HOME/conf/hadoop-env.sh to the same path as you did in your .bash_profile.
A: It may still be a problem with setting your JAVA_HOME as it could be different from examples on the web. Use this command in your terminal to find your JAVA_HOME directory /usr/libexec/java_home
A: This is caused when the jre you are running is older than the jre that compiled the class files. For example running 1.6 compiled java with the 1.5 jre. If the class was compiled just for 1.6 it will not work with 1.5.
Do a
java -version
and see which jre you have. Most likely you have an old one and need to upgrade it.
A: Try typing jps and seeing how many nodes are actually running .
There should be 6 of them . You shouldn't have a problem hopefully .
A: Following steps worked seamlessly for me:
http://ragrawal.wordpress.com/2012/04/28/installing-hadoop-on-mac-osx-lion
For wordcount example, you need to copy your file to hdfs, for which you can find the command here: (this is the only step where I struggled after following the above page).
http://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/#running-a-mapreduce-job
A: However for newer versions of OS X like 10.9 setting PATH described above is not working.
Found a way where you can add default PATH environment for MAC in file /etc/paths.
Open this file using Terminal in SUDO mode.
$ sudo nano /etc/paths (enter password when prompted).
Append the path in below format.
/users/hadoop/hadoop-1.2.1/bin
/users/hadoop/hadoop-1.2.1/sbin
save the file and restart the Machine. Next time no need to type whole command to run Hadoop script command from Script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problems aligning ImageButton within LinearLayout? This is my code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:background="@drawable/game_background"
android:weightSum="100"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ScrollView android:id="@+id/ScrollView01" android:layout_weight="70"
android:layout_width="fill_parent" android:layout_height="228dp">
<LinearLayout android:layout_width="wrap_content"
android:layout_height="30px" android:id="@+id/LinearLayout02"
android:orientation="vertical">
<TextView android:layout_height="wrap_content" android:text="Version 0.0.0.1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content" android:textColor="#000000"></TextView>
<TextView
android:text="Thanks for trying out the very first version of this program!\n\n"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000"></TextView>
<ImageButton android:id="@+id/imageButton1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:src="@drawable/prefs_exit" android:onClick="exit_button"
android:background="#00000000"></ImageButton>
</LinearLayout>
</ScrollView>
<LinearLayout android:layout_width="fill_parent" android:layout_weight="30"
android:layout_height="fill_parent" android:id="@+id/LinearLayout02"
android:orientation="vertical">
<ImageButton android:id="@+id/imageButton1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:src="@drawable/prefs_exit" android:onClick="exit_button"
android:background="#00000000"></ImageButton>
</LinearLayout>
</LinearLayout>
The problem is the image button in the second linearLayout comes on the right side of the screen instead of at the bottom :(
How do I fix this?
And finally, I want to put a graphic (a logo) on the total bottom, right corner side.
Note, I am a newbie and still very much learning this... just got lost via the examples.
Thanks!
Ryan
A: try adding android:orientation="vertical" to the first LinearLayout
UPDATE
as for logo to the right, try android:gravity="right" in your second LinearLayout
A: Here is your correct layout, just check it and just replace the background images with your images. Have fun developing applications.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/LinearLayout01"
android:background="#ffffff"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="100">
<LinearLayout
android:layout_height="fill_parent"
android:id="@+id/linearLayout1"
android:orientation="vertical"
android:layout_width="wrap_content"
android:gravity="center">
<ScrollView
android:id="@+id/ScrollView01"
android:layout_height="228dp"
android:layout_width="fill_parent">
<LinearLayout
android:layout_width="wrap_content"
android:id="@+id/LinearLayout02"
android:layout_height="30px"
android:orientation="vertical">
<TextView
android:textColor="#000000"
android:text="Version 0.0.0.1"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"></TextView>
<TextView
android:textColor="#000000"
android:text="Thanks for trying out the very first version of this program!\n\n"
android:layout_height="wrap_content"
android:layout_width="wrap_content"></TextView>
<ImageButton
android:src="@drawable/icon"
android:layout_height="wrap_content"
android:background="#00000000"
android:onClick="exit_button"
android:id="@+id/imageButton1"
android:layout_width="wrap_content"></ImageButton>
<LinearLayout
android:layout_height="fill_parent"
android:id="@+id/LinearLayout02"
android:layout_weight="30"
android:orientation="vertical"
android:layout_width="fill_parent">
<ImageButton
android:src="@drawable/icon"
android:layout_height="wrap_content"
android:background="#00000000"
android:onClick="exit_button"
android:id="@+id/imageButton1"
android:layout_width="wrap_content"></ImageButton>
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SSRS Report Parameters that are not in select I created a SSRS report and I wanted to pass date (begin date and end date). I am not populating the field on the report (i.e its not in select statement). In this case how to assign report parameters to query in the 'Report Parameter Properties' window.
SELECT *
FROM EMPLOYEE
WHERE DOB between @BEGINDATE and @ENDDATE
A: You don't assign parameters to a query in the "Report Parameter Properties" dialog. Here you set up the properties of the parameter itself: it will live in the report. (Here you will want to specify a date.)
Then, in the dataset for your query, you can assign parameters to your query. The easiest way to do this is just use an identically named parameter in the query by prefixing '@'. That is the parameter named BeginDate can be used as @BeginDate. The BIDS will take care of mapping the query parameter to the report parameter. You can do this manually or adjust BIDS mappings on the Parameters section of the Dataset Properties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: INPUT type=image, how to get coordinate value? An <input> with type="image" and name="something" will send the variables something_x and something_y to the server, along with the coordinates where the image was clicked.
If the form is being handled by JavaScript, for instance in an AJAX setup, how do I go about getting the coordinates where the element was clicked?
So far my only idea is to set:
imginput.onclick = function(e) {
e = e || window.event;
var coords = getMouseCoords(e), elempos = getElementCoords(this); // defined elsewhere
this.value = (coords.x - elempos.x)+","+(coords.y - elempos.y);
}
The problem is, I'd have to make sure the onclick event is assigned to the correct input elements, even if they are loaded or otherwise created after the document has loaded (a problem I've already had to face when dealing with custome tooltips). Is there maybe a better solution?
A: You have to select those elements after they are created to add the event listener. jQuery has a function called .live() that selects every applicable element now and in the future.
A: Resolved in the same way as custom tooltips: an "updateLiveContent" function that re-runs the tooltip initialisation and the input images.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need help forming JQuery to clone element and insert within parent div There are multiple identical div#DropDown as in the below html with same id:
<div class="DropDown">
<div class ="ListAndLink">
<select id="mydropdown" name="mydropdown">
<option selected="selected" value="18">Blah</option>
<option value="0">Do not include</option>
</select> <a class="clone"> + Add</a>
</div>
</div>
The following jquery (Using 1.5.1) works to adegree, but what it does is clone the entire <div class="DropDown"> and inserts another one after it, the "+Add" link on the clones does not work either. And pressing +Add on the original will double/2x whatever is already cloned, including the original.
$(".clone").click(function () {
var clone = $(this).parent().clone();
$(this).parent().append(clone);
OnSuccess(mydata); // <- calculates total for all selected items
});
What I want to get is this: (Without "+Add" and in place of it "-Del") retaining "selectedness" is not important. Pressing the "-Del" should delete <select> element it is near (but action script when pressing on the cloned elements does not fire it seems, like they are not part of DOM?):
<div class="DropDown">
<div class ="ListAndLink">
<select id="mydropdown" name="mydropdown">
<option selected="selected" value="18">Blah</option>
<option value="0">Do not include</option>
</select> <a class="clone"> + Add</a>
</div>
<div class ="ListAndLink">
<select id="mydropdown" name="mydropdown">
<option selected="selected" value="18">Blah</option>
<option value="0">Do not include</option>
</select> <a class="Delete"> - Del</a>
</div>
</div>
Also I don't know how to put it in words exactly, but is there a way to permanently, at least for the said browser window to retain the html that Jquery generates, because it all disappears if I press the back-button. I am not sure if this happens because the html generated by Jquery is not retained in DOM, because the server side does not override the page contents when using "back" as I understand it's not how browsers work and HTML is retained in memory of browser.
Most importantly, I need the cloned elements to be picked up by the existing javascript,
say I have an $('select').change(function () { OnSuccess(mydata); }); script that works with all original dropdown lists , right now when I choose different option from the cloned drop down lists it does not fire!
Thanks..
A: http://jsfiddle.net/mqeN5/
This is what you need:
HTML
<select class='keep'>
<option value='Keep this' selected>Keep This</option>
<option value='Delete this'>Delete This</option>
</select>
<span class='add'>+Add</span>
<select class='delete'>
</select>
<span class='rem'>-Rem</span>
Javascript:
$('.add').click(function(){
$('.keep option:selected').clone().appendTo('.delete').end().end().remove();
});
$('.rem').click(function(){
$('.delete option:selected').clone().appendTo('.keep').end().end().remove();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Secure HTTP communication I'm really new to Android programming, so this may seem silly to do this...but
I want to communicate to a PHP server (I assume using JSON is best). So...would I use a HTTP connection or what? IS there anyway to make this 'secure', like if I was sending site user credentials over the wire?
A: Secure - against what?
Secure against eavesdropping in the middle - just use HTTPS instead of HTTP.
Secure against devices being stolen - introduce user authentication on the site.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Public\Shared assembly without GAC I have two assemblies and this assembly was used by many applications. I dont have to have this in GAC.
Is there a way to share the assembly publicly accessible by many applications without the use of GAC
My customer dont want to dump these dlls in GAC since these assemblies used by three applications So i dont want to hold in GAC
A: There are some ways to share assemblies among applications. Although the most recommended is through the GAC, you have also these other options:
Probing
You can specify a subdirectory under the application base directory to search for assemblies. I think this is not valid for you because this is not valid for different apps.
CodeBase
You can specify a Uri where the shared assemblies are located. In your case, those assemblies must be strong named so that they can be located in a shared common directory.
Also take into account that the CodeBase tag only can be used in the Machine configuration or publisher policy files.
<?xml version="1.0" encoding="utf?8" ?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas?microsoft?com:asm.v1">
<dependentAssembly>
<codeBase version="1.0.0.0"
href= "file:///c:\Shared Assemblies\MySharedAssembly.dll"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
AssemblyResolver
This is by far the least complicated mechanism to locate shared assemblies. Basically, the ApplicationDomain raises an event when it fails in the resolution of an assembly. This event can be caught by your application to manually return desired assembly from any location.
class Example
{
public static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
// Uses MySharedAssembly
Foo();
...
}
private static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
// I guess requested assemblyName is located in this file.
var file = @"c:\Shared Assemblies\MySharedAssembly.dll";
try
{
return Assembly.LoadFile(file);
}
catch (Exception)
{
...
}
return null;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I use SQL Server Profiler to view the TSQL ran in a CLR trigger? How can I user SQL Server Profiler to view the TSQL ran in a CLR trigger?
I have a CLR trigger in the a MS SQL Server DB, that checks the Inserts, Updates, Deletes on a table and then conditionally does inserts to another table. Is there a setting to get those T-SQL inserts that are made from within the CLR Trigger to show the SQL Server Profiler trace results?
A: In the event selection tab, after you click "Show all events" there is a CLR section. There is only one event in it "Assembly Load". This event is happens when there is a request to load the CLR assembly. Any SQL that comes from the assembly should register as a standard TSQL event, so I would go to the TSQL section and pick every "SQL:" event. Also check out the "Errors and Warnings" section. I am assuming there is something wrong in the setup of the assembly or a .NET exception is happening before the SQL is called.
If your CLR trigger is just a conditional insert into another table I would not use an assembly. This is especially true if the table is selected, updated, or deleted from frequently. Assemblies run in the servers application memory space, not in the dedicated sql server memory space so all of the sudden you have a sql server that is using more application memory than normal. I've crashed my fair share of sql servers this way.
It also introduces more complexity in source control, builds, and has some security issues that you should understand. All in all, I'd say using the SQL Server CLR should be a last ditch effort.
A: It depends on how you are executing the code. Are you using a SqlCommand? If so, are you setting the CommandType to be StoredProcedure or Text?
If you are specifying a CommandType of Text or not specifying a CommandType in the first place (since Text is the default), then the statements are dynamic SQL and you need to use the SQL:StmtStarting and SQL:StmtCompleted events in the TSQL group. This is probably the case for your Trigger.
If you are specifying a CommandType of StoredProcedure, then try the SP:Starting and SP:Completed events in the Stored Procedures group.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Difference between prop in obj and obj.hasOwnProperty(prop) and obj[prop]? Should I use one over the other? Is using them all together better? Thanks.
A: *
*prop in obj checks whether obj has a property named prop at all, even if it's just inherited from a prototype.
*obj.hasOwnProperty(prop) checks whether obj itself holds a property named prop; it ignores properties inherited from prototypes.
*obj[prop] gets the value of the prop property.
Use whichever one is appropriate for what you're trying to accomplish
Note: In all three cases, prop must be a string.
A: Just to give an example for this:
var animal = {"legs": 4};
var dog = {"barks" : true};
dog.__proto__ = animal; // JS inheritance (dog inherits from animal)
now this means that:
console.log("legs" in dog); // TRUE - due to JS inheritance and since 'in' key looks into inherited prototypes
console.log(dog.hasOwnProperty("legs")); // FALSE
console.log(dog.hasOwnProperty("barks")); //TRUE
prints
true
false
true
Note one more thing: If dog had "legs" property of lets say 5 (hhmm spooky i know), so the 'in' operator ("legs" in dog) will refer to the "legs" property which is declared in the dog object and not the inherited "legs" which comes from animal object. e.g.:
var animal = {"legs": 4};
var dog1 = {"barks": true};
var dog2 = {"barks": true, "legs": 5};
dog1.__proto__ = animal;
dog2.__proto__ = animal;
console.log(dog1.legs);
console.log(dog2.legs);
console.log("legs" in dog2) // 'in' refer to the un-inherited "legs" of dog2
prints
4
5
true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to test a scenario that requires javascript to complete? A project I'm working on fetches data from a 3rd party service and caches it locally along with specific info for my app.
My environment:
*
*I provide a search mechanism against the service's search API.
*When a user browses to the item page for the first time, the my server fetches the info from the service and stores it
*On subsequent requests the browser just requests the information from my server
.. however.. I want info from the 3rd party service to stay up to date.
My plan (feedback welcome!)
*
*On a subsequent request after page load, some JS will ping the 3rd party service to check for updates
*If the item has been updated, push an update to my copy server side
How to test this?
When I write a controller spec I don't think the page's javascript is executed (to fetch the since-updated item from the service)
I had quite a bit of trouble trying to describe this so a diagram might help.
Technology I'm using: Rails/RSpec/Factory Girl/JQuery
A: Let's think out of the box a little to solve this.
Can you hit the 3rd Party Service from the Back End when the page is requested? Then you remove the dependance on JavaScript.
There are a few other methods that are better than this, like putting the "update item information" action into a queue, and then processing it in the background on the Back End. This would allow for the 3rd Party Service to not slow your site down.
A: It looks like there are a few ways to test this assuming my current solution.
Thoughtbot makes a library called capybara-webkit that will spin up webkit in the background and render/run your tests through it. Selenium is another.
github link
blog post
back on this project after a bit of a hiatus.. using capybara and :js => true seems to work - some tricky timing issues, but otherwise good to go
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to login a website using python module "mechanize" with a cookies.txt exported by the chrome extension "cookies.txt export"? I have looked through similar questions in stackoverflow yet seemingly no answers measures up. Now I have a cookies.txt in hands which is exported by a chrome extension named "cookies.txt". I can execute a command "wget --load-cookies cookies.txt www.example.com" to download the webpage with the account authenticated.
However, I met a problem when I tried to use this file in my python script as follows,
import mechanize
cookie = 'cookies.txt'
cookiejar = mechanize.FileCookieJar(cookies.txt)
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_cookiejar(cookiejar)
url = 'www.example.com'
response = br.open(url)
s = response.read()
f = open('test.html','w')
f.write(s)
f.close()
I only got a webpage without my account logged in after executing this script. And If I change the first several lines of code into this
import mechanize
cookie = 'cookies.txt'
cookiejar = mechanize.MozillaCookieJar()
cookiejar.load(cookie)
I got an error message "mechanize._clientcookie.LoadError: cookies.txt does not look like a Netscape format cookies file" executing the script.
I have no idea how I can get the authentication done with this cookies.txt given that this file works in wget command.
A: I was getting the same error until I added this to the top of my cookie file, and now works.
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
A: According to the mechanize source code, the load method of class MozillaCookieJar will search for the regexp "#( Netscape)? HTTP Cookie File" first, so you can insert this line into the top of the exported cookie.txt:
# Netscape HTTP Cookie File
A: Use the cookielib module to handle the cookies.
http://docs.python.org/library/cookielib.html
Specifically, you need to read up on how to use FileCookieJar.load()
That should get you on track.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Animate (slide in) new panel to replace current panel's contents? I'm trying to change the contents of an Ext.List. I'm trying to change the content to a new panel, although I don't need more list elements.
This seems to replace the contents, but how do I animate the change?
onItemDisclosure: function(record, btn, index) {
console.log('Disclose more info for ' + record.get('name'));
var panel1 = Ext.getCmp('panel-1');
panel1.remove(Ext.getCmp('panel-1'));
panel1.add(Ext.getCmp('panel-2'));
panel1.doLayout();
}
A: The best is to have the panel-1 and panel-2 as items in a different panel and then switch between them. Example:
var detailPanel = new Ext.Panel({
fullscreen: true,
id:'detailPanel',
scroll:'vertical',
tpl:'<h1>{text}</h1>'
});
var list = new Ext.List({
id :'theList',
itemTpl : '{firstName} {lastName}',
store: store1,
width: '100%',
scroll:false
});
var panel = new Ext.Panel({
fullscreen: true,
id:'thePanel',
layout: 'card',
cardSwitchAnimation:'slide',
scroll:'vertical',
items:[list, detailPanel]
});
Then you can update the detailPanel like this Ext.getCmp('detailPanel').update(record.data); and switch to it. Ext.getCmp('thePanel').setActiveItem(1,{type:'slide',direction:'left'});
The second argument of the setActiveItem is the animation config. object. http://dev.sencha.com/deploy/touch/docs/?class=Ext.Panel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Capistrano deploy/assets on Rails 3.1 fails I added the this line load 'deploy/assets' to my Capfile to deploy assets with Rails 3.1.
Capistrano gets to this line
* executing "cd /home/deploy/armonia/stage/releases/20110928021521 && bundle exec rake RAILS_ENV=stage RAILS_GROUPS=assets assets:precompile"
then fails with
Could not find multi_json-1.0.3 in any of the sources which is weird because the gem is found when I run bundle show multi_json on my deployment server.
What causes this?
A: Fixed this by updating to bundler to 1.0.18, seems to be related to this https://github.com/capistrano/capistrano/issues/81
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Dictionary Iteration Python I am newbie in Python.
Dictionary has multiple values.
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
If you iterate over 'dc' you find there are three occurrences of '3'. First occurrence is in 1:['2','3'].
I would like to iterate over dict so that
if first occurrence of '3' occurs:
dosomething()
else occurrence of '3' afterwards:#i.e. 2nd time, 3rd time....
dosomethingelse()
How can I do this in Python
Thank you.
A: Assuming the values in the dict are the lists:
foundThree = False
for key, val in dc.items():
if '3' in val and not foundThree:
foundThree = True
# doSomething()
elif '3' in val:
# doSomethingElse()
else:
# doAnotherThing()
Edit (update for your comments about finding the first '3' in the list which is the value of a dict item) - this should work:
for key, val in dc.items():
foundThree = False
for n in val:
if n == '3' and not foundThree:
foundThree = True
# doSomething()
elif n == '3':
# doSomethingElse()
else:
# doAnotherThing()
A: Most of what you're asking for is pretty straightforward, the only part I can see you having trouble with is determining if the number 3 occurs after the first element.
You can do this with:
list[1:]
For instance:
>>> 3 in [1,2,4,5][1:]
False
>>> 3 in [3,1,2,4][1:]
False
>>> 3 in [1,2,3,4][1:]
True
Here's something that should work:
dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
def dosomething(): print 'something'
def dosomethingelse(): print 'something else'
for key,value in dc.items():
if value[0] == '3':
dosomething()
elif '3' in value[1:]:
dosomethingelse()
A: dict_ = {1:['2', '3'], 2:['3'], 3:['3', '4']}
def dosomething():
print 'doing something'
def dosomethingelse():
print 'doing something else'
three_handler = dosomething
for v in dict_.values():
for three in [x for x in v if x == '3']:
three_handler()
three_handler = dosomethingelse
Output:
doing something
doing something else
doing something else
A: Here's an alternative that doesn't use an if statement to check if the 3 is the first occurrence.
d = {1:['2', '3'], 2:['3'], 3:['3', '4']}
def doSomething():
print('ds')
def doSomethingElse():
print('dse')
for key,value in d.iteritems():
do = doSomething
for item in value:
if item == '3':
do()
do = doSomethingElse
A: You can also keep a count of the times the element has been seen. Use a dict for this, and increment with each sighting:
#!/usr/bin/python
dc = {3:['3', '4'], 1:['2', '3'], 2:['3']}
de={}
def do_something(i,k):
print "first time for '%s' with key '%s'" % (i,k)
def do_somethingelse(i,j,k):
print "element '%s' seen %i times. Now with key '%s'" % (i,j,k)
for k in sorted(dc):
for i in dc[k]:
if i not in de:
de[i]=1
do_something(i,k)
else:
de[i]+=1
do_somethingelse(i,de[i],k)
As others have said, dictionaries do not have the same order necessarily as the insertion or code listing. You can just sort the keys (with to sorted(dc)) to distinguish 'first' vs subsequent if this is the same as sort order. This method is easily extended to 'do_somthing' based on how many times the item has been seen.
Output:
first time for '2' with key '1'
first time for '3' with key '1'
element '3' seen 2 times. Now with key '2'
element '3' seen 3 times. Now with key '3'
first time for '4' with key '3'
Alternatively:
r=[]
for k in sorted(dc):
print dc[k]
if '3' in dc[k]:
r.append("'3' number {} with key: {}".format(len(r)+1,k))
produces:
["'3' number 1 with key: 1", "'3' number 2 with key: 2", "'3' number 3 with key: 3"]
The list r will have the 3 strings in the order that the keys of dc are sorted in, then just iterate over the sequence r.
And if you are just looking for the 'first' 3 then the rest, you can use a list comprehension:
>>> l=[i for sub in [dc[k] for k in sorted(dc)] for i in sub if i == '3']
>>> l
['3', '3', '3']
>>> l[0]
'3'
>>> l[1:] #all the rest...
A: The code snippet below will give you an idea on how to do it.
This will work in single thread execution environment.
For more information start at python docs and Dive Into Python
firstInstance = False
for k in mydict.keys():
obj = mydict.get(k)
for i in range(len(obj)):
value = obj[i]
if value == 3 and firstInstance:
doSomething()
firstInstance = True
else:
doSomethingElse()
A: Assuming the 'first' is as sorted by the dictionary's keys, this works:
>>> dc = {1:['2', '3'], 2:['3'], 3:['3', '4']}
>>> [dc[k] for k in sorted(dc) if '3' in dc[k]][0]
['2', '3']
>>> [dc[k] for k in sorted(dc) if '3' in dc[k]][1:]
[['3'], ['3', '4']]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I make the Eclipse content assist case-sensitive? Does anyone know of an easy way to configure the Eclipse content assist to respond to the case of the first letter in a fragment? When I start a token with a lowercase letter, I'd prefer not to have suggestions for classes, since I am always referring to a member or variable. It would also be nice for a method name fragment to auto-complete when selection of any suggestion would result in the same text (e.g., multiple methods having the same name with different parameters, and no other suggestions offered).
The preferences for content assist don't mention either of these options, and I'm hoping to avoid writing (and maintaining) a plugin just for small conveniences. Thanks for your help.
Byron
A: Unfortunately this is not possible today. There are a few open bugs in this area, e.g. https://bugs.eclipse.org/bugs/show_bug.cgi?id=25305, you can contribute a patch :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: XML declaration not playing nice with PHP I'm using PHP to output custom XML based upon values stored in a MySQL database. I have the following at the start of the condition:
echo '<?xml version="1.0" encoding="UTF-8"?>';
(I've also tried this variation:
echo "<?xml version='1.0' encoding='UTF-8'?>";
to no avail.)
However, this is always outputted (in every browser and even when viewed as a downloaded file from wget) as:
<?xml version=1.0 encoding=UTF-8 ?>
Somewhere along the line, the single quotes around the version number and encoding got dropped. Where did I go wrong and what can I do to fix this? I'm getting errors from my parser and I believe it's because this declaration is not following the XML standard of having either single or double quotes around these values.
A: I think this is because the content type of your document is already set to text/html (by default by php).
The solution to this is to set this as a header rather than echo it.
eg :
header ("Content-Type:text/xml");
to set the charset :
header('Content-Type: text/xml; charset=utf-8');
And make sure that you set this BEFORE you output (echo) anything else.
Hope that helps :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Add a dynamic supervisor to ejabberd Is it possible to start a supervisor module in ejabberd which I can add a gen_fsm module to, per connection?
Specifically, I want to create a supervisor which I start when the server starts (or when connections come in). And I have a couple of gen_servers which I want to start, but the part I'm looking for some guidance on is how to dynamically add a gen_fsm module to my supervisor when I see this user's presence become available?
A: You might want to have a look to the Simple one for on supervisor, which:
is a simplified one_for_one supervisor, where all child processes are
dynamically added instances of the same process
...
When started, the supervisor will not start any child processes. Instead, all child
processes are added dynamically by calling:
supervisor:start_child(Sup, List)
...
Basically, you use this kind of supervisors when:
*
*All the children are of the same type
*You want to add children dynamically
Which appears to be your case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: grails on ec2 - bitnami tomcat 7 stack vs 'vanilla' Ubuntu instance Just started prepping AWS ec2 account for small grails app deploy and would like to know your thoughts on deploying to bitnami instance with tomcat7 vs going through the process of installing java, tomcat and doing configuration by hand.
Any pros and cons in relation to one or the other? I'm planning to use h2 in embedded mode (at least for now) so I'm not worried about MySql instance at this point.
I'm trying to keep the whole process as simple as possible and keep the overhead to a minimum.
Thanks in advance.
A: I currently use the bitnami stack for some of my grails apps on ec2 I like it but I'm used to how bitnami has placed everything, if you are more comfortable with vanilla ubuntu use that.
If your main goal is to do simple deployments you should consider looking into some of the PaaS offerings, Elastic Beanstalk is build on top of EC2 and should make things very easy to deploy, but it may have its own issues with storing data from H2 I haven't looked into that.
A few other PaaS to look at:
*
*OpenShift
*CloudFoundry
*Heroku [Seems early for using Grails there]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drag and Drop to folder behavior I have been searching around and learning about android widget programming. I am wondering about interaction in android widget. Is it possible for me to create a home screen widget that allow users to drag and drop other application icons to my widget? (behave like folder) If so, could you provide me some useful resources or examples of how to do it.
Thanks in advance.
Edited: I have found a widget called Semi Folder is similar to what I am looking for but this widget still not allow users to drag and drop to itself. It allows users to select and store applications via activity. Therefore, I still look for the solution of drag and drop to my widget.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why can't I "git clone" from my server with a key that works from my local machine? This is the content of /home/ubuntu/.ssh
drwx------ 2 ubuntu ubuntu 4096 2011-09-28 02:32 .
drwxr-xr-x 5 ubuntu ubuntu 4096 2011-09-28 02:08 ..
-rw------- 1 ubuntu ubuntu 396 2011-09-27 20:53 authorized_keys
-rw------- 1 ubuntu ubuntu 115 2011-09-27 21:10 config
-rw------- 1 ubuntu ubuntu 1670 2011-09-27 21:10 id_rsa
-rw------- 1 ubuntu ubuntu 397 2011-09-27 21:10 id_rsa.pub
-rw-r--r-- 1 ubuntu ubuntu 407 2011-09-28 02:07 known_hosts
id_rsa.pub is already a key added to my github account because if I try to add it, it tells me it already exists. It's also the key that allows me to git clone from my local machine. But when I try to git clone something from the server:
$ git clone git@github.com:redCashion/ruby-mysql.git
Cloning into ruby-mysql...
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
A: For diagnostic, try ssh -T git@github.com, it should give something like:
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
If that fails, you do not have your keys setup right or it is using some other keys. Try:
ssh -vT git@github.com
to see what private key it is trying. Make sure it is at /home/ubuntu/.ssh like you expect it to be.
A: You can try ssh'ing directly to github, and it will give you some diagnostic info. On top of that, use ssh -vvv ... to get very verbose output about what's happening. You may find that it's not using the key you think it is. If that's the case, check the contents of ~/.ssh/config.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS - heightForRowAtIndexPath does not fire during scrolling I am writing a simple iOS app using Xcode4, which uses a table view to display a list of stories (fetched from a URL). I'm displaying the story titles as UILabels, and as a subview of the table cell.
I am over-riding heightForRowAtIndexPath to calculate the correct height for the cells according to the length of each story title. I'm adding the label to the cell in cellForRowAtIndexPath. When I run the app in the simulator, everything is rendered well. However: when I scroll down and scroll up, the labels get messed up. They get truncated and over-run. I debugged a little, and found that the heightForRowAtIndexPath method is not fired during scrolling, so the cell heights are not re-calculated, and therefore the label text overflows, and gets rendered ugly. Here is the relevant code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[cell autorelease];
}
/* NOTE: code to load trimmedTitle dynamically is snipped */
NSString* trimmedTitle;
UIFont *cellFont = [UIFont fontWithName:@"Georgia" size:14.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [trimmedTitle sizeWithFont:cellFont constrainedToSize:constraintSize
lineBreakMode:UILineBreakModeWordWrap];
UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, 230, labelSize.height)];
tempLabel.lineBreakMode = UILineBreakModeWordWrap;
tempLabel.text = trimmedTitle;
tempLabel.numberOfLines = 0;
[cell.contentView addSubview:tempLabel];
[tempLabel release];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString* cellText; // code to load cellText dynamically is snipped off
UIFont *cellFont = [UIFont fontWithName:@"Georgia" size:14.0];
CGSize constraintSize = CGSizeMake(230.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
A: In situations like these I typically pre-calculate the heights of all of my rows, store them in an array, and then just returns those heights in heightForRowAtIndexPath. This way the tableview knows the height of each cell and cells be conform to that height even after reuse. I don't know of a way to force a calculation of the cell height beyond looking for when a cell will be viewable and reloading it, which seems too costly.
Update: some example code:
I have a method called - (void)calculateHeights which does the same calculation you had in heightForRowAtIndexPath, but stores the result in my mutable array heights_ ivar:
- (void)calculateHeights {
[heights_ removeAllObjects]
for (Widget *myWidget in modelWidgetArray) {
NSString* cellText; // code to load cellText dynamically is snipped off
UIFont *cellFont = [UIFont fontWithName:@"Georgia" size:14.0];
CGSize constraintSize = CGSizeMake(230.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
[heights_ addObject:[NSNumber numberWithFloat:labelSize.height + 20.0f]];
}
}
And then in heightForRowAtIndexPath, given a 1-section table view:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [heights_ objectAtIndex:[indexPath row]];
}
If your table view has more than one section you'll need to do some math to convert to the one-dimensional heights_ array and back again. Also, any time you -reloadData you'll need to -calculateHeights as well.
A: The -tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath method is invoked before the scroll view is composed.
The purpose of calling this method before calling -tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath and not fired during the scrolling is that the table view (Which is inherited from UIScrollView) need to know the whole height of the contentView. Once the table view knows all the height, it cached the height before you call -reloadData
Your problem means you need to clear the content in the cell's -prepareForReuse and call -setNeedLayout to layout all the new contents.
A: you can use tag for your label to avoid messed up to each other
UILabel *label= (UILabel*)[cell viewWithTag:2];
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MySQL + PHP: select multiple rows on a join, then update those rows/insert new ones I want to do the following:
*
*Select multiple rows on an INNER JOIN between two tables.
*Using the primary keys of the returned rows, either:
*
*Update those rows, or
*Insert rows into a different table with the returned primary key as a foreign key.
*In PHP, echo the results of step #1 out, ideally with results of #2 included (to be consumed by a client).
I've written the join, but not much else. I tried using a user-defined variable to store the primary keys from step #1 to use in step #2, but as I understand it user-defined variables are single-valued, and my SELECT can return multiple rows. Is there a way to do this in a single MySQL transaction? If not, is there a way to do this with some modicum of efficiency?
Update: Here are the schemas of the tables I'm concerned with (names changed, 'natch):
CREATE TABLE IF NOT EXISTS `widgets` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`author` varchar(75) COLLATE utf8_unicode_ci NOT NULL,
`text` varchar(500) COLLATE utf8_unicode_ci NOT NULL,
`created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated` timestamp
NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `downloads` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`widget_id` int(11) unsigned NOT NULL,
`lat` float NOT NULL,
`lon` float NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);
I'm currently doing a join to get all widgets paired with their downloads. Assuming $author and $batchSize are php vars:
SELECT w.id, w.author, w.text, w.created, d.lat, d.lon, d.date
FROM widgets AS w
INNER JOIN downloads AS d
ON w.id = d.widget_id
WHERE w.author NOT LIKE '$author'
ORDER BY w.updated ASC
LIMIT $batchSize;
Ideally my query would get a bunch of widgets, update their updated field OR insert a new download referencing that widget (I'd love to see answers for both approaches, haven't decided on one yet), and then allow the joined widgets and downloads to be echoed. Bonus points if the new inserted download or updated widgets are included in the echo.
A: Since you asked if you can do this in a single Mysql transaction I'll mention cursors. Cursors will allow you to do a select and loop through each row and do the insert or anything else you want all within the db. So you could create a stored procedure that does all the logic behind the scenes that you can call via php.
Based on your update I wanted to mention that you can have the stored procedure return the new recordset or an I'd, anything you want. For more info on creating stored procedures that return a recordset with php you can check out this post: http://www.joeyrivera.com/2009/using-mysql-stored-procedure-inout-and-recordset-w-php/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PayPal complete date format PayPal send back the payment_date field in the following format 19:19:09 Sep 27, 2011
I am using php to calculate days remaining from payment_date, but my code is based on getting the format in 2011-09-27 12:19:00.
How do I change?
This is my code (which works perfectly if date in my correct format):
<?php
$today = time();
$cdate = strtotime('2011-09-27');//strtotime($row_details['payment_date']);// testing
$dateDiff = $today - $cdate;
$fullDays = floor($dateDiff/(60*60*24));
$dayscalculate = 30 - $fullDays; // Set number of days
echo $dayscalculate.(($dayscalculate == 1) ? " day" : " days");
?>
Thank you
A: There should be no issue here. strtotime() will accept PayPal's format as:
strtotime("19:19:09 Sep 27, 2011")
Just be sure you have the correct timezone set in your php.ini, or at runtime with date_default_timezone_set()
A: <?php
$end = date('Y-m-d H:i:s', strtotime("03:49:26 27 May 2013 PDT"));
echo $end;
?>
Result : 2013-05-27 11:49:26
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: The page loading animation for hiding whole page load process ends long before It must fade out
Possible Duplicate:
Hiding page loading
I'm using loading animation for hiding whole page load process. but it ends long before It must fade out. it ends while loading but must fade out after full page load
Here is the js
$(document).ready(function(){
$('#loading').fadeOut(600, function()
{
$("#wrap").fadeIn(1000);
$("#footer").fadeIn(1000);
});
});
HTML markup
<html>
<body>
<div id="loading"><img src="core/design/img/load/load.gif" /></div>
<div id="wrap"></div>
<div id="footer"></div>
</body>
</html>
I'm trying to hide whole page loading process with following solution.
CSS Rules:
#loading {
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
background-image:url("img/load/tr.png");
z-index:100;
}
#loading img {position: absolute; margin-left:-110px; margin-top:-9px; left:50%; top:50%}
You can see it in action
A: You need to use $(window).load(function(){ }); instead of $(document).ready(function(){ });
More info: $(document).ready vs. $(window).load
For users with javascript disabled:
$(document).ready(function(){
$('body').append('<div id="loading"><img src="core/design/img/load/load.gif" /></div>');
});
$(window).load(function(){
$('#loading').fadeOut(600, function(){
$("#wrap").fadeIn(1000);
$("#footer").fadeIn(1000);
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Syntax error while running tests from terminal I have a rails application on RubyMine. While running tests on terminal(Mac OS X 10.7), I am getting the following error:
Ruby -Itest test/unit/user_test.rb
Creating sqlite :memory: database
-- create_table("logins", {:force=>true})
-> 0.0014s
-- create_table("posts", {:force=>true})
-> 0.0094s
-- create_table("users", {:force=>true})
-> 0.0011s
-- initialize_schema_migrations_table()
-> 0.0009s
-- assume_migrated_upto_version(20110927003058, ["db/migrate"])
-> 0.0007s
Loaded suite test/unit/user_test
Started
E
1) Error:
test_the_truth(UserTest):
SyntaxError: (erb):23: syntax error, unexpected keyword_end, expecting $end
; end ; _erbout.concat "\n"
^
Finished in 0.024246 seconds.
1 tests, 0 assertions, 0 failures, 1 errors, 0 pendings, 0 omissions, 0 notifications
0% passed
41.24 tests/s, 0.00 assertions/s
I am guessing these lines are creating the issue:
<td><%= link_to 'Destroy', user, confirm: 'Are you sure?', method: :delete %></td>
Is that so? If Yes, why?
Edited:
<h1>Listing users</h1>
<table>
<tr>
<th>Unity id</th>
<th>Name</th>
<th>Password</th>
<th>Role</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @users.each do |user| %>
<tr>
<td><%= user.Unity_ID %></td>
<td><%= user.Name %></td>
<td><%= user.Password %></td>
<td><%= user.Role %></td>
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to "Destroy", user, :confirm => "Are you sure?", :method => :delete %> </td> --- Line 23
</tr>
<% end %>
</table>
<br />
<%= link_to 'New User', new_user_path %>
Thanks!
A: Usually when I get that error (warning: anecdotal), it's because I've missed the do keyword after an iterator, or a haml function that takes a block in a view.
I don't see anything wrong with the link_to line - can you post the source of the file that contains the error (and point out which line is line 23)?
A: It was a configuration issue. Created a new project, copied my files. Now its working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone disabling caching for stringWithContentsOfURL I have an iPhone app which needs to load some data from a URL. I have the following line of code:
NSString *versionControlContents = [NSString stringWithContentsOfURL:[NSURL URLWithString:versionControlURL] encoding:encoding error:NULL];
The issue that I'm having is that if the contents of the URL have changed since the first time the URL was loaded, the changes aren't being reflected. Every subsequent time that line of code runs, versionControlContents ends up with the same content as the first time it ran.
I'm assuming this is because the iPhone has some sort of caching mechanism so that it doesn't actually load the data from the URL every subsequent time. How can I disable this temporarily?
Thanks!
A: You might try + requestWithURL:cachePolicy:timeoutInterval:
Then you can set your cacheing policy as you wish.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .NET Regex Equivalent of Python Regex's (?P=previousmatchname) In Python's implementation of regular expressions you can do the following:
<(?P<foo>.*)>(.*)</(?P=foo)>
and basically it will look for <this>right here</this> but not <this>right </here>. Basically it allows you to use the previously captured named match later in your regex. Is there a way to do this with .NET's Regex?
A: You can use sharp brackets or single quotes and use \k to reference them:
<(?<foo>.*)>(.*)</(\k<foo>)>
or
<(?'foo'.*)>(.*)</(\k'foo')>
See this page for more info and scroll down to the "Named Capture with .NETβs System.Text.RegularExpressions" section.
A: try this:
<(?<foo>.*)>(.*)</\<foo>>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I disable selection in specific UIPickerView item? I can find a post that teach to use delegate method to check if the row valid and then scroll to the right one if not.
But that's not I want. Can I disable the specific row after the pickerView initialized?
Like "Gray-out" the row and can't stop indicator on it.
Thank you, experts.
A: There are two parts to doing this.
*
*Use -[<UIPickerViewDelegate> pickerView:viewForRow:forComponent:reusingView:] to return a custom view for each row, such as a UILabel. For the row you want to show up as disabled, you'll need to configure the view to reflect that disabledness.
*In -[<UIPickerViewDelegate> pickerView:didSelectRow:inComponent:], you'll need to detect when the disabled is selected, and then use -[UIPickerView selectRow:inComponent:animated:] to "rollback" to a "valid" row.
A: You could also just leave a blank in the implementation, e.g.:
- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
if(row==0){
//Code
}
if(row==1){
//BLANK
}
if(row==2){
//Code
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Adding active class to wordpress 3+ menu I'm having problems with adding active class to wordpress menu. (If is home highlight home, if blog highlight blog and so on... )
I'm using superfish menu.
I have this in my functions.php
function me_register_menu() {
register_nav_menu('main-menu', __('Main Menu'));
}
add_action( 'init', 'me_register_menu' );
And in my header, where my menu is
<?php
if ( has_nav_menu ( 'main-menu' ) ) {
wp_nav_menu( array ( 'theme_location' => 'main-menu' , 'container_class' => 'grid_7', 'container_id' => 'menu' , 'menu_class' => 'menu sf-menu') );
}
?>
I'd like to add .active class to my active menu. Any ideas how?
A: You can do it with css. It's hard to say without seeing your page, but this should work:
/* Highlight using list element */
.menu-item a:active{
background:#999 !important;
color:#fff;
}
/* Highlight using link element */
.menu-item:active {
text-decoration:underline;
background:#666 !important;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to redefine the .^ operator in MATLAB? How can I redefine the exponential function .^ in MATLAB? From:
x.^y
to:
sign(x).*abs(x.^y))
A: Don't. It won't be correct. (-1).^(1/2) should always give you the imaginary unit (i). The expression you have would give you (-1).^(1/2) -> -1. Even worse, consider (-1)^2.
Create a separate function to perform the operation you're describing. Something like
function a = myPowerFunc(x, y)
a = sign(x).*abs(x.^y);
A:
Can you redefine an arithmetic operator in MATLAB?... Yes
Should you redefine an arithmetic operator in MATLAB?... Eh, probably not.
Why? Because every other function in MATLAB expects that the arithmetic operator will behave as defined by the built-in implementation.
I've answered a few other related questions that have dealt with overloading arithmetic operators and shadowing built-in behavior, which I definitely suggest reading through first to understand the details, difficulties, and pitfalls involved in such an approach:
*
*MATLAB: Is it possible to overload operators on native constructs (cells, structs, etc)?
*How do I get real integer overflows in MATLAB/Octave?
And now that I'm done with my disclaimer, I'll hand you the gun with which to potentially shoot yourself in the foot... ;)
Arithmetic operators in MATLAB have functional equivalents that are called behind the scenes when you invoke them, which are listed here. The arraywise power operator .^ calls the built-in power function when invoked.
Now, there will be a separate power function defined for each data type that uses it. This function will be placed in an @type directory, which you can see by using the which function to look at the different power functions that exist:
>> which power -all
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@single\power) % single method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@double\power) % double method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@char\power) % char method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int64\power) % int64 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int32\power) % int32 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int16\power) % int16 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@int8\power) % int8 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint64\power) % uint64 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint32\power) % uint32 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint16\power) % uint16 method
built-in (C:\Program Files\MATLAB\R2010b\toolbox\matlab\ops\@uint8\power) % uint8 method
If your variables x and y are going to be of type double (as they are by default in MATLAB), then you will have to shadow the built-in @double\power function. You can do this by creating a directory (we'll call it temp), creating a subdirectory within that called @double, and then placing the following custom power function in that subdirectory:
function result = power(x, y)
result = sign(x).*abs(builtin('power', x, y));
end
Now, based on the function precedence order MATLAB follows, if you add the directory temp to the MATLAB path, or if you simply change the current working directory to temp, then the above custom power function will be called instead of the built-in one when using the .^ operator on double variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rails submit button not working in Internet Explorer Bizzarre issue I've been working that is beyond frustrating. The submit button on one of my edit views is not working in Internet Explorer. It is a pretty standard layout using input type = submit (not a customized button_to or something).
*
*The button works fine in Safari, Chrome, and Firefox on both Mac and Windows.
*Edit submit buttons work fine on other pages in IE
*Using nested_form_for, with :html => {:multipart => true}
Submit button
<%= f.submit("update", :class=>"post_button")%>
Has anyone had issues with submit buttons not working in IE?
== update ==
Updated jQuery to make sure it wasn't a nested_form issue. I actually think the link may be not been working before I added the nested form. However, it has always been a multipart form.
View
<head>
<%= stylesheet_link_tag 'profile' %>
<%= javascript_include_tag "jquery.min", "nested_form" %>
</head>
<%= nested_form_for(@profile, :html => {:multipart => true}) do |f| %>
<div class="content">
<div class="editprofilesub">
<div class="profile_title"> basic </div>
<table>
<tr>
<td class="profileformright">
<%= f.label :firstname, "First Name" %>
</td>
<td class="profileformleft">
<%= f.text_field :firstname, :class => "profilefield", :class=>"profilefield" %>
</td>
</tr>
<tr>
<td class="profileformright">
<%= f.label :lastname, "Last Name" %>
</td>
<td class="profileformleft">
<%= f.text_field :lastname, :class => "profilefield" %>
</td>
</tr>
<td class="profileformright">
<%= f.label :avatar, "User Image" %><br>
</td>
<td class="profileformleft">
<i>Please rotate images prior to uploading.</i> <br>
<%= f.file_field :avatar%>
</td>
</table>
<div class="profile_title"> location </div>
<table>
<tr>
<td class="profileformright">
<%= f.label :city %>
</td>
<td class="profileformleft">
<%= f.text_field :city, :class => "profilefield" %>
</td>
</tr>
</table>
<br>
<table>
<tr>
<td class="profileformright">
<%= f.label :state, "State" %>
</td>
<td class="profileformleft">
<%= f.select :state, Carmen.state_names(),{}, :class=> "state" %>
</tr>
</table>
<div class="profile_title"> about </div>
<table>
<tr>
<td class="profileformright">
<%= f.label :bio, "about" %>
</td>
<td class="profileformleft">
<%= f.text_area :bio, :rows => '5', :cols => '60', :class => "profilefield" %><br>
</td>
</tr>
<tr>
<td class="profileformright">
<%= f.label :dob, "Date of Birth" %>
</td>
<td class="profileformleft">
<%= f.date_select :dob,
{:start_year => Time.now.year,
:end_year => 1900,
:order => [:month, :day, :year]}%>
</td>
</tr>
</table>
</div>
<div class="right">
<%= f.submit("update", :class=>"post_button")%>
</div>
</div>
<%end%>
A: I just found a similar issue in my non-MVC application, in IE8 and below. When enter is used, the server-side click handler for the submit button wasn't being executed. The problem was that IE doesn't POST the submit button when enter is used (but does when it is clicked). So, .NET knows it's a post back, but not what control caused it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Existing movable type plugin that does URL shortening and redirection? We send out a newsletter that has URLs in it. Rather than having foreign URLs directly, they all come to our website and then redirect to the outside world.
Right now the redirects are all done with HTML files. My goal is to have them all done with redirects in the .htaccess file. So I want to have the person who is entering all of this data enter it all through the movable type GUI.
My questions:
*
*Is there is plug-in for movable type that already does this?
*If not, is there a good template for creating a movable type that allows one to records in the MySQL database?
Thanks.
A: This could be done in the standard Entry interface in MT. Just dedicate a blog for these redirects. You could make the EntryTitle the redirect and have the EntryBody be the full URL (or use Custom Fields). Then just create an .htaccess template that loops through all the entries.
<mt:Entries lastn="0">
Redirect /<mt:EntryTitle dirify="-"> <mt:EntryBody>
</mt:Entries>
A: The way I would do this is to create a custom field for the outside URL.
Then I would populate the .htaccess file with something like:
Redirect /
In the above coding, I'm looping through the latest 999 entries and I'm checking if the custom field with the tag 'EntryDataMyCustomField' is filled out.
If it is filled out, then I redirect / to the URL from that custom template.
This is like redirecting say:
/234 to whatever URL you may think of, like say:
http://en.wikipedia.org/wiki/Main_Page
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Use Rails path helpers from inside an plain old ruby class? (Resque job) I need to make some API calls from inside a Resque job (which is just a plain old Ruby class) and those API calls need to include URLs to resources on my site.
Is it "correct" to just add this to my class definition?
include Rails.application.routes.url_helpers
Or is there an "expected" way to do this?
A: It seems that is the way to do it.
http://snipplr.com/view/37063/to-access-url-helpers-urlfor-etc-from-rails-console-rails-3/
linked to from here http://apidock.com/rails/ActionController/UrlWriter
A: In your controller:
Rails 1.x:
include Rails.application.routes.url_helpers
Rails 2.x:
include ActionController::UrlWriter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: AutoSuggest running problem
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<html xmlns="http://www.w3c.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<link type="text/css" rel="stylesheet" href="themes/bluesky/skin.css"/>
</h:head>
<h:body>
<center>
<p:panel header="Login Form" style="width: 350;">
<h:form>
<h:panelGrid columns="2" cellpadding="2">
<h:outputLabel for="#{UserManagedBean.username}" value="UserName"/>
<h:inputText value="#{UserManagedBean.username}" label="UserName"/>
<h:outputLabel for="#{UserManagedBean.password}" value="Password"/>
<h:inputSecret value="#{UserManagedBean.password}"/>
<h:commandButton type="submit" value="Login" action="#{UserManagedBean.login}"/>
</h:panelGrid>
</h:form>
</p:panel>
<div>
<h:messages/>
</div>
</center>
</h:body>
</html>
What could be the possible problem here? I really don't know.
A:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
This is a typical MSIE warning message whenever you request a X(HT)ML file which does not have a XSL stylesheet (which is basically like CSS for HTML).
That you're getting this on a Facelet page can only mean that the request URL did not match the URL pattern of the FacesServlet as definited in your webapp's web.xml. In other words, the FacesServlet has never got any chance to run, parse that Facelet file and do all the JSF works to generate a bunch of HTML so that the webbrowser has something sensible to work with.
There are 2 solutions for this problem:
*
*Fix your request URL (the one in browser address bar) to match the URL pattern of the FacesServlet in web.xml. If it is for example <url-pattern>*.jsf</url-pattern>, then you need to replace .xhtml extension in URL by .jsf.
*Change the URL pattern of your FacesServlet to <url-pattern>*.xhtml</url-pattern>. This way you do not need to worry about accidently seeing XHTML source anymore.
Please note that this all has nothing to do with "autosuggest problem". Work yourself through some basic JSF tutorials first. Our JSF wiki page has some good links.
Oh, before I forgot, the <center> element is deprecated since HTML4 in 1998. Do not use it. Use CSS margin: 0 auto;. Try to avoid reading tutorials/books older than 2 years.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Understanding merge sort optimization: avoiding copies I have below merge sort program in algorithms book, it is mentioned that The main problem is that merging two sorted lists requires linear extra memory, and the additional work spent copying to the temporary array and back, throughout the algorithm, has the effect of slowing down the sort considerably. This copying can be avoided by judiciously switching the roles of "a" and "tmp_array" at alternate levels of the recursion.
My question is what does author mean "copying can be avoided by judiciously switching the roles of a and tmp_array at alternate levels of the recursion" and how it is possible in following code? Request to show an example how we can achieve this?
void mergesort( input_type a[], unsigned int n ) {
input_type *tmp_array;
tmp_array = (input_type *) malloc( (n+1) * sizeof (input_type) );
m_sort( a, tmp_array, 1, n );
free( tmp_array );
}
void m_sort( input_type a[], input_type tmp_array[ ], int left, int right ) {
int center;
if( left < right ) {
center = (left + right) / 2;
m_sort( a, tmp_array, left, center );
m_sort( a, tmp_array, center+1, right );
merge( a, tmp_array, left, center+1, right );
}
}
void merge( input_type a[ ], input_type tmp_array[ ], int l_pos, int r_pos, int right_end ) {
int i, left_end, num_elements, tmp_pos;
left_end = r_pos - 1;
tmp_pos = l_pos;
num_elements = right_end - l_pos + 1;
/* main loop */
while( ( 1_pos <= left_end ) && ( r_pos <= right_end ) )
if( a[1_pos] <= a[r_pos] )
tmp_array[tmp_pos++] = a[l_pos++];
else
tmp_array[tmp_pos++] = a[r_pos++];
while( l_pos <= left_end ) /* copy rest of first half */
tmp_array[tmp_pos++] = a[l_pos++];
while( r_pos <= right_end ) /* copy rest of second half */
tmp_array[tmp_pos++] = a[r_pos++];
/* copy tmp_array back */
for(i=1; i <= num_elements; i++, right_end-- )
a[right_end] = tmp_array[right_end];
}
A: Start by thinking of merge sort in this way.
0: Consider the input array A0 as a collection of ordered sequences of
length 1.
1: Merge each consecutive pair of sequences from A0, constructing a
new temporary array A1.
2: Merge each consecutive pair of sequences from A1, constructing a
new temporary array A2.
...
Finish when the last iteration results in a single sequence.
Now, you can obviously get away with just a single temporary array by doing this:
0: Consider the input array A0 as a collection of ordered sequences of
length 1.
1: Merge each consecutive pair of sequences from A0, constructing a
new temporary array A1.
2: Merge each consecutive pair of sequences from A1, overwriting A0
with the result.
3: Merge each consecutive pair of sequences from A0, overwriting A1
with the result.
...
Finish when the last iteration results in a single sequence.
Of course, you can be even smarter than this. If you want to be nicer to the cache, you might decide to sort top-down, rather than bottom-up. In this case, it hopefully becomes obvious what your textbook means when it refers to tracking the role of the arrays at different levels of recursion.
Hope this helps.
A: I'm going to assume that, without looking at this code, it is performing merge sort by declaring a contiguous block of memory the same size as the original.
So normally merge sort is like this:
*
*split array in half
*sort half-arrays by recursively invoking MergeSort on them
*merge half-arrays back
I'm assuming it's recursive, so no copies will be done before we're sorting sub-arrays of size 2. Now what happens?
_ means it is memory we have available, but we don't care about the data in it
original:
8 5 2 3 1 7 4 6
_ _ _ _ _ _ _ _
Begin recursive calls:
recursive call 1:
(8 5 2 3) (1 7 4 6)
_ _ _ _ _ _ _ _
recursive call 2:
((8 5) (2 3)) ((1 7) (4 6))
_ _ _ _ _ _ _ _
recursive call 3:
(((8) (5))((2) (3)))(((1) (7))((4) (6)))
_ _ _ _ _ _ _ _
Recursive calls resolving with merging, PLUS COPYING (uses more memory, or alternatively is 'slower'):
merge for call 3, using temp space:
(((8) (5))((2) (3)))(((1) (7))((4) (6))) --\ perform merge
(( 5 8 )( 2 3 ))(( 1 7 )( 4 6 )) <--/ operation
UNNECESSARY: copy back:
(( 5 8 )( 2 3 ))(( 1 7 )( 4 6 )) <--\ copy and
_ _ _ _ _ _ _ _ --/ ignore old
merge for call 2, using temp space:
(( 5 8 )( 2 3 ))(( 1 7 )( 4 6 )) --\ perform merge
( 2 3 5 8 )( 1 4 6 7 ) <--/ operation
UNNECESSARY: copy back:
( 2 3 5 8 )( 1 4 6 7 ) <--\ copy and
_ _ _ _ _ _ _ _ --/ ignore old
merge for call 1, using temp space:
( 2 3 5 8 )( 1 4 6 7 ) --\ perform merge
1 2 3 4 5 6 7 8 <--/ operation
UNNECESSARY: copy back:
1 2 3 4 5 6 7 8 <--\ copy and
_ _ _ _ _ _ _ _ --/ ignore old
What the author is suggesting
Recursive calls resolving with merging, WITHOUT COPYING (uses less memory):
merge for call 3, using temp space:
(((8) (5))((2) (3)))(((1) (7))((4) (6))) --\ perform merge
(( 5 8 )( 2 3 ))(( 1 7 )( 4 6 )) <--/ operation
merge for call 2, using old array as temp space:
( 2 3 5 8 )( 1 4 6 7 ) <--\ perform merge
(( 5 8 )( 2 3 ))(( 1 7 )( 4 6 )) --/ operation (backwards)
merge for call 1, using temp space:
( 2 3 5 8 )( 1 4 6 7 ) --\ perform merge
1 2 3 4 5 6 7 8 <--/ operation
There you go: you don't need to do copies as long as you perform each "level" of the merge-sort tree in lock-step, as shown above.
You may have a minor issue of parity, also as demonstrated above. That is, your result may be in your temp_array. You either have three options for dealing with this:
*
*returning the temp_array as the answer, and release the old memory (if your application is fine with that)
*perform a single array copy operation, to copy temp_array back into your original array
*allow yourself to consume a mere twice-as-much memory, and perform a single cycle of merges from temp_array1 to temp_array2 then back to original_array, then release temp_array2. The parity issue should be resolved.
This is not necessarily "faster":
additional work spent copying to the temporary array and back
This is actually not the core reason why it's 'faster' per se. It is obviously not asymptotically faster, nor necessarily even faster. There is a notion of latency vs. throughput. Generally running time is measured in latency, because extra garbage work (like releasing memory) may be done asynchronously. You don't necessarily need to copy "back" to the original array depending on your language. However, if you are repeating something many times on memory-bound hardware in a garbage-collected language, the garbage collection can occasionally be forced to spike if the GC algorithm is a poor choice for what you are doing (or if this is C, maybe you are waiting to allocate). Thus if you were to create extra memory in a GC language, it should not really count against you. Granted, this may cause you not to take advantage of cache properly if you use too much memory. You'd have to benchmark it yourself, very carefully for your use case.
I do not recommend creating random temporary arrays for each step though, as that would make memory O(N log(N)) and this is a trivial optimization.
Minor notes on in-placeness:
Also, the reason you can't naively do it in-place is because while you are merging two sorted sub-arrays, the new result sorted sub-array may take arbitrarily many from one input array before spontaneously swap to the other array. For example, as you can see we need a buffer because our input arrays might get split into fragments:
( 4 6 7 8 10)(1 2 3 5 9 11)(... other sub-arrays)
( 1)(6 7 8 10)(4)(2 3 5 9 11)(...
( 1 2)(7 8 10)(4 6)(3 5 9 11) ...
( 1 2 3)(8 10)(4 6 7)(5 9 11)
( 1 2 3 4(10)(8)(6 7)(5 9 11) ooph :-(
( 1 2 3 4 5)(8)(6 7)(10)(9 11) ooph
You might be able to so cleverly in-place if you do some weird variant of the kth-statistic median-of-medians algorithm, performing your merge into the middle of the two arrays rather than the start (merging from a specifically chosen element outwards left/decreasing and right/increasing simultaneously). I'm not sure how one would implement that though, or if the hunch is true.
(very minor note: Perhaps those who are familiar with sorting algorithms should be careful of comparing a traditional swap traditional swap operation involving a tmp variable in a register, which is two reads-from-cache and two writes-to-cache, to not-in-place copying to other bits of memory, without a per-operation counting argument.)
Certainly, OP's method is extremely simple to code for only twice as much memory.
A: Here is my implementation without extra copies.
public static void sort(ArrayList<Integer> input) {
mergeSort(input, 0, input.size() - 1);
}
/**
* Sorts input and returns inversions number
* using classical divide and conquer approach
*
* @param input Input array
* @param start Start index
* @param end End index
* @return int
*/
private static long mergeSort(ArrayList<Integer> input, int start, int end) {
if (end - start < 1) {
return 0;
}
long inversionsNumber = 0;
// 1. divide input into subtasks
int pivot = start + (int) Math.ceil((end - start) / 2);
if (end - start > 1) {
inversionsNumber += mergeSort(input, start, pivot);
inversionsNumber += mergeSort(input, pivot + 1, end);
}
// 2. Merge the results
int offset = 0;
int leftIndex = start;
int rightIndex = pivot + 1;
while (leftIndex <= pivot && rightIndex <= end) {
if (input.get(leftIndex + offset) <= input.get(rightIndex)) {
if (leftIndex < pivot) {
leftIndex++;
} else {
rightIndex++;
}
continue;
}
moveElement(input, rightIndex, leftIndex + offset);
inversionsNumber += rightIndex - leftIndex - offset;
rightIndex++;
offset++;
}
return inversionsNumber;
}
private static void moveElement(ArrayList<Integer> input, int from, int to) {
assert 0 <= to;
assert to < from;
assert from < input.size();
int temp = input.get(from);
for (int i = from; i > to; i--) {
input.set(i, input.get(i - 1));
}
input.set(to, temp);
}
A: Look at the very last part of the merge function. What if, instead of copying that data, you just used the knowledge that the sorted part is now in tmp_array instead of a when the function returns, and a is available for use as a temp.
Details are left as an exercise for the reader.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: querying arcgis and getting results sorted by distance from some point Using the REST or javascript api, does anyone know how to get results back sorted by distance from a point? I'm doing someething like this:
http://help.arcgis.com/en/webapi/javascript/arcgis/help/jssamples_start.htm
and i need the results sorted by distance from the center of a google map.
Thanks!
A: you might could set up a geoprocessing task with the 'Near' Arctool.
and then sorting the result.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C Memory Management in Embedded Systems I have to use c/asm to create a memory management system since malloc/free don't yet exist. I need to have malloc/free!
I was thinking of using the memory stack as the space for the memory, but this would fail because when the stack pointer shrinks, ugly things happen with the allocated space.
1) Where would memory be allocated? If I place it randomly in the middle of the Heap/Stack and the Heap/Stack expands, there will be conflicts with allocated space!
12 What Is the simplest/cleanest solution for memory management? These are the only options I've researched:
*
*A memory stack where malloc grows the stack and free(p) shrinks the stack by shifting [p..stack_pointer] (this would invalidate the shifted memory addresses though...).
*A linked list (Memory Pool) with a variable-size chunk of memory. However I don't know where to place this in memory... should the linked list be a "global" variable, or "static"?
Thanks!
A: This article provides a good review of memory management techniques. The resources section at the bottom has links to several open source malloc implementations.
A: Declare a huge static char buffer and use this memory to write your own malloc & free functions.
Algorithms for writing malloc and free could be as complex (and optimized) or as simple as you want.
One simple way could be following...
based on the type of memory allocation needs in your application try to find the most common buffer sizes
*
*declare structures for each size with a char buffer of that length
and a boolean to represent whether buffer is occupied or not.
*Then declare static arrays of above structures( decide array sizes
based on the total memory available in the system)
*now malloc would simply go the most suitable array based on the
required size and search for a free buffer (use some search algo here
or simply use linear search) and return. Also mark the boolean in the
associated structure to TRUE.
*free would simply search for buffer and mark the boolean to FALSE.
hope this helps.
A: For embedded systems the memory is partitioned at link time into several sections or pools, i.e.:
ro (code + constants)
rw (heap)
zi (zero initialised memory for static variables)
You could add a 4th section in the linker configuration files that would effectively allocate a space in the memory map for dynamic allocations.
However once you have created the raw storage for dynamic memory then you need to understand how many, how large and how frequent the dynamic allocations will occur. From this you can build a picture of how the memory will fragment over time.
Typically an application that is running OS free will not use dynamic memory as you don't want to have to deal with the consequences of malloc failing. If at all possible the better solution is design to avoid it. If this is not at all possible try and simplify the dynamic behaviour using a few large structures that have the data pre-allocated before anything needs to use it.
For example say that you have an application that processes 10bytes of data whilst receiving the next 10 bytes of data to process, you could implement a simple buffering solution. The driver will always be requesting buffers of the same size and there would be a need for 3 buffers. Adding a little meta data to a structure:
{
int inUse;
char data[10];
}
You could take an array of three of theses structures (remembering to initialise inUse to 0 and flick between [0] and [1], with [2] reserved for the situations when a few too many interrupts occur and the next buffer is required buffer one is freed (the need for the 3rd buffer). The alloc algorithm would on need to check for the first buffer !inUse and return a pointer to data. The free would merely need to change inUse back to 0.
Depending on the amount of available RAM and machine (physical / virtual addressing) that you're using there are lots of possible algorithms, but the more complex the algorithm the longer the allocations could take.
A: Use the GNU C library. You can use just malloc() and free(), or any other subset of the library. Borrowing the design and/or implementation and not reinventing the wheel is a good way to be productive.
Unless, of course, this is homework where the point of the exercise is to implement malloc and free....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to receive AJAX data in CherryPy Beginning to climb the ajax learning curve, I'm trying to make a simple ajax call back to my CherryPy application and echo the data sent back to the browser.
My ajax call is working and I can return, for instance, the request method back to the browser.
I cannot, however, find the data sent by browser in the request object inside my CherryPy handler. Here is my CherryPy handler, cribbed from this question:
class Contact:
def index(self):
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read(int(cl))
body = None
#body = simplejson.loads(rawbody)
if body is None:
return cherrypy.request.method + ' (no body found)'
else:
return cherrypy.request.method + ' ' + body
index.exposed = True
and here's my Javascript:
<script type="text/javascript">
function SendContactEntry() {
$.ajax( {type: "POST",
url: "/contact/",
data: { word: "HELLO" },
processData: false,
cache: false,
contentType: "application/json",
dataType: "text",
success: function (response){
alert(response);
}
}
);
}
</script>
Using this code my browser receives back a response of "POST (no body found)".
What I want to do is learn, in my CherryPy handler, that I was sent a word value of "HELLO".
If I uncomment the line body = simplejson.loads(rawbody) I receive an HTML Status of 500 back from CherryPy. The same happens if I try to decorate my index() function with @cherrypy.tools.json_in().
A: word may be in cherrypy.request.params already. Check in there?
http://www.cherrypy.org/wiki/RequestObject#params
I don't think jQuery converts the stuff you put into data as a JSON object. http://api.jquery.com/jQuery.ajax/
A: Since you have set processData to false and you are passing over an object you are sending over a stringified version of your data object - and there is nothing to see.
Either:
*
*Call JSON.stringify on your data object before sending it over (which should make your simplejson.loads call work).
*Remove your processData attribute and let jQuery send the request over as a normal URL-encoded request (and you can access your variables through request.params["word"]).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Does having more buckets in amazon s3 matter? My website currently has 3 sections in which i want store files, lets call it A, B, and C. Whats the difference of making my file structure like this:
bucket -> A, B, C
or making the structure like this:
bucket ->A
bucket->B
bucket->C
*consider the A, B, and C as folders
A: I would imagine the role of S3 bucket is comparable to that of 'database' (ie, bucket == database). So, would you like to have 3 databases, or just 1? Having them separated may make sense if the data is unrelated and has different usage patterns, but of course it is more complex. So, if you have no particular reason to split your data (like different security requirements), I'd put that into one bucket.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Write consistency with nested subquery in Oracle I've read many of the gory details of write consistency and I understand how it works in the simple cases. What I'm not clear on is what this means for nested sub-queries.
Here's a concrete example:
A table with PK id, and other columns state, temp and date.
UPDATE table SET state = DECODE(state, 'rainy', 'snowy', 'sunny', 'frosty') WHERE id IN (
SELECT id FROM (
SELECT id,state,temp from table WHERE date > 50
) WHERE (state='rainy' OR state='sunny') AND temp < 0
)
The real thing was more convoluted (in the innermost query), but this captures the essence.
If we assume the state column is not nullable, can this update ever fail due to concurrent modification (i.e., the DECODE function doesn't find a match, a value of 'rainy' or 'sunny', and so tries to insert null into a non-nullable column)?
A: Oracle supports "statement level read and write consistency" (as all other serious DBMS)
This means that the statement as a whole will not see any changes to the database that occurred after the statement started.
As your UPDATE is one single statement there shouldn't be a case where the decode returns null.
Btw: the statement can be simplified, you don't need the outer SELECT in the sub-query:
UPDATE table SET state = DECODE(state, 'rainy', 'snowy', 'sunny', 'frosty')
WHERE id IN (
SELECT id
FROM table
WHERE date > 50
AND (state='rainy' OR state='sunny')
AND temp < 0
)
A: I don't see any reason to be concerned. The subquery explicitly retrieves only IDs of rows with state 'rainy' or 'sunny' and that's what outer DECODE is going to get. Thole thing is one statement, and is going to be executed within transaction boundaries.
A: Answering my own question: turns out there is a bug in Oracle which can cause this query to fail. Details confirmed by Tom Kyte, in the discussion starting here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: $.ajax & passing data to .asmx webservice I'm quite confused as to why this is happening.
I can't seem to pass data successfully via $.ajax, the URL gets all mangled up instead of the data being passed in a query string.
I've cleaned up the code for brevity, see below.
Webservice (using GET)
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string TestMethod(string country, string city)
{
return country + city;
}
jQuery
$.ajax({
url: "Test.asmx/TestMethod",
type: "GET",
data: '{"country":"' + country + '","city":"' + city + '"}',
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
Resulting URL and Error (in Firebug)
http://example.com/Test.asmx/TestMethod?{%22country%22:%22NZ%22,%22city%22:%22AK%22}
System.InvalidOperationException: Missing parameter: country.
A: Try to change
data: '{"country":"' + country + '","city":"' + city + '"}'
To
data: "country="+country+"&city="+city
A: Adding a "contentType" property to the options list would be the easiest change in my mind.
I also use JSON.stringify() to reduce the introduction of quotation errors.
$.ajax({
url: "Test.asmx/TestMethod",
type: "GET",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ country: country, city: city }),
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can I simulate multiple clients this way? I wrote a small server program. I wanted to see how it is handling multiple requests. So I wrote the following program to simulate multiple clients.
Pseudo Code:
main()
{
//set up all necessary data structures to connect to the server
fork();
fork();
fork();
create_socket();
connect()
//more code
}
Is there a better way of doing it? What tools I can use to test multi threaded program in C(at least the basic functionality)?
A: You've basically created a "process-fan" with this approach, so yes, that can work, although it's not threading ... you're actually creating new processes. Therefore you will want, in order to prevent zombie child processes, to "wait" for all processes to complete in each process that has spawned a new process. You could do this with the following line at or near the end of your main() for all processes that have called fork() (i.e., include the child-processes as well since they are spawning additional processes):
while(wait(NULL) != -1 || errno == EINTR);
This will wait for all the child-processes the current process has spawned, while preventing any early returns of wait() due to your process catching a signal. When there are no remaining child-processes for the current process, then wait() will return -1 and set errno to ECHILD, thus exiting the while-loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to select display:none labels from the div i want to select all labels inside a div that are only apply style display:none
labels like below
<label for="txtAmount_146" generated="true" class="errortd" style="display: none; ">This field is required.</label>
i tried
if($('.errortd', this).not(':hidden')){
alert($(this).text())
}
I have no luck still any help
A: You want to select all labels that have "display:none" and do something, right?
Consider this html:
<div id="something">
<label class="errortd" style="display: none; ">This field is required 1.</label>
<label class="errortd" >This field is required 2.</label>
<label class="errortd" style="display: none; ">This field is required 3.</label>
</div>
You can alert the text of the first and third label with this:
$(function(){
$('#something label:hidden').each(function(){
alert( $(this).text() );
});
});
A: This should do it
$("label:hidden", "div")...
So to do something like you do in your example do:
$("label:hidden", "div").each(function(i) { alert($(this).text();});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jQuery tooltip with link inside I have a grid of large images for products. I'm looking to have a tooltip appear when you rollover the image. Though the tooltip will need to stay visible because there will be content and links inside of it. The tooltip will be positioned partly on top of its respective large product image. How do I determine to hide the tooltip when the user is not over the tooltip and the product image and show the tooltip when the user is over the tooltip and image?
Is there a jQuery plugin that handles this already?
Any help is appreciated! Thanks!
A: Hey I had an issue like this once. Though not exactly what you need this is what I ended up using.
var over_picker = false; //var to store state of over or not over
$('.list_picker').live('mouseover mouseout', function(event){
if (event.type == 'mouseover') {
over_picker=true;
console.log('inside');
}else{
over_picker=false;
console.log('outside');
}
});
$('body').live('click', function(){
if(! over_picker) $('.list_picker').hide();
});
I hope this can be of some help.
A: As already suggested in another thread, the native design of the tooltip rely on different assumptions, so the behaviour you need (a sticky tooltip that allows the user to click its content) is not officially supported.
Anyway looking at this link you can see it's possibile to achieve what you need using jQuery Tools:
http://jquerytools.org/demos/tooltip/any-html.html
Here is a standalone demo
http://jquerytools.org/demos/tooltip/any-html.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android OnItemClickListener not working I'm using android 2.3.3. I set up a layout like,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/mainList" android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And I'm manipulating it with
package org.dewsworld.ui;
import org.dewsworld.core.NBConfig;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class NewsBotActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter( new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
NBConfig.topics));
ListView listView = (ListView) findViewById(R.id.mainList) ;
listView.setOnItemClickListener( new OnItemClickListener() {
});
}
}
Using eclise IDE, when I setthe OnItemClickListener it gives me the error
The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView<ListAdapter> is not applicable for the arguments (new
OnItemClickListener(){})
I can't fix this. [I've added an image with the error]
A: how about filling in the body of your new object by defining the onItemClick() function:
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Display a messagebox.
Toast.makeText(this,"Your Listener Works!",Toast.LENGTH_SHORT).show();
}
try using ctrl+shift+o in eclipse to organize all your imports automatically...
A: It seems you have imported the wrong OnItemClickListener, try this one instead, and remove import of android.view.View.OnClickListener
import android.widget.AdapterView.OnItemClickListener;
A: Just implement OnItemClickListener to your class.
Like This:
public class ClassName extends Activity implements OnItemClickListener{}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Index out of bounds array exception +Streamreader I have encountered an array index out of bounds exception based on the following codes:
I understand that readtoend method may disrupt the pointer for the streamreader, hence i implement the discardbuffereddata and seekorigin 0. However, im still getting an index out of bounds. help please? thanks!
StreamReader sr = new StreamReader(@".\Input\" + inServer + ".txt");
readall = sr.ReadToEnd();
string[] splited = Regex.Split(readall, "~~~~~~~~~~~~~~");
sr.BaseStream.Seek(0, SeekOrigin.Begin);
sr.DiscardBufferedData();
while (sr.Peek() >= 0)
{
currLine = sr.ReadLine();
}
A: try modifying your codes as follows:
readAll = sr.ReadToEnd();
sr.Close();
foreach (string s in readAll.Split(new char[] { '\r', 'n' }))
{
currLine = s;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.