text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: how does one check if UIWebView is empty or not I need to check if a webview when completed loading has any content or not.
What I require is simple. Its a small webview strip at the bottom of my pages (like an advert)
I call
NSURLRequest *request=[NSURLRequest requestWithURL:adURL];
[gWebView loadRequest:request];
I get the callback
-(void)webViewDidFinishLoad:(UIWebView *)webView {
But in my scenario the webview shall return empty and sometime it shall have data.
I do not want to show the webview if my server php file returned nothing.
How can I verify that I received an empty page in the callback (or any other way)?
A: This is based on Jano's approach but should perform better:
NSString *script = @"document.getElementsByTagName('body')[0].innerHTML.length";
NSString *length = [self.webView stringByEvaluatingJavaScriptFromString:script];
if (length.integerValue > 0) {
NSLog(@"not empty");
}
A: Just replying to an old post, but maybe new arrivals will find it useful. I struggled with the same problem and found this solution to work in my case:
if (webView.request.URL.absoluteURL == nil) {
NSLog(@"nil webby");
NSLog(@"url: %@", webView.request.URL.absoluteURL);
// Perform some task when the url is nil
} else {
NSLog(@"loaded webby");
NSLog(@"url: %@", webView.request.URL.absoluteURL);
// Perform some task when the url is loaded
}
You can call it from the webViewDidFinishLoad: method.
A: If you are loading a HTML page:
NSString *string = [myWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
BOOL isEmpty = string==nil || [string length]==0;
Or you could load the content first, test if it is not empty, and then feed it to the webview. See UIWebView's loadHTMLString:baseURL: or loadData:MIMEType:textEncodingName:baseURL:.
A: In my case, I was looking to detect if the PDF was malformed. I.e., the web view would be empty because the PDF could not be loaded. Since with iOS 7.1.1, I wasn't getting the didFailLoadWithError delegate callback, I needed a different way to do this. I ended up using the method below before attempting to load the PDF doc into the web view.
// See https://developer.apple.com/library/ios/documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html
- (BOOL) isValidPDFDoc: (NSURL *) deviceLocalURL {
CFStringRef path;
CFURLRef url;
CGPDFDocumentRef document;
size_t count;
BOOL validDocument = YES;
// Must use path of URL not absoluteString here.
path = CFStringCreateWithCString (NULL, [[deviceLocalURL path] cStringUsingEncoding:NSASCIIStringEncoding],
kCFStringEncodingUTF8);
url = CFURLCreateWithFileSystemPath (NULL, path, // 1
kCFURLPOSIXPathStyle, 0);
CFRelease (path);
document = CGPDFDocumentCreateWithURL (url);// 2
if (!document) {
validDocument = NO;
}
CFRelease(url);
count = CGPDFDocumentGetNumberOfPages (document);// 3
if (count == 0) {
validDocument = NO;
}
CGPDFDocumentRelease (document);
return validDocument;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Passing on a list of arguments I am trying to pass on a list of arguments to sprintf which apparently doens't pick them up. What am i missing?
void respond( const char *format, ...) {
char buffer[256];
va_list args;
int len, retCode;
va_start( args, format);
len = sprintf( buffer, format, args);
va_end( args);
retCode = send( newSockFD, buffer, len, 0);
if( retCode == -1) error( "Could not write to socket");
}
A: Use vsnprintf() instead sprintf().
http://pubs.opengroup.org/onlinepubs/009695399/functions/vprintf.html
A: sprintf can not work with varable argument so use
vsnprintf()
len = vsnprintf( buffer, sizeof(buffer),format, args);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Algorithm to find all possible 'StringPairGroups' in Java? Mathematics/algorithms was never my strong point (!) so requesting help on this one.
What is the most efficient implementation for a method with the following signature:
/*
* pairParts.size() > 0
* pairParts.size() is always an even number
*/
private Set<StringPairGroup> getAllPossibleStringPairGroups(Set<String> pairParts) {
Set<StringPairGroup> groups = new HashSet<StringPairGroup>();
// logic that adds all possible StringPairGroups
` return groups;
}
/*
* StringPair object: first and second values cannot be null.
* StringPair object: first != second
* StringPair object: is equal to another if both the first values and both the second values are equal.
*/
public class StringPair {
private final String first;
private final String second;
...
}
/*
* StringPairGroup object: is equal to another if their StringPair sets exactly match.
*/
public class StringPairGroup {
Set<StringPair> stringPairs
...
}
As an example an input of {'A', 'B'} would return {[AB],[BA]}.
An input of {'A', 'B', 'C', 'D'} would return
{[AB],[BA],[AC],[CA],[AD],[DA][...], [AB,CD],[BA,CD],[AB,DC],[BA,DC],[AC,DB],[...]}.
I am really just interested in the logic that creates all the possible StringPairGroups
for any set of input Strings. I could probably come up with some sort of brute force implementation but would rather know how to do something a lot 'cleverer'.
So any hints as to how I would implement that would be useful.
Edit:
Sorry guys I think I may have missed off something quite important. I am really beggining to confuse myself. This is it:
A StringPairGroup cannot contain a repeated 'pair part' across all of its StringPairs. Does that make sense?
A: I would do it this way:
*
*Implement a comparison in StringPair that when passed another StringPair compares to see if they share any element: boolean shareElement(StringPair other)
*I could create a list of all possible StringPairs [AB], [BA], [AC], [CA]
*I would then do the following for i = 1 - (originalList.size() / 2)...
a. Create combinations of i elements from the unique pair list that do not share any elements.
Combine this solution with @Hemal Pandya's and I think you will have your answer. Meaning, use Hemal's recursive combination of the sets in combination with the shareElement above.
Edit: I would also create a boolean shareElement(StringPair... others)
A: I don't know if this is efficient, but here's an attempt..
In step 1 Given A, B, C generate [A,B], [A,C], [B, A], [B, C], [C, A], [C, B]
That's easy (right?).
Now, initially you had a set of 3 elements, each of size 1, from which you generated the pairs.
After the first step you have set of 6 elements, each of size 2, so you do the same thing you did with the first one to generate the 2nd order sets.
And so on till you have a set of 1 element.
Make sense?
Looking at your note that the order does not matter I am thinking maybe this is incorrect.
A: I understand the question as follows. There is a collection of N different strings (N is even),
e.g. A, B, C, D.
A pair is any concatenation of two different strings from this collection.
So, AB, BA are pairs, but AA is not a pair. A pair is different from another pair
if the corresponding concatenated strings are different strings. So, AB is different from BA,
and AB equals AB (obiously). There are N*N - N different pairs that can be built from
N different strings.
A group of order k is a set of k different pairs. So, [AB], [CD] are groups of order 1
because they both contain 1 pair.
[AB, CD], [BA, CD] are groups of order 2, because they both contain 2 pairs.
Two groups are equal if and only if they are equal as two sets. So, two equal
groups have exactly the same pairs; the order of the pairs does not matter. E.g.,
[AB, CD] and [BA, CD] are different groups because not all pairs in them are equal.
[AB, CD] and [CD, AB] are two equal groups.
All groups of order k can be constructed recursively:
*
*Select any pair P of strings
*If k = 1 return the groups built from all these pairs
*If k > 1:
3.1 Remove this pair from the collection C(N) of N strings, leaving a collection C(N-2)
of the remaining strings.
3.2 Construct all groups of order k-1 from C(N-2) and combine them with the pair P.
Here is a Java program (the complete code is on github:gist). An executable program in on ideone.
public static class Pair {
public String s1, s2;
public Pair(String s1, String s2) {
this.s1 = s1; this.s2 = s2;
}
public String toString() {
return s1 + s2;
}
}
public static class Group {
public List<Pair> pairs = new ArrayList<Pair>();
public Group(Pair p) {pairs.add(p);}
}
public static List<Group> getGroups(String[] strings, int order) {
List<Group> groups = new ArrayList<Group>();
for (int i = 0; i < strings.length; ++i) {
for (int j = 0; j < strings.length; ++j) {
if (i != j) {
Pair p = new Pair(strings[i], strings[j]);
if (order == 1) {
groups.add(new Group(p));
}
else {
String[] strings2 = new String[strings.length - 2];
for (int k = 0, k2 = 0; k < strings.length; ++k) {
if (k != i && k != j) {
strings2[k2++] = strings[k];
}
}
List<Group> groups2 = getGroups(strings2, order - 1);
for (int k = 0; k < groups2.size(); ++k) {
Group g = new Group(p);
groups.add(g);
Group g2 = groups2.get(k);
g.pairs.addAll(g2.pairs);
}
}
}
}
}
return groups;
}
There are N/2 possible orders. Contruct the groups for all these orders and append them.
String strings[] = {"A", "B", "C", "D", "E", "F"};
List<Group> groups = new ArrayList<Group>();
for (int order = 1; order <= strings.length/2; ++order) {
List<Group> groups2 = getGroups(strings, order);
groups.addAll(groups2);
}
The recursive solution is well understandable but less efficient. If your N is large
then you would need a faster iterative solution. The iterative solution is less
illustrative than the recursive one and would not be suitable for the presentation here.
You can consult e.g. Knuth: The Art of Computer Programming, Vol. 4A: Combinatorial Algorithms.
A: I would do it on two stages. First I would create an Iterable implementation that would have a constructor that would take in a Set as a parameter.
Then I would convert the Set into an array (I used Set rather than any other collection to guarantee uniqueness of the input set). You don't really need to store it into the array if you can guarantee no concurrent access.
Then based on the size of the array I calculate the number of possible permutations and store it into a final variable. The formula should be something like N!/2 I think.
I then have two indexes (or iterators) created. First one p is on the first element the second one q is on the second element.
Each time iterate is called, I would check if q is at the end if it is, reset q back to the first element and increment p by 1. If p is also at the end then indicate there is no more elements. Else return the new string pair of p and q.
I can then use this iterable to create a new set, array, etc of string pairs.
The separation would allow you to save memory because you don't store the string pair groups unless you need it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bug with accessing XML data named "duration" Jquery Is there any reason why something named duration wouldn't work in JQuery?
For example, here is my XML
<video description="description etc" duration="43306" id="1144537378001" name="Fashion" thumbnail="http://www.domain.com/1144537378001-219x119.jpg" videoURL="http://www.domain.com/Half.mp4" videoId="1144537378001"/>
alert($(this).attr("duration"));
alert($(this).attr("thumbnail"));
alert($(this).attr("id"));
Everything will alert ok, except duration will always be NaN despite being fine in the XML. Even before I do parseInt or eval.
I can't change the XML so any workarounds using JS would be awesome.
A: works like a dream
http://jsfiddle.net/QevjN/
(its not json data btw)
A: Dodn't know what the issue could be, but you can always try with plain JavaScript dom methods.
document.getElementById("1144537378001").getAttribute("duration");
If it still doesn't work then you can assume that it's not jQuery related.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find the bounding box of each character in a license plate I use emgu with c# to read a license plate in an image. After edge detection I want find the bounding box of each character in it and use neural networks to recognize characters. How can I do it?
Thanks
A: Well the simplest method since you can detect the license plate is to look for the dividing lines. I'm afraid I can only speculate from google images for Iranian number plates (if this is what your using) however after each letter there is a break and a white or yellow area.
To Find the bounding boxes of the individual letters:
You could look at the sum of the columns and where there is a peak in yellow or white and take that as a dividing point. Or you could sum only the black components or the writing, in ideal circumstances you will start with 0 find black components and then return to a a count of 0 and you have your letter. A little adaptable statistics may be needed here.
[EDIT]
Segment the license plate from the image. Start by looking at the sum of each column, you will notice peaks of 255 * the height of the license plate image. Use this as your threshold, find the middle of these peaks and you have the point in which denotes a letter edge. You can segment your image using this data.
Now the peaks may be hard statistically to segment reliably, they shouldn't but just in case. Invert your image so your white is black and your black is white. Again take the sum of the columns in this case the peaks are the locations of the letters now you look for changes from 0 to >1 and wait until you find a 0 again. Recording the x position where this happens will give you your letter locations. I will give you the code for the sum of the columns if needed but google will also have your answer the statistics required are all you, just translate the steps.
An alternative method
An alternative to dividing the image into separate squares or regions and a favourite of students is simply to scan a mask across the license plate. So you feed into your Neural Network (NN) the first ROI say (0,0,100,100) then move one along the y axis (0,1,100,100). You continue this till you read in all your data. You obviously risk the NN from over detecting as it can classify the same letter so many times so when you classify a letter you can always jump 20 pixels or so removing false classifications.
Obviously your will need to reduce the size of the license plate image to make this method quicker. I have seen accurate OCR using 9 by 9 arrays however you will require larger use you best judgement 20x20 should be suffice but have a look.
[EDIT]
Efficiency
Which one is better? well it depends. They will all work (depending on NN tranining), however the methods involved in finding the bounding boxes of the individual letters can be hard to set up reliably. The scanning across of the mask feeding all data into the NN is usually quite reliable but can be incredibly inefficient. If you working with 20*20 images that's 400 data points to feed into the NN and you've got to times that by the license plate width -20. That will give you the maximum number of iterations through the loop.
NN can take a long time to train but also execute with large amounts of data (depending on NN). The method of segmenting each letter is more efficient as you really less on the NN and can feed more accurate data into your NN.
The problem you face is if your using the OCR engine already built into EMGU OCR recognition is extremely quick. As you will be able to see in the EMGU example the only way to decide on the best method is to write and compare all 3 methods. If you just need one that works then use the NN one and where you get a match note that as your letter ROI since you will still know the X position along the license plate.
I'm sorry I can't give you a more direct answer on which ones best but there are two many factors that could effect things.
I hope some of these methods help,
Many Thanks
Chris
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Image Preloading problem with jquery here i am giving the code to preload image by jquery.
var _images = ['/images/ajax-loader.gif'];
$.each(_images, function (e) {
$(new Image()).load(function () {
//alert($(this).attr('src') + 'has loaded!');
}).attr('src', this);
});
the above code works fine because here we hard code the image path but when image path is stored in variable then it is not working.
here i am giving the code which gives error.
var _images = '[' + data.d[0].LabelImagePath + ']';
$.each(_images, function (e) {
$(new Image()).load(function () {
$('#imgHolder').html("<img src='" + data.d[0].LabelImagePath + "' border=0/>");
$("#btnPrint").show();
}).attr('src', this);
});
this line return image path like /images/1Z520777777779.gif.
so please guide me how to preload images when image path is stored in variable with jquery by the above code. thanks
A: You are building up a string instead of an array (I dunno why). Your $.each() expects something that can be iterated.
Try creating an array instead, it will work:
var _images = [data.d[0].LabelImagePath];
Also, inside the $.each(), don't use data.d[0].LabelImagePath, because it will break your code when you're trying to preload more than one image.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cakephp: database, xml or json to generate report I'm trying to generate a student's report card. What is the best way to store the stages of development of each child and his grades? For example:
Name:Carla Smith
Class: Prep II
MOTOR DEVELOPMENT TERM1 TERM2
Draws freehand pictures B A
Cuts and pastes pictures A A
......
WORK HABITS
Works independently C A
Follows instructions C B
TERM 1: Teacher's comments
TERM 2: Teacher's comments
Is it better to store these data in the database or shall I store them in XML or JSON files or are there any other tecniques that i'm not aware of? I don't think it is possible to store in database coz' each development category is going to have many sub categories ie. Motor Development category itself is divided into sub categories.
Any help is much appreciated.
As for the report I intend to use tcpdf from the net.
A: It looks like your data is semi-structured (subcategories...), so XML and JSON seem to be adequate formats.
I think both directions you mention make sense: using a database layer (there are databases that support XML data, for example eXist-db, Sedna, Sausalito, MarkLogic...) or a file system layer (with an XML or JSON file that an XQuery/XSLT engine such as Saxon, Zorba, ... can read and update).
As a rule of thumb, if you have little data, using a file might be easier and faster to set up, whereas if you have a lot of data, an XML database can bring a lot of added value and better performance (indices for example).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Indexer in C# but without this It is posible to craete indexer in C#, but something like this:
public class MyClass
{
Dictionary<int, string> myCollection = new Dictionary<int, string>();
public string Value[int i]
{
get { return myCollection[i]; }
set { myCollection[i] = value; }
}
}
Thanks
A: No, C# do not allows this.
Specification section 1.6.7.3 saying:
An indexer is a member that enables objects to be indexed in the same
way as an array. An indexer is declared like a property except that
the name of the member is this followed by a parameter list written
between the delimiters [ and ].
I would suggest you to use simple method for this like:
public string GetValue(int key)
{
if (dictionary.ContainsKey(key))
.....
}
In your case you reffer dictionary items by key not an index, this is pretty defferent things.
PS: keep in mind that Dictionary does not persist order of the items and this could be vital for some cases!
A: No,
Actually your property Value already have indexer from string and returns char. Probably you need something like this:
public class MyClass
{
Dictionary<int, string> myCollection = new Dictionary<int, string>();
public Dictionary<int, string> Value
{
get { return myCollection; }
set { myCollection = value; }
}
}
And it will be the behaviour what you expected.
string value = myClassInstance.Value[0];
A: You can't do it that way, (not supported by C#)
How about instead
public class MyClass
{
public MyClass()
{
Values = new Dictionary<int, string>()
}
public Dictionary<int, string> Values { get; set }
}
which will then allow you to do
MyClass foo = new MyClass();
var someVal = foo.Values[3];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: javascript to refer to img url: best practices? I have written a tiny bit of javascript which uses two images.
inside the code it does something like
str+='<img src="left.jpg"></img>';
...
str+='<img src="right.jpg"></img>';
...
The script works very well.
The problem is that depending which HTML page uses my script I might get the images broken.
I could solve the problem by defining a directory /img for all the images but I would rather not.
I would rather pack the images required by each script in their folders.
Can somebody suggest how to do this ? or what are the best practices for doing this
thanks
A: But all HTML pages that use your script are, I suppose, in different folders. They try to find images in their folder, and images appear on the page which is in the same folder as images. So you can:
*
*Place all HTML pages in one folder (and images in the same folder)
*Create a separate folder for images and access that folder in the pages
*[not recommended] Make a copy of all the images for each HTML page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to edit Model property as HTML I created module for orchard.
I have the following Model:
public class SliderPart : ContentPart<SliderPartRecord>
{
[Required]
public string Slide1
{
get { return Record.Slide1; }
set { Record.Slide1 = value; }
}
[Required]
public string Slide3
{
get { return Record.Slide3; }
set { Record.Slide3 = value; }
}
[Required]
public string Slide2
{
get { return Record.Slide2; }
set { Record.Slide2 = value; }
}
}
Let say I also have editor template for it:
@Html.EditorFor(m => m.Slide1, new { @class = "text" })
@Html.EditorFor(m => m.Slide2, new { @class = "text" })
@Html.EditorFor(m => m.Slide3, new { @class = "text" })
How to make my fields editable as HTML, like body on Pages module does?
Any idea?
Maybe some attribute to set at Model?
Thank you.
A:
@{
Script.Require("OrchardTinyMce");
}
@Html.TextArea("Slide1", Model.Slide1, 25, 80,
new Dictionary {
{"class", "html tinymce"},
{"data-mediapicker-uploadpath",""},
{"data-mediapicker-title",T("Insert/Update Media")
}
})
and etc for 2nd and 3rd
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to run a service when the screen is locked? I want to recognize a shake event when the screen is locked with my Android.
I made a service to run in background but when the screen is locked, it doesn't work.
Is it possible to run a service when the screen is locked?
If not, is there a workarround :)
A:
The service is down when the phone is locked
No, the service is not "down". The CPU is powered off. When the screen goes dark, the device will normally go into a sleep mode, where nothing is running. This is perfectly normal. Moreover, it is essential for giving the user decent standby battery life.
If, for a minute or two, you want to keep the device running with the screen off, use a WakeLock.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: wp_mail function headers I would to customize the sender of the email so I am trying to set properly the headers of the email.
This is the cose I use to customize the headers:
$current = wp_get_current_user();
global $user_email;
get_currentuserinfo();
$headers_mail = "From: ".$current->first_name." ".$current->last_name." <".$user_email.">" . "\r\n";
and this is the cose I use to send the email:
wp_mail($email, $subject, $message, $headers_mail);
Unfortunately the sender of the email is always set to "WebsiteTitle " where WebsiteTitle is an alias for the real title of the website and mydomain.com is an alias for the real domain of the website.
How can I overwrite the headers of the email? Is there any filter that I should use?
A: Solved.
I used wp_mail_from and wp_mail_from_name filters.
An excellent documentation can be found here http://adambrown.info/p/wp_hooks/hook/wp_mail_from?version=3.2&file=wp-includes/pluggable.php and here http://adambrown.info/p/wp_hooks/hook/wp_mail_from_name?version=3.2&file=wp-includes/pluggable.php
A: You can also use an excellent WP Mail SMTP plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: text box validator for minimum length <asp:RequiredFieldValidator ID="NewPasswordRequired" runat="server" ControlToValidate="NewPassword"
ErrorMessage="New Password is required." ToolTip="New Password is required." ValidationGroup="ChangeUserPasswordValidationGroup">
</asp:RequiredFieldValidator>
How can I validate the text box to enter a value which length should be more than 8 and must contain 1 number and 1 uppercase letter.
A: <asp:RegularExpressionValidator ID="RegExp1" runat="server"
ErrorMessage="Password length must be between 7 to 10 characters"
ControlToValidate="txtPassword"
ValidationExpression="^[a-zA-Z0-9'@&#.\s]{7,10}$" />
A: In addition to your RequiredFieldValidator add a RegularExpressionValidator
For the regex pattern you can use this pattern:
^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$
Must be at least 8 characters
Must contain at least one one lower case letter, one upper case letter, one digit and one special character
Valid special characters are - @#$%^&+=
Technically you could use just the Regex validator but using multiples allows you to have different errors messages depending on a missing vs. simply incorrect password.
A: You should use two separate validators, one to check for length and the other to check for the minimum required characters (that way you get two separate error messages for each check).
Example:
<asp:TextBox ID="MyPasswordField" runat="server" TextMode="Password"></asp:TextBox>
<!-- Add validator for minimum length requirement -->
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordMinLengthValidator" ValidationExpression="^[\s\S]{8,}$" runat="server" ErrorMessage="Password must be at least 8 characters long."></asp:RegularExpressionValidator>
<!-- Add validator for minimum required characters -->
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordRequiredCharacterValidator" ValidationExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$" runat="server" ErrorMessage="Must contain at least one uppercase letter, one lowercase letter, and one number."></asp:RegularExpressionValidator>
If you also need to validate the password for a maximum length as well, you can change the regex for the first validator to be as follows:
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordMinMaxLengthValidator" ValidationExpression="^[\s\S]{8,40}$" runat="server" ErrorMessage="Password must be between 8 and 40 characters long."></asp:RegularExpressionValidator>
If you need to validate that at least one special character was present then you can use this regex for the second validation (at least one of the following characters: <space>@#$%^&?,;:_|{}=+-!.*()[]~):
<asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="MyPasswordField" ID="MyPassordRequiredCharacterValidator" ValidationExpression="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%^&?,;:_|~{}=\+\-\!\.\*\(\)\[\] ]).+$" runat="server" ErrorMessage="Must contain at least one uppercase letter, one lowercase letter, one number, and one special character."></asp:RegularExpressionValidator>
A: I would use two validators: the LenghtValidator and the RegularExpressionValidator.
The advantage of having two validators is that you can have two error messages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Textview not wrapping text I used all possible ways to wrap text in textview but it's not working. It's only showing one line and the rest is gone. I'm fetching address from database and assigning it to textview. I tried textview's height and width parameters with all possible values but it's still not working.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout1" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="fill_horizontal">
<TextView android:layout_toRightOf="@+id/address"
android:layout_alignTop="@+id/address" android:layout_alignBottom="@+id/address"
android:layout_height="wrap_content"
android:id="@+id/addressans"
android:layout_marginLeft="55dp"
android:inputType="textMultiLine"
android:layout_weight="1"
android:ellipsize="none"
android:singleLine = "false"
android:layout_width="wrap_content">
</TextView>
</RelativeLayout>
A: That's coz you specified both android:layout_alignTop="@+id/address" and android:layout_alignBottom="@+id/address". Your TextView has no space to stretch. You probably need to remove android:layout_alignBottom="@+id/address" attribute to let it stretch to the bottom.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mysql insert/update multi rows in one call In my MySql table I want to insert a number of rows. Some of the rows exist and these should only be updated.
So my table looks like this:
mytable: Id (key) | Value (varchar)
And my query is something like this:
INSERT INTO keycomp_mytable (key, value) VALUES
("k1","foo"),("k2","bar"),("k3","baz"),("k4","qux")
If one key exists allready, say k2, then that value should just be updated. How do I do this?
A: Look into the insert on duplicate syntax.
Note that this only works if the duplicate value is a UNIQUE key or a primary key (which in your question looks like this is the case).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python subprocess.Popen and asynchronous output I have simple Python script to execute test suite both under Windows and Linux.
Every test writes its output to separate file.
I use subprocess.Popen class to execute shell command in a cycle.
Every shell command starts like that:
def system_execute(self, command, path, out_file):
params_list = command.split(' ')
file_path = os.path.join(path, out_file)
f = open(file_path, "w")
subprocess.Popen(params_list, stdout=f)
f.close()
It works fine, but script finishes its work before all output files have been written.
Actually, I getting hundreds of zero-size files, and it takes some time to finish writing output and close handles.
Could anyone explain the reason why it works so strange, and is there a synchronous way to do the same job?
Thanks
A: Before f.close(), you have to wait() for our subprocess.
def system_execute(self, command, path, out_file):
params_list = command.split(' ')
file_path = os.path.join(path, out_file)
f = open(file_path, "w")
sp = subprocess.Popen(params_list, stdout=f)
sp.wait()
f.close()
or just
def system_execute(self, command, path, out_file):
params_list = command.split(' ')
file_path = os.path.join(path, out_file)
f = open(file_path, "w")
subprocess.call(params_list, stdout=f)
f.close()
(or, for easier file handling,
[...]
with open(file_path, "w") as f:
subprocess.call(params_list, stdout=f)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Dynamically passing parameters to event listeners AS3 I have a 16x16 grid of buttons, and want to add an event listener to each of them so when clicked it will return its unique grid position number (anything between 0-255);
What I have so far:
public static const GRID_SIZE:Number = 16;
private var i:int;
private var j:int;
// Constructor
public function Grid()
{
for (i = 0; i < GRID_SIZE; i++)
{
for (j = 0; j < GRID_SIZE; j++)
{
// Creates new instance of GridButton, a custom class that extends SimpleButton
var button:GridButton = new GridButton();
// Arranges buttons into a grid
button.x = (i + 1) * button.width;
button.y = (j + 1) * button.height;
// Create unique value for grid position
var position:Number = i * GRID_SIZE + j;
// Add listener to button, with position as extra param
button.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) : void { buttonClick(e, position) } );
// Adds button to Sprite
addChild(button);
}
}
}
}
Unfortunately every time the listener function is called by each button, it uses the last two values of i and j, which in this case return 255 for every button.
Any suggestions?
A: there are some other options...
1 use signals instead of flash event listeners, here's a post that describes it and gives more detail. Also a video tutorial to get you started quickly. The reason I'm suggesting this is that you can setup a signal to pass a parameter, so you don't need to use the event target, which doesn't always work the best.
2 use a function factory.
// factory:
public function fooFactory($mc:GridButton):Function{
var $f:Function = new Function($e:MouseEvent):void{
trace($mc.x, $mc.y);
}
// you might want to consider adding these to a dictionary or array, so can remove the listeners to allow garbage collection
return $f;
}
// then assign the function to the button like this
button.addEventListener(MouseEvent.CLICK, fooFactory(button) );
this does essentially what you wanted to do, but it will work because the position var is not changing. In your code the position is changing every time the loop executes, then when you you fire the listener function it uses the last value that position was assigned, which is why you are getting 255 for all of them. Let me know if that's not making sense...
A: You could add a name to this button, for example button.name = "button" + position; and in event handler function you can extract position parameter from target name (e.target.name):
button.name = "button" + position;
button.addEventListener(MouseEvent.CLICK, buttonClick);
and event handler:
function buttonClick(e:MouseEvent) {
var position:Number = Number(e.target.name.replace("button", ""));
// ... do wathever you want with position parameter
}
A: You can get back the values of i and j from the same expression which is being used to assign x and y values to the buttons. For example:
button.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(e:MouseEvent) {
var i:int = (e.target.x / e.target.width) - 1;
var j:int = (e.target.y / e.target.height) - 1;
var position:Number = i * GRID_SIZE + j;
}
A: I tried this and it worked fine....i.e. clicking on different text fields traced different value.
The idea is to create a new reference to pos:Number so that even after updating pos, the closure still points to the old
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
public class AsDing extends Sprite
{
private static const GRID_SIZE:uint = 2;
public function AsDing()
{
for(var i:uint=0; i<GRID_SIZE; i++)
{
for(var j:uint=0; j<GRID_SIZE; j++)
{
var tf:TextField = new TextField();
var pos:Number = i*GRID_SIZE + j;
tf.text = pos.toString();
tf.type = TextFieldType.DYNAMIC;
tf.addEventListener(MouseEvent.MOUSE_DOWN, createMCHdlr(pos));
addChild(tf);
tf.x = i*100; tf.y = j*100;
}
}
}
private function createMCHdlr(pos:Number):Function
{
var ret:Function = function(evt:MouseEvent):void
{
trace('pos: ' + pos);
};
return ret;
}
}
}
A: By using a variable from outer scope inside an anonymous function you got big trouble with closures and memory leak already: position is used in function(e:MouseEvent), but it was created in function Grid(), so it'll obey function Grid()'s changes. And you're dealing with 256 function(e:MouseEvent)s that you added but can't remove, overheading memory!
Let's remake your code the simplest working way:
public static const GRID_SIZE:Number = 16;
private var i:int;
private var j:int;
public function Grid() {
var functions:Object;
for (i = 0; i < GRID_SIZE; i++) {
for (j = 0; j < GRID_SIZE; j++) {
var button:GridButton = new GridButton();
button.x = (i + 1) * button.width;
button.y = (j + 1) * button.height;
var position:Number = i * GRID_SIZE + j;
functions[position] = buttonClick(position);
button.addEventListener(MouseEvent.CLICK, functions[position]);
//button.removeEventListener(MouseEvent.CLICK, functions[position]);
addChild(button);
}
}
buttonClick(position:Number):Function {
return function(e:MouseEvent):void {
// Now you can use both unique "e" and "position" here for each button
}
}
}
Since you're adding 256 listeners, you have to store each in distinct variables (the list of properties functions[position] was made for it), so you can safely remove each one later to free memory in the same way you added them.
This was elaborated from this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Assertion failure in -[UILabel setFont:] I am getting this exception on setting a font of UILabel in iOS 3.1.2 but its running fine in iOS 4,
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: font != nil'
The code line is,
Outbound_Label.font = [UIFont fontWithName:@"DS-Digital" size:24];
where DS-Digital is my custom font.
A: My guess is that your custom font is not being found instantiated.
Whenever I have a problem like this where there are two things happening: obtaining a font and setting a font, I separate them to find the problem:
UIFont *font = [UIFont fontWithName:@"DS-Digital" size:24];
Outbound_Label.font = font;
Then I can determine where the error is easily with either the debugger or NSLog().
In fact this is a very clear way to write the code in the first place. I never worry about optimization, I only worry about clarity and ease of maintenance. Later if there are performance issues I profile, find the real culprits and resolve them. The clearer the code the easier that is.
In a case like this the compiler will undoubtedly optimize away the font variable so there is no harm.
See this:SO answer
Applications that want to use custom fonts can now include those fonts in their application bundle and register those fonts with the system by including the UIAppFonts key in their Info.plist file. The value of this key is an array of strings identifying the font files in the application’s bundle. When the system sees the key, it loads the specified fonts and makes them available to the application.
A: [UIFont fontWithName:@"DS-Digital" size:24] returns nil. Because no font available for "DS-Digital" (Apple supported font list). so it giving the crash.
A: Please try this, it's works fine for me.
https://github.com/zynga/FontLabel
i have download DS-Digital font from http://www.fontriver.com/font/ds-digital/
and run the above app with this font and it's works with IOS 3.1.2.
Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I am having a requirement to make my UITabbar to Scroll I need a Scrollable UITabbar .I need more than 7 items so I need to make it scroll.
A: I am not pretty much sure about this, but I think if you could display UIView or UIViewController in the UITabbar, it will help you to scroll the view present inside this.
A: if you lay tabbar on the scrollview, you can implement scrollable tabbar.
Adobe method what i explain, maybe one of right methodes. i implement scrollable tabbar adobe method. :D
if wrong my grammar, please understand because i'm not live in englist-speaking countries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: give item direction and speed from the way i swipe on the screen I am working on a game in cocos2d. The game has multiple sprites coming on the screen. I would like to change that items direction ato the direction a swipe and the speed to how fast i swipe . Does anyone know how i can do this?
A: UISwipeGestureRecognizers sort of do what you are asking, although you are limited on the directions you can use. If you want to implement any direction, simply make some code that figured out the direction and speed in the touchesMoved: method. This is a great tutorial on how to get the direction, and also has code which you can modify to get the speed. Simply get the distance and see how long it took to get there, and that gives you the speed. Hope that Helps!
A: Kobold2D (improved Cocos2D) will have built-in gesture recognition starting with Preview 5.
A: If you want to do it without the gesture recognizer, here's a simple D.I.Y solution: http://www.cocos2d-iphone.org/forum/topic/7925
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Highlighting Pushpins with Bing Maps Our website selects establishments from a query and returns the results to the user in batches of 10 locations displaying details in a gridview and locations as user pushpins in bing maps. Hovering the item in the map pops up info panel etc.
My requirements to make this more useable are as follows:-
1) When a user hovers over the item in the gridview list, the corresponding pin on the map should be highlighted.
2) When a user clicks an item in the list, the map zooms to that location. (which I think is relatively simple by redrawing map with different centre and scale)
My thoughts for the first one are to use JavaScript to get the element of the associated pushpin and replace it with a new image in the ‘highlighted’ state and to replace it with the original afterwards.
So my question is:-
Is this the right approach or is there a better one and is there any sample code doing something similar available out there?
Many thanks
Paul
A: That's exactly the approach I use ;) The only slight modification I'd suggest is that, instead of replacing the image with an entirely new one, you make use of a sprite sheet that has both the highlighted and unhighlighted images on it.
Then, in the onmouseover event handler, set the typeName property of the pushpin to assign a CSS class that offsets the image to display only the highlighted state, and in the onmouseout event reset the CSS class again so that the unhighlighted background image is displayed. That way, your page will load quicker and you won't have to risk a flicker as the old image is replaced with the new.
Reference for typeName property: http://msdn.microsoft.com/en-us/library/gg427629.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why does Google use base64 encoded data as image src attributes? All times in my life, I save images on my server as files:
*
*the originals
*the thumbnails
*the original with watermarks
... all as files in folders.
But today, I'm viewing google images, and the src of images is a base64 encoded hash. What benefit does Google get from serving images in this manner? Why would someone do that instead of just serving images conventionally?
A: google is sort of obsessed with latency; latency for the page load goes up if your browser has to go and make a separate request to the web server for every image on the page. you can eliminate this latency by writing the data of the image right into the page when you generate the page. i actually see a lot of image-heavy sites, especially blogs, using this technique nowadays.
just because the image is included in the page doesn't necessarily mean it's not stored as files on the web server -- just that the web server process that generated the page has already opened and read the image file and then wrote it's data into the page. google is probably storing the images in it's proprietary and secret data store, but you don't have to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: read() stops after NUL character I'm downloading files over HTTPS, I request the files through urllib2.Request and they come back as a socket._fileobject. I'd ideally like to stream this to file to avoid loading it into memory but I'm not sure how to do this.
My problem is if I call .read() on the object it only returns all the data up to the first NUL character and doesn't read the whole file. How can I solve this?
The NUL character comes down as \x00 if that's any help, not sure what encoding that is
A: I found out the problem was that I was running the code inside PyScripter and the in-built python interpreter terminates NUL bytes in the output. So there was no problem with my code, if I run it outside PyScripter everything works fine. Now running Wing IDE and never looking back :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to ensure that two div always have same height in jQuery Mobile I am very new to jquery mobile framework, so kindly bear with me.I am developing a project where i need to show that data in tabular format.
So i have used below structure to create left and right column.
<div data-role="controlgroup" data-theme="d" class="ui-grid-m ui-corner-all ui-controlgroup ui-controlgroup-vertical">
<div id="left" class="ui-block-m">
<li>Moisture Sensitivity Level (MSL)</li>
</div>
<div id="right" class="ui-block-n">
<li> 3 </li>
</div>
</div>
But problem is when i have a large string in any of the one column and shorter string in other column, then height of column get's distorted.
So, my question is how can i ensure that both the div(Which i am using as columns having classes ui-block-m and ui-block-n) have same hieght.
Any suggestion is highly appreciated.
Thanks in advance!!.
How can i ensure that div with class ui-block-m and div with class ui-block-n
A: quick and dirty:
$(function(){
var $m = $('.ui-block-m');
var $n = $('.ui-block-n')
if($m.height() < $n.height()){
$m.css('height',$n.height());
}else if($m.height() > $n.height()){
$n.css('height',$m.height());
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Downgrade iPhone application from Apple Store How to Downgrade iPhone application from Apple Store.
I have my one application in Apple Store Live with version 1.4 for some reason i need to downgrade to 1.3 and remove 1.4.
How can i do like this from apple developer portal OR http://itunesconnect.apple.com/.
Cheers.
A: I don't think it is possible. Re-submit v1.3 of your app as v1.5.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Display custom method field in Admin Display Lets say I have some Django model that has a list of numbers as a field. I compute some statistics on the field using a custom method in the model. These models are displayed on the admin panel as an InlineAdminModel "embedded" in a parent object. Is there a way to display this custom method value in the admin panel when modifying the parent model, this would obviously only apply to ones that have already been created.
e.g. (truncated)
class ListModel(models.Model):
number_list = models.CommaSeparatedIntegerField(max_length = 20)
def sum(self):
return sum([int(s) for s in number_list.split(',')])
class ListModelAdmin(admin.TabularInline):
model = ListModel
list_display = ('sum') #works fine for displaying the ListModel
fields = ['number_list', 'sum'] #Obviously Doesn't work, but demonstrates
#what I want to accomplish. sum wouldn't be settable but displayed when
#number_list is updated
A: fields is for editable fields. Use readonly_fields instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to find sorted previous element in jquery .? <div id="con" >
<p class="bb">1</p>
<p class="aa">2</p>
<p class="aa">3</p>
<p class="bb">4</p> /*----- i want this reference */
<p class="aa">5</p>
<p class="aa">6</p>
<p id="last" class="aa">7</p>
<p class="aa">6</p>
<p class="aa">6</p>
</div>
i want to find the previous element among the siblings with sorted value.
here i want to find the 'p' has class 'aa' previous to #last
$("#last").prev('p.bb').text()
// empty string
$("#last").prev().text()
//will give 6
i want 4.. just the text of previous closest 'p.bb'
A: is it:
$("#last").siblings('p.bb:last').text()
that you are looking for? demo: http://jsbin.com/opaqen/edit
or is it like:
http://jsbin.com/opaqen/2/edit
or use .prevAll() to get all previous siblings from #last:
var lastB = $("#last").prevAll("p.bb:first");
lastB.css("background-color","#f00");
A: I'm unsure of what, precisely, you're looking for, but assuming you want to find the last p of class bb that comes before your #last element:
var $last = $('#last');
var lastIndex = $last.index('#con p');
for (i=lastIndex; i>=0; i--){
if ($('#con p').eq(i).hasClass('bb')){
$('#con p').eq(i).css('background-color','#f00');
alert($('#con p').eq(i).text());
break;
}
}
JS Fiddle demo.
While this is rather more verbose than @voigtan's answer it allows you to use any arbitrary element, and ensures that the .bb element found always occurs prior to that element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio, Filter on error list I 'm working with Visual Studio 10, my project is with monorail and I get a lot of error on my ".vm" files, those errors are not pertinent, and I don't want to see them anymore is there a way.
I tagged this ask with castle monorail, because I guess some users could have the same problem. But I'm sure it's a problem more general.
I get the same problem sometime with aspx or xslt visual studio check the file's validity ( with the own rules) and report the errors in the error list
A: New Answer:
Unfortunately, these errors are emitted by CVSI, and can be ignored - I agree they're a bit annoying. I've found that they go away if I re-open the solution. Not a great answer, but it's the only one I've found that works.
Previous Answer:
Are these errors ObjectDisposedExceptions?
What are your settings WRT exception handling in VS.NET? Go to Debug -> Exceptions in the menu. If there's a check in the "Thrown" column, then you need to open that up and then find System.ObjectDisposedException and then deselect it.
If you're looking to still break on deselected exceptions which are thrown elsewhere, you're out of luck, as this isn't currently supported by VS.NET.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selecting from a HSQLDB table with a BIT column I have a table with a column of data type bit.
> CREATE MEMORY TABLE Dummy (name varchar(10), flag bit)
> INSERT INTO Dummy VALUES ('foo', 1)
> INSERT INTO Dummy VALUES ('bar', 0)
> INSERT INTO Dummy VALUES ('foo2', true)
> INSERT INTO Dummy VALUES ('bar2', false)
> select name from Dummy where flag=1
foo2
> select name from Dummy where flag=true
foo2
Why don't I get foo? How are the 0 and 1 bits converted to booleans? It seems that both are false and I can't differentiate between them.
(By the way, this table is based on one I have in Sybase. The bits 1 and 0 are translated to true and false correctly.)
A: This works as you would expect with HSQLDB 2.2.5, returning two rows.
HSQLDB 2.x supports the BIT type directly and stores bit values. Values B'0' and B'1' can be stored. It translates TRUE and FALSE into 1 and 0 respectively. Integer values 0 and 1 are also translated into bits.
HSQLDB 1.8 translates BIT into BOOLEAN as soon as the column is defined. Conversion from integer may not always work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Fragment onStop() being called directly after onStart() - WHY? I'm having a strange problem with my app -
A have a Fragment Activity which contains a fragment - This fragment starts an AsyncTask onCreate() and cancels the AsyncTask onStop(). My problem arises because, although my Fragment stays running & isn't obscured it's onStop() is called almost directly after it's onCreate().
Does anyone know how to trace why this would be happening?
09-28 11:41:56.785: VERBOSE/SearchFragment1(924): onCreate()
09-28 11:41:56.796: VERBOSE/SearchFragment1(924): onStop()
EDIT
I've removed the code from the Fragment and I'm still absolutely baffled - The problem persists! I've added a few more lines of logging:
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onAttach()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onCreate()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onCreateView()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onActivityCreated()
09-28 14:09:00.242: VERBOSE/SearchResultsFragment1(1789): onStart()
09-28 14:09:00.246: VERBOSE/SearchResultsFragment1(1789): onStop()
09-28 14:09:00.246: VERBOSE/SearchResultsFragment1(1789): onStart()
09-28 14:09:00.246: VERBOSE/SearchResultsFragment1(1789): onResume()
The above behaviour is... baffling. The code used in the Activity looks like this:
if(savedInstanceState == null)
{
try {
FragmentTransaction transaction= getSupportFragmentManager().beginTransaction();
Fragment currentFragment= (Fragment)Class.forName(getIntent().getAction()).newInstance();
transaction.replace(R.id.singlePane, currentFragment);
transaction.commit();
} catch ...
This is the Fragment as it stands during debug:
private static final boolean LOGGING_ENABLED = true;
private static int global_creation_count = 0;
private int local_count = global_creation_count;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onAttach()");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
global_creation_count+=1;
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onCreate()");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onCreateView()");
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count,
"onActivityCreated()");
}
@Override
public void onStart() {
super.onStart();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onStart()");
}
@Override
public void onResume() {
super.onResume();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onResume()");
}
// Fragment is active
@Override
public void onPause() {
super.onPause();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onPause()");
}
@Override
public void onStop() {
super.onStop();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onStop()");
}
@Override
public void onDestroyView() {
super.onDestroyView();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onDestroyView()");
}
@Override
public void onDestroy() {
super.onDestroy();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onDestroy()");
}
@Override
public void onDetach() {
super.onDetach();
if(LOGGING_ENABLED) Log.v(this.getClass().getSimpleName() + local_count, "onDetach()");
}
EDIT2
From the code it seems that the onStop() is being called directly after onStart(). I've tried to see if it's being called at the same time as onStart() by adding a Thread.sleep(1000) in onCreateView(). The output is the same - which makes me beleive the onStop() is being called/caused directly from Fragment creation process.
EDIT3
Stacktrace when breaking on onStop():
I'm going to try and attach the source code and step through to discover where the problem is.
A: Still don't know what it was trying to do... I researched on where to get the source code for the class's involved in called onStop() and found that the source for android-support-v4.jar comes packaged along with the jar in the SDK.
After attaching this source though I soon found it was out of sync and that my android-support-v4.jar was vastly different to the one shipped with the current version of the SDK.
Replacing the jar with the one packaged with the SDK fixes the problem instantly and no onStop() is called after onStart(). Not sure what bug was causing this but the latest version seems to fix it quite handily.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How to convert a pdf file into CSV file? I want to convert a PDF file into a CSV file.
I am using iText library for this.
The program is working fine but the output is not in desired format.
All the data is coming in first line of the csv file. The output should be exactly same as pdf file(means with line breaks).
Please help.
Thanks in advance.
Document document = new Document();
document.open();
PdfReader reader = new PdfReader("C:\\Indiaops-projects\\PREMIUM_PAID_ACKNOWLEDGEMENT.pdf");
PdfDictionary dictionary = reader.getPageN(1);
AcroFields fileds = reader.getAcroFields();
PRIndirectReference reference = (PRIndirectReference)
dictionary.get(PdfName.CONTENTS);
PRStream stream = (PRStream) PdfReader.getPdfObject(reference);
byte[] bytes = PdfReader.getStreamBytes(stream);
PRTokeniser tokenizer = new PRTokeniser(bytes);
FileOutputStream fos=new FileOutputStream("C:\\Indiaops-projects\\pdf.csv");
StringBuffer buffer = new StringBuffer();
StringBuffer data = new StringBuffer();
int i=0;
while (tokenizer.nextToken()) {
if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) {
String value = tokenizer.getStringValue();
if("x-none".equals(value)){
String datastr =data.toString();
if(!"".equals(datastr)){
buffer.append("\""+datastr+"\",");
data = new StringBuffer();
}
}else{
data.append(value);
}
}
}
String test=buffer.toString();
StringReader stReader = new StringReader(test);
int t;
while((t=stReader.read())>0)
fos.write(t);
document.add(new Paragraph(".."));
document.close();
A: You need to introduce a line break '\n' in the buffer after each table row.
buffer.append("\n");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a way to test circular reference in JavaScript? I'm making a game, and I've come across a problem... When I try to save, JSON fails and reports that circular reference is being made somewhere. I don't think it actually is, I can't see it, so is there an algorithm or anything which could tell me where it is exactly (between which objects and stuff)? Also, is there a JSON alternative that can save circular reference? I'm running a node.js server, I saw this, but I can't get it to work (it's not made as a module i can require() in my code).
A: There is no good way to detect circularity in objects but it is possible though by walking the object tree and checking references. I baked up a node-walking function that tries to detect if a node has been already used as its parent
function isCircularObject(node, parents){
parents = parents || [];
if(!node || typeof node != "object"){
return false;
}
var keys = Object.keys(node), i, value;
parents.push(node); // add self to current path
for(i = keys.length-1; i>=0; i--){
value = node[keys[i]];
if(value && typeof value == "object"){
if(parents.indexOf(value)>=0){
// circularity detected!
return true;
}
// check child nodes
if(arguments.callee(value, parents)){
return true;
}
}
}
parents.pop(node);
return false;
}
And the usage would be isCircularObject(obj_value) where the function returns true if circularity exists and false if not.
// setup test object
var testObj = {
property_a:1,
property_b: {
porperty_c: 2
},
property_d: {
property_e: {
property_f: 3
}
}
}
console.log(isCircularObject(testObj)); // false
// add reference to another node in the same object
testObj.property_d.property_e.property_g = testObj.property_b;
console.log(isCircularObject(testObj)); // false
// add circular node
testObj.property_b.property_c = testObj.property_b;
console.log(isCircularObject(testObj)); // true
The key point being that an object value is equal with an other value only if it is the same object reference and not when it's another object (even if completely similar).
A: This is a small extension to Andris' answer that tells you where the first circular element is so you can deal with it accordingly.
function findCircularObject(node, parents, tree){
parents = parents || [];
tree = tree || [];
if (!node || typeof node != "object")
return false;
var keys = Object.keys(node), i, value;
parents.push(node); // add self to current path
for (i = keys.length - 1; i >= 0; i--){
value = node[keys[i]];
if (value && typeof value == "object") {
tree.push(keys[i]);
if (parents.indexOf(value) >= 0)
return true;
// check child nodes
if (arguments.callee(value, parents, tree))
return tree.join('.');
tree.pop();
}
}
parents.pop();
return false;
}
If you don't want a string, the tree array is unnecessary. Just change the original function to
return value;
for the circular object itself or
return parents.pop();
for its parent.
A: If you want to serialize a circular reference so you can save it, you need to make the reference "virtual" in that it can't be serialized as a circular reference, since that would cause serialization to serialize the same circle of objects forever (or at least until the runtime has run out of memory).
So instead of storing the circular reference itself, you just store a pointer to the object. The pointer will just be something like ref : '#path.to.object' that can be resolved when you deserialize so you point the reference back to the actual object. You just need to break the reference on serialization to be able to serialize it.
Discovering a circular reference in JavaScript can be done by recursively iterating through all objects (with for (x in y)), store x in an array and compare each x with the identity operator (a.k.a. strict comparison operator) === for each z in the temporary array. Whenever x === z equals true, replace the reference to x with a placeholder that will be serialized to the above mentioned ref.
An alternative to keeping an array over "visited" objects is to "taint" the objects you iterate through by setting a property on them, like in this very naïve example:
for (x in y) {
if (x.visited) {
continue;
}
x.visited = true;
}
A: I was thinking about what you're trying to accomplish based off the initial code from your other question. Why not do something like this.
Player = function()
{
this.UnitTypeXpower = 2
this.UnitTypeYpower = 7
}
UnitTypeXAdd = function(owner)
{
owner.UnitTypeXpower++;
}
That way you don't have to use a circular reference and it accomplishes the same thing.
A: Here is the code that I am using to detect circular references, it uses the technique that was suggested in the accepted answer by asbjornu, whereby each value is walked through and its reference is maintained in an array so that the next value can be compared with those previously walked.
function isCircular(obj, arr) {
"use strict";
var type = typeof obj,
propName,
//keys,
thisVal,
//iterKeys,
iterArr,
lastArr;
if (type !== "object" && type !== "function") {
return false;
}
if (Object.prototype.toString.call(arr) !== '[object Array]') {
//if (!Array.isArray(arr)) {
type = typeof arr; // jslint sake
if (!(type === "undefined" || arr === null)) {
throw new TypeError("Expected attribute to be an array");
}
arr = [];
}
arr.push(obj);
lastArr = arr.length - 1;
for (propName in obj) {
//keys = Object.keys(obj);
//propName = keys[iterKeys];
//for (iterKeys = keys.length - 1; iterKeys >= 0; iterKeys -= 1) {
thisVal = obj[propName];
//thisVal = obj[keys[iterKeys]];
type = typeof thisVal;
if (type === "object" || type === "function") {
for (iterArr = lastArr; iterArr >= 0; iterArr -= 1) {
if (thisVal === arr[iterArr]) {
return true;
}
}
// alternative to the above for loop
/*
if (arr.indexOf(obj[propName]) >= 0) {
return true;
}
*/
if (isCircular(thisVal, arr)) {
return true;
}
}
}
arr.pop();
return false;
}
This code is available on jsfiddle, where you can test it for yourself.
I have also run some performance tests on jsperf.
Array.indexOf was only introduced as of Javascript 1.6, see MDN page
Array.isArray was only introduced as of Javascript 1.8.5, see MDN page
Object.keys was only introduced as of Javascript 1.8.5, see MDN page
It is also worth noting that arguments.callee is deprecated and forbidden in strict mode in preference to using named functions
A: This thread already contains some good answers. If you are looking for a way to detect circular references or compare two values while dealing with circular references, you should check out this library:
https://www.npmjs.com/package/@enio.ai/data-ferret
It has the following methods:
hasCircularReference(someValue) // A predicate that returns true when it detects circular reference.
isIdentical(valueA, valueB) // By calling setConfig(options) opt-in circular reference support, this function does an equality check that does not fall into an infinite recursion trap.
Under the hood, it uses a similar algorithm to what @Asbjørn Ulsberg describes, but cleans after itself by removing all flags inserted.
However, the primary difference between the algorithms discussed here and the suggestion is that it can deal with any number of native/custom, iterable/non-iterable classes, meaning it supports circular detection and value comparison beyond the JSON specification and JavaScript's Object and Array.
All that's required for it to handle other classes is to call:
registerClassTypes()
registerIterableClass()
This library comes with 100% code coverage, so you can check out how to use the API by reading the .spec files if you visit the GitHub page.
Disclaimer: I wrote this library, but I do think there is a legitimate reason to mention it as it gives additional features that you might need when dealing with circular dependencies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: drupal db schema error In a module I'm building for Drupal 7 I'm trying to create a DB schema for the installing and uninstalling process. When enabling the module (and thus installing it) I get an error and my table is not created.
Can anybody see where it's going wrong?
<?php
/**
* Implementation of hook_schema().
*/
function wind_and_waves_schema() {
$schema['wind_and_waves'] = array(
'description' => 'Caches wind and waves data',
'fields' => array(
'id' => array(
'description' => 'The unique identifier for this item.',
'type' => 'serial',
'disp-width' => '11',
'unsigned' => TRUE,
),
'creation' => array(
'description' => 'Moment the data has been loaded',
'mysql_type' => 'datetime',
'disp-width' => '11',
),
'load_time' => array(
'description' => 'Moment the wind data has been loaded by rijkswaterstaat',
'mysql_type' => 'datetime',
'disp-width' => '11',
),
'hoek_wind_snelheid' => array(
'description' => 'Windsnelheid op hoek',
'type' => 'varchar',
'disp-width' => '11',
),
'hoek_wind_stoot' => array(
'description' => 'Windstoot op hoek',
'type' => 'varchar',
'disp-width' => '11',
),
'hoek_wind_richting' => array(
'description' => 'Windrichting op hoek',
'type' => 'varchar',
'disp-width' => '11',
),
'hoek_golf_hoogte' => array(
'description' => 'golfhoogte op hoek',
'type' => 'varchar',
'disp-width' => '11',
),
'ijmuiden_wind_snelheid' => array(
'description' => 'Windsnelheid op ijmuiden',
'type' => 'varchar',
'disp-width' => '11',
),
'ijmuiden_wind_stoot' => array(
'description' => 'Windstoot op ijmuiden',
'type' => 'varchar',
'disp-width' => '11',
),
'ijmuiden_wind_richting' => array(
'description' => 'Windrichting op ijmuiden',
'type' => 'varchar',
'disp-width' => '11',
),
'ijmuiden_golf_hoogte' => array(
'description' => 'golfhoogte op ijmuiden',
'type' => 'varchar',
'disp-width' => '11',
),
'golf_periode' => array(
'description' => 'golfperiode',
'type' => 'varchar',
'disp-width' => '11',
),
'watertemp' => array(
'description' => 'watertemperatuur',
'type' => 'varchar',
'disp-width' => '11',
),
'luchttemp' => array(
'description' => 'luchttemperatuur',
'type' => 'varchar',
'disp-width' => '11',
),
),
'primary key' => array('id'),
);
return $schema;
}
?>
The error I get:
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL COMMENT 'Windsnelheid op hoek', hoek_wind_stoot VARCHAR DEFAULT ' at line 4: CREATE TABLE {wind_and_waves} ( id INT unsigned auto_increment DEFAULT NULL COMMENT 'The unique identifier for this item.', creation DATETIME DEFAULT NULL COMMENT 'Moment the data has been loaded', hoek_wind_snelheid VARCHAR DEFAULT NULL COMMENT 'Windsnelheid op hoek', hoek_wind_stoot VARCHAR DEFAULT NULL COMMENT 'Windstoot op hoek', hoek_wind_richting VARCHAR DEFAULT NULL COMMENT 'Windrichting op hoek', hoek_golf_hoogte VARCHAR DEFAULT NULL COMMENT 'golfhoogte op hoek', ijmuiden_wind_snelheid VARCHAR DEFAULT NULL COMMENT 'Windsnelheid op ijmuiden', ijmuiden_wind_stoot VARCHAR DEFAULT NULL COMMENT 'Windstoot op ijmuiden', ijmuiden_wind_richting VARCHAR DEFAULT NULL COMMENT 'Windrichting op ijmuiden', ijmuiden_golf_hoogte VARCHAR DEFAULT NULL COMMENT 'golfhoogte op ijmuiden', golf_periode VARCHAR DEFAULT NULL COMMENT 'golfperiode', watertemp VARCHAR DEFAULT NULL COMMENT 'watertemperatuur', luchttemp VARCHAR DEFAULT NULL COMMENT 'luchttemperatuur', PRIMARY KEY (id) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'Caches wind and waves data'; Array ( ) in db_create_table() (line 2657 of /home/sitede01/domains/sitedezign.net/public_html/includes/database/database.inc).
A: All columns of type varchar need a length property, e.g.:
'luchttemp' => array(
'description' => 'luchttemperatuur',
'type' => 'varchar',
'length' => 11
)
disp-width is only valid for non-varchar type columns
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to avoid a shift reduce conflict in a LALR grammar for parsing nested lists? I would like to create a LALR grammar to parse nested lists, but I get always a shift/reduce conflict.
I have the list1 which is a list of type1 items and list2:
<list1> ::= <type1> | <type1> <list1> ;
<type1> ::= A | B | <list2> ;
And I have a list2 which is a list of type2 items:
<list2> ::= <type2> | <type2> <list2> ;
<type2> ::= X | Y ;
This grammar produces a shift/reduce error. How can I avoid it?
This is the concrete Bigloo source:
(lalr-grammar
(comment
new-line
text-chunk
white-space)
(input
(() '())
((node-list) node-list))
(node-list
((node) (cons node '()))
((node node-list) (cons node node-list)))
(node
((comment) (cons 'comment comment))
((new-line) (cons 'new-line new-line))
((text) (cons 'text text))
((white-space) (cons 'white-space white-space)))
(text
((text-chunk) (cons 'text text-chunk))
((text-chunk text) (cons 'text (string-append text-chunk text)))))
The terminals are: comment, new-line, text-chunk and white-space.
The non terminals are: input, node-list, node and text.
Bigloo complains about the reduce rule for text to text-chunk:
*** WARNING:bigloo:lalr-grammar
** Shift/Reduce conflict:
- shift to state 2
- reduce rule (text --> text-chunk)
on token `text-chunk'
But I do not think that this is a Bigloo problem. It looks like a grammar problem.
A: The grammar is in fact ambiguous, because a sequence of type2 instances can be accumulated on list2 level, but it can also be seen as a sequence of type1 instances.
E.g. this input
X X
can be parsed as
list1(
type1(
list2(
type2(
X)
list2(
type2(
X)))))
but also as
list1(
type1(
list2(
type2(
X)))
list1(
type1(
list2(
type2(
X)))))
What about introducing a delimiter on list1 level? This would solve the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to use Mysql database data in javascript widget I'm creating a widget for users to place on their blogs to direct traffic to my coupon code site. I want the widget to access the database and output the 5 top coupons of the day. Here is what I will them place on their site:
<script src="http://example.com/widget/script.js" type="text/javascript"></script>
<div id="example-widget-container"></div>
Now the script.js file looks like:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://www.mydomain.com/widget_data.php";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
The problem I'm having is how do I return a json array to the js file, and how do I loop through it to output a unordered list with each coupon being its own list item?
Any help is greatly appreciated!!!!
A: Use Ajax,
send a HttpRequest from the widget to the web server,
send back from the server a json response, for example in PHP would be something like this
...
//access the database
$sql = "SELECT * FROM coupons LIMIT 5";
while ($row = mysql_fetch_assoc($sql)) {
$coupons[] = $row;
}
//return json object
echo json_encode($coupons);
...
Once the js widget has received the json string, you can convert it to a js object to do what you need to
JSON.parse(strJSON)
jQuery ajax request example:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL to query drupal nodes with multiple taxonomies Good morning all.
I've read some of the suggested question before posting this but seems like no one has my same issue (probably and inidicator of how bad I am in Drupal and coding in general)
I need to write a query that returns all the nodes with TWO SPECIFIC taxonomies associated to it (of which I know the IDs), but it seems I don't know the right syntax cause I just manage to get it work with ONE term id.
Here's what I have so far (and works)
SELECT * FROM node
INNER JOIN term_node AS tn ON node.vid = tn.vid
LEFT JOIN content_type_extra_content AS xc ON node.vid = xc.vid
WHERE tn.tid IN (SELECT th.tid FROM term_hierarchy AS th WHERE th.tid = '146')
That '146' is the id of the first taxonomy term I need to check (call it "shoes")
Now I have to check that the node has also the taxonomy id '223' (call it "season")
I've tried different solutions with no avail.
I'm pretty sure the solution is under my nose but at the moment I can't wrap my head around it.
Please note that the taxonomies are in different vocaboularies and they are at level-0
Thanks in advance for any help
A: If I understand you correctly, you want the nodes which have 2 specific terms (shoes and season), then try something like this:
SELECT * FROM node
INNER JOIN term_node AS tn ON node.vid = tn.vid
LEFT JOIN content_type_extra_content AS xc ON node.vid = xc.vid
WHERE tn.tid IN ('146','223')
GROUP BY node.vid
HAVING count(*) = 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android login with hashed username and password I'm working on a project where user have to login first in application to use it. And my little problem is that when user enter his username and password, than I have to hash them and send to the server instead of username and password entered by the user. So for now I'm doing something like this :
EditText txtUserName = (EditText) findViewById (R.id.username_login_input);
EditText txtPassword = (EditText) findViewById (R.id.password_login_input);
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.shalqlqlq.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username_hash", hashUser(txtUserName.getText().toString(),txtPassword.getText().toString())));
postParameters.add(new BasicNameValuePair("password_hash", hashPass(txtUserName.getText().toString(),txtPassword.getText().toString())));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
byte[] buffer = new byte[1024];
buffer = EntityUtils.toString(response.getEntity()).getBytes();
public String hashUser(String username, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
String hashUser = SHA1.Sha1Hash(username);
String hashPass = SHA1.Sha1Hash(password);
String luser = hashPass+hashUser;
String lastUser = SHA1.Sha1Hash(luser);
return lastUser;
}
public String hashPass(String username, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
String hashUser = SHA1.Sha1Hash(username);
String hashPass = SHA1.Sha1Hash(password);
String lpass = hashPass+hashUser;
String lastPass = SHA1.Sha1Hash(lpass);
return lastPass;
}
And it still tells me that username and password are incorrect. I'm pretty sure that hashing is correct because I've already tried it. So can anybody help me to find out where is my mistake ?
A: For a start, your hashed username and hashed password are identical:
public String hashUser(String username, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
String hashUser = SHA1.Sha1Hash(username);
String hashPass = SHA1.Sha1Hash(password);
String luser = hashPass+hashUser; // <-- Hashed pass + user
String lastUser = SHA1.Sha1Hash(luser); // <-- Hashed a second time
return lastUser;
}
public String hashPass(String username, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
String hashUser = SHA1.Sha1Hash(username);
String hashPass = SHA1.Sha1Hash(password);
String lpass = hashPass+hashUser; // <-- Hashed pass + user
String lastPass = SHA1.Sha1Hash(lpass); // <-- Hashed a second time
return lastPass;
}
Unless the server stores usernames and passwords each as a hashed hash of password and username, then I'm guessing this is where your problem is.
Why not just use something like:
postParameters.add(new BasicNameValuePair("username_hash", SHA1.Sha1Hash(txtUserName.getText().toString())));
postParameters.add(new BasicNameValuePair("password_hash", SHA1.Sha1Hash(txtPassword.getText().toString())));
A: If everything is ok, I guess maybe the problem is in getting the username and password from edittext.Try to put
postParameters.add(new BasicNameValuePair("username_hash", hashUser(txtUserName.getText().toString(),txtPassword.getText().toString())));
postParameters.add(new BasicNameValuePair("password_hash", hashPass(txtUserName.getText().toString(),txtPassword.getText().toString())));
in some kind of event. I guess you have a button Login..so you set these params on onClick method and I think it will work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to check whether perl cgi request originates from localhost I would like to expose a service written in Perl to localhost HTTP requests. I do not want to modify Apache configuration. How to check whether a Perl CGI HTTP request originates from localhost?
I want for this check to succeed even if this call is made through a virtual host eg. https://www.myserivce.com/hidden/service.pl given that the call is made from inside of www.myserivce.com.
A: REMOTE_ADDR, but that's a dumb way to do it because you put the authentication logic in the application.
Instead, bind a stand-alone Web server to local interface only, thus the operating system's IP/networking stack guarantees that no request from outside can reach the server.
A: I think that if you put in /etc/hosts file an entry with myservice.com and ip 127.0.0.1 then all the requests from localhost to your site will have the REMOTE_ADDR set to 127.0.0.1 .
I am afraid that this is the only way to do it, unless you are making requests to 127.0.0.1/hidden/service.pl instead of myservice.com/hidden/service.pl
A: I have used the following code:
my $server_addr = inet_ntoa(scalar gethostbyname(hostname() || 'localhost'));
my $call_addr = $query->remote_addr();
die unless $call_addr eq "127.0.0.1" || $call_addr eq $server_addr;
I do not think it covers all cases, but seems to work with my setup. If anybody knows a generic solution then please submit it here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Brisk for small files I am a newbie to Cassandra and Hadoop. While looking for integration of the two products i came across Brisk. From the description i understand that Brisk replaces HDFS for CassandraFS. So this replacement is a solution for small file problem of Hadoop? If so what about large files ? Currently i need to implement a resource storage containing both large binary data files with their meta data and small files such as images.
A: It's both, really (although I think Brisk has now been rolled into a commercial product, DataStax Enterprise, and isn't being actively developed in its own right).
Brisk includes CassandraFS (cfs) which is a drop-in replacement for HDFS, so supports large files. Under the hood, these are broken into chunks and stored in Cassandra rows/columns.
For small files, you can store the data in native Cassandra rows instead of CassandraFS, and run Hadoop jobs over the rows instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sencha Touch FormPanel With Store I have a store as follows.
var eventsStore = new Ext.data.Store({
model: 'Event',
sorters: [{
property: 'OccurringOn',
direction: 'DESC'
}],
proxy: {
type: 'ajax',
url: BaseURL + 'Events.php',
api: {
read: BaseURL + 'Events.php',
create: BaseURL + 'Events.php'
},
reader: {
type: 'xml',
root: 'Events',
record: 'Event'
},
writer: {
type: 'xml',
writeAllFields: false,
root: 'Events',
record: 'Event'
}
},
getGroupString: function(record) {
if (record && record.data.OccurringOn) {
console.log(record.get('OccurringOn'));
return record.get('OccurringOn').toDateString();
}
else {
return '';
}
}
});
I also have a List view which gets all Events fine. I have a form which allows user to add new event and I have FormPanel for it. The FormPanel has Toolbar which has Save button which when clicked will do following.
var eventCard = It's a card
var newEventCard = eventCard.items.items[1];
var currentEvent = newEventCard.getRecord();
newEventCard.updateRecord(currentEvent);
var errors = currentEvent.validate();
// here I check errors and prompt user about them
var eventList = eventCard.items.items[0].items.items[0];
var eventStore = eventList.getStore();
eventStore.add(currentEvent);
eventStore.sync();
eventStore.sort( [ { property: 'OccurringOn', direction: 'DESC' } ] );
eventList.refresh();
The above code adds two empty rows to the MySQL database and copies the event list view items with 3 empty new items. Why this is the behavior and what I am missing?
If you can tell me what parameters are sent as POST to the Events.php when I sync that would much appreciated.
A: It was my fault I figured out. I was echo'ing when there was POST request to the service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the best practices to avoid XSS and SQL Injections attacks (platform agnostics)? I wish there was a do/don't list (such as input sanitation, etc.) which when respected, such attacks are nearly impossible to succeed.
A: Take a look at the OWASP Top Ten Project: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
A: Aha, you'll be wanting the XSS (Cross Site Scripting) Prevention Cheat Sheet and the SQL Injection Prevention Cheat Sheet from OWASP, then.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to open and edit an XML file from res/xml local project folder I can open the xml files from my local folder of an android project in Eclipse to read the values:
Resources res = activity.getResources();
XmlResourceParser xpp = res.getXml(R.xml.tittes);
But how could I open a local xml file to edit the file and save it after?
Thanks for the replies!.,
I mean with a local file, a XML file I need to read and edit for data storage purposes. I've decided to place the file in the asset folder and I can open it easily for read::
*DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
InputStream iS = this.getAssets().open("myFile.xml");
Document doc = docBuilder.parse(iS);*
...,, but I don`t obtain, after many attemps, the way to save the file to edit: My last attempt is:
*TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
OutputStream f0;
byte buf[] = xmlString.getBytes();
**f0 = new FileOutputStream("/assets/wines.xml");**
//f0 = new FileOutputStream("file:///assets/wines.xml");
for(int i=0;i<buf .length;i++) {
f0.write(buf[i]);
}
f0.close();
buf = null;*
and the failed result is File not found!!!,. I come from C# projects,.and I couldn`t imagine that save a modified file was so dificult,.,
any ideas?!¿!? thanks again!!
A:
but anyone know how could I open a local xml file to edit the file and save it after.
If by "local xml file" you mean a file in getFilesDir(), use DOM, or SAX, or the XmlPullParser.
If by "local xml file" you mean a resource, and you want to modify that resource, that is not possible at runtime.
A: There is no way to edit xml resources in the res folder in your program.
You can try another way, such as saving your resources to SharedPreference or SQLite at the first time your app starts, and later on you just edit and use your own copy.
This is useful when you use the resource to fill some component, but not good for layouts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mysql between two dates index I'm selecting Data from a mysql database table.
When i'm searching a specific date, my index is wiorking fine.
When I'm searching data between two dates the index isn't working and the query takes to long.
Has anybody an idea how can i improve the query or the index?
Query A:
EXPLAIN SELECT * FROM sal_import
WHERE dateStats>="2011-07-28" AND dateStats<="2011-07-30" GROUP BY f_shop
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE i range dateStats dateStats 3 (NULL) 7896 Using where; Using temporary; Using filesort
Query B:
EXPLAIN SELECT * FROM sal_import i
WHERE dateStats="2011-07-30" GROUP BY f_shop
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE i ref dateStats dateStats 3 const 2182 Using where
This is the index of the table:
ALTER TABLE sal_import ADD INDEX(dateStats,f_shop);
Thank you very much.
A: Try this:
SELECT * FROM sal_import WHERE dateStats BETWEEN '2011-07-28' AND '2011-07-30'
Also see http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
A: The reason is that the date index is non-clustered and as such the data is not sequentially ordered by that key on disk. Your table has a small number of records, so the query optimiser has decided it is quicker to do a full table scan, rather than use the secondary index and piece the records together.
A table can only have one clustered index and this is usually the primary key. A date column is generally a valid and sensible column on which to put the clustered index, but it may not be the best use of it; it really depends on how that table is used.
http://msdn.microsoft.com/en-us/library/aa933131(v=sql.80).aspx
Unfortunately in MySQL a clustered index must be on a unique column and you cannot define a clustered index on a column (apparently); the database chooses that index for you by default. Given this you might not be in luck on this one.
http://dev.mysql.com/doc/refman/5.0/en/innodb-index-types.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Set Session in Asp page using Asp.net I have a Login Page which is created in asp.net now when i successfully logins into my application i need to transfer session related information from my asp.net page to my asp page so how to set my session information in asp using asp.net.
Regards,
A: How to share session state between classic asp and asp.net
A: I see you mentioned wanting to use State Server. You could try NSession it allows sharing session state between Classic ASP and ASP.Net using State server. Pretty easy to setup just configure App to use State Server for session and register a couple of dll files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ASP:Table adding rows programmatically I am trying to add rows programmatically to a server side table in asp.net. I have a button, and within the click event handler I have:
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.Controls.Add(new TextBox());
row.Cells.Add(cell);
myServersideTable.Rows.AddAt(myServersideTable.Rows.Count - 1, row);
All good, the code works the first time the button is clicked and a new row is added.
However, all subsequent button clicks don't add a new row. No error is thrown.
Why this might be happening?
A: You can't do this because of the stateless nature of Http protocol. For more information please read ASP.NET page life cycle from the MSDN.
A: You are adding a row dynamically, so when you postback you will have to again recreate the controls.
In this case you are using a Table and the row is added on first button click, so when you click again you will have to recreate the previous row again and one more for the current click
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JavaScript language query around Backbone.js _bindRoutes method I've been looking through the Backbone.js source, and I'm a little confused as to how the _bindRoutes method in Backbone.Router actually works.
When you create a set of routes, the ordering is of course very important:
routes: {
"blah", "checkFirst",
"blah2", "checkSecond",
"*anything", "ifNothingElseMatches"
}
However the code in _bindRoutes, seems to pull out the specified routes simply with a for in loop over the routes object.
This would potentially pull the results out in an un-ordered fashion ("There is no guarantee that for...in will return the indexes in any particular order" - MDN).
Am I missing something? As I can't see how you can trust the route priority order if the above is all true.
A: There's no guarantee in the language specification (and that isn't changing with ES5 - "The mechanics and order of enumerating the properties ... is not specified"), but the de facto standard is for for..in iteration to give you properties in definition/insertion order.
Since the behaviour isn't specified, implementations are technically free to do what they want, giving you bug reports like Chromium Issue 164 when one of them differs from the others, in this case because Chrome treats numeric properties differently.
A: Why do you think ordering is important? The order in the routes object is not important. As you mentioned, there is no order in litteral objects.
If you look at the Backbone doc for Routers (http://documentcloud.github.com/backbone/#Router) you'll see that the routes is association of urls and functions.
You'll want to define actions that are triggered when certain URL fragments are matched, and provide a routes hash that pairs routes to actions.
In your example, when I'll go to www.your_site.com/your_page#blah2 it will execute the checkSecond function in the Backbone Router.
So, as there is no order in the routes, you have to guide the user through routing.
You can redirect user by using the navigate function :
router.navigate("blah", true)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: database connection time expired issue I have a server machine and four client machine for database connectivity.
I installed sqlexpress 2008 in server and one machine and all remaining systems, they have connected the database through the EMS (SQL Manager 2008 for SQL Server ).
The issue is that when I connect the database from that m/c which has sqlexpress 2008 then it gives "Timeout Expired"
But all remaining systems connect to server easily.
Why it gives an error for that particular system.
I didn't get any proper solution for this issue.
A: It depends on what do you use to connect: Windows integrated security or SQL Server security?
And also, make sure you are connecting to the right instance of SQL Server on server machine (default instance doesn't need to specify the instance name, while for named instances you need to connect to \\
Hope this helps,
Bye
cghersi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Profile Post Code Search Finder Nearest Carrer I have a web site that is Facebook for the old to find careers around the UK however the owner has asked for postcode partial search to be in place and that and a distance selection so they can search for careers in say 5 10 15 miles distances from the original postcode. I store postcode and long and latitude into the profile table.
userid int(11) Yes NULL
profile_pic text Yes NULL
qualification text Yes NULL
education int(11) Yes NULL
patient int(11) Yes NULL
carer int(11) Yes NULL
telephone varchar(50) Yes NULL
mobile varchar(50) Yes NULL
gender int(11) Yes NULL
profile_areas int(11) Yes NULL
type int(11) Yes NULL
care_cats int(11) No
lng varchar(20) No
lat varchar(20) No
My question is how would i create such a search the im reversing looking up long and lat via a third party search i need to give the distance avalble and show the profiles that match the distance
A: Here's the SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
From: http://code.google.com/apis/maps/articles/phpsqlsearch_v3.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to reload page using javascript
Possible Duplicate:
how to refresh a page using javascript?
how to reload (refresh) the web-page through java script only once not repeatedly. I want to refresh the page once at a time.
A: If you want to refresh (reload) the page you can use location.reload(true).
This link may help you to explore it further more Javascript Refresh Page
A: using history.go(0) refreshes the current page
A: location.reload( true );
The parameter tells the browser, to always reload the current page from the server. If that is skipped or explicitly set to false, the browser may load the page from its cache.
A: Options :-
window.location.reload()
window.location.href=window.location.href
A: It will help you
window.location.reload(true);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to get latitude and longitude from address in C# I want to get the lat and long based on a address. I have already set it so it captures the users location which brings it up as Manchester.
i want to write an if statement..................;
if there is an address
{
// set lat/long from address
}
here is the full coding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GeoCoding.Google;
using GeoCoding;
using System.Web.Configuration;
namespace MVCFacebookTestApp.Models
{
public class Home
{
//public string UserID { get; set; }
public string FBID { get; set; }
public string AccessToken { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string Gender { get; set; }
public DateTime? DOB { get; set; }
public string Email { get; set; }
public DateTime DateLiked { get; set; }
public string ImageURL { get; set; }
//public string TestString { get; set; }
//public string TestString2 { get; set; }
public bool IsLiked { get; set; }
//public string ImgUrl { get; set; }
private Home() {
//Console.WriteLine(GoogleAPIKey);
}
public static Home NotLiked()
{
Home h = new Home();
h.IsLiked = false;
return h;
}
public static Home Liked()
{
Home h = new Home();
h.IsLiked = true;
return h;
}
public void AddUser(string facebookID, string accessToken, string fName, string lName, DateTime dob, string email, DateTime dateLiked, string gender, string imageURL, string locationID, string locationValue)
{
Entities context = new Entities();
//DBNameDataContext myDB = new DBNameDataContext();
IEnumerable<User> users = context.Users.Where(u => u.FacebookID == facebookID);
if (users.Count() == 0)
{
//UserID = userID;
FBID = facebookID;
AccessToken = accessToken;
FName = fName;
LName = lName;
DOB = dob;
Email = email;
DateLiked = dateLiked;
Gender = gender;
ImageURL = imageURL;
User newUser = new User();
//newUser.UserID = 1;
newUser.FacebookID = facebookID;
newUser.AccessToken = accessToken;
newUser.FName = fName;
newUser.LName = lName;
newUser.Gender = gender;
newUser.DOB = DOB;
newUser.Email = email;
newUser.DateLiked = dateLiked;
newUser.ImageURL = imageURL;
context.Users.AddObject(newUser);
context.SaveChanges();
}
else if (users.Count() == 1)
{
User user0 = users.First();
if (user0.Gender != gender)
{
user0.Gender = gender;
}
if (user0.FName != fName)
{
user0.FName = fName;
}
if (user0.LName != lName)
{
user0.LName = lName;
}
if (user0.DOB != dob)
{
user0.DOB = dob;
}
if (user0.Email != email)
{
user0.Email = email;
}
if (user0.DateLiked != dateLiked)
{
user0.DateLiked = dateLiked;
}
if (user0.ImageURL != imageURL)
{
user0.ImageURL = imageURL;
}
context.SaveChanges();
FBID = user0.FacebookID;
AccessToken = user0.AccessToken;
FName = user0.FName;
LName = user0.LName;
DOB = user0.DOB;
Email = user0.Email;
DateLiked = user0.DateLiked;
Gender = user0.Gender;
ImageURL = user0.ImageURL;
}
else
{
throw new ApplicationException();
}
//LOCATION...
//LocationID = locationID;
//FBID = facebookID;
//Latitude = latitude;
//Langitude = langitude;
//Description = description;
//IEnumerable<User> users = context.Users.Where(u => u.FacebookID == facebookID);
IEnumerable<Location> locations = context.Locations.Where(l => l.FacebookID == facebookID);
{
Location newLocation = new Location();
newLocation.FacebookID = locationID;
newLocation.Latitude = "";
newLocation.Langitude = "";
newLocation.Description = locationValue;
IGeoCoder geoCoder = new GoogleGeoCoder(GoogleAPIKey);
Address[] addresses = geoCoder.GeoCode(locationValue);
context.Locations.AddObject(newLocation);
context.SaveChanges();
}
if (Address= true)
{
langtitude = ;;
}
}
public string GoogleAPIKey
{
get
{
return WebConfigurationManager.AppSettings["GoogleAPIKey"];
}
}
}
}
A: Your question isn't really clear, but I guess you want something like:
IGeoCoder geoCoder = new GoogleGeoCoder(GoogleAPIKey);
Address[] addresses = geoCoder.GeoCode(locationValue);
// I believe the API never returns a null reference...
if (addresses.Length != 0)
{
// Let's assume the first one is good enough
Address address = addresses[0];
Location location = address.Location;
// Use location.Latitude and location.Longitude
}
Note that for testability it would be a good idea to inject the IGeoCoder instead of creating it within your class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remaining item positions in ListView is incorrect after deleting items I'm having trouble with getting the correct items after deleting an item in my ListView.
The position should fit to the index of the item in an ArrayList, but after deleting an item in the ListView, the positions are incorrect (and might even give an indexoutofbounds exception.
I bet it has something to do with the Views position, but I just can't find the error.
I have this ListActivity class with an inner BaseAdapter class:
public class MSMobilMyStocksActivity extends ListActivity {
static MyStocksCtr myStocksCtr;
static ListView listview;
static EfficientAdapter adap;
boolean downloadSuccess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystockslist);
mContext = this;
listview = getListView();
myStocksCtr = MyStocksCtr.getInstance(mContext);
adap = new EfficientAdapter(this);
setListAdapter(adap);
if (isOnline())
new InsertDataTask().execute();
else {
startTimer();
Toast.makeText(mContext, "Du har ingen internetforbindelse", 1000)
.show();
}
}
public static boolean updateData() {
return myStocksCtr.downloadJson();
}
private class InsertDataTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
try {
listview.setEnabled(false);
} catch (Exception e) {
}
}
// can use UI thread here
@Override
protected void onPostExecute(final Void unused) {
if (isOnline()) {
if (downloadSuccess) {
try {
if (myStocksCtr.getArray().size() == 0) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else if (myStocksCtr.getArray().size() == 1
&& myStocksCtr.getArray().get(0)
.getString("FH_FULLNAME").equals("-")) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else {
adap.notifyDataSetChanged();
}
} catch (JSONException e) {
Toast.makeText(mContext, "JSONException", 2000).show();
}
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
startTimer();
try {
listview.setEnabled(true);
} catch (Exception e) {
}
}
@Override
protected Void doInBackground(Void... arg0) {
downloadSuccess = false;
if (isOnline()) {
try {
if (updateData())
downloadSuccess = true;
} catch (Exception e) {
Toast.makeText(mContext, "Fejl under download af data",
2000).show();
downloadSuccess = false;
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
return null;
}
}
}
public static class EfficientAdapter extends BaseAdapter implements
Filterable {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mylistitem, null);
holder = new ViewHolder();
holder.stockName = (TextView) convertView
.findViewById(R.id.stockName1);
holder.stockPrice = (TextView) convertView
.findViewById(R.id.stockValue1);
holder.stockChange = (TextView) convertView
.findViewById(R.id.stockChange1);
holder.stockPctChange = (TextView) convertView
.findViewById(R.id.stockPctChange1);
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
Intent i = new Intent(mContext, MSStockDetailActivity.class);
Bundle b = new Bundle();
b.putInt("position", position); //Your id
b.putBoolean("isMyStocks", true);
i.putExtras(b); //Put your id to your next Intent
mContext.startActivity(i);
} catch (Exception e) {
Toast.makeText(mContext, "OnClick error ", 2000)
.show();
}
}
});
convertView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View arg0) {
final CharSequence[] items = {
"See stock details",
"Delete the stock \"" + holder.stockName.getText()
+ "\" from the list", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setTitle("Configure list");
builder.setItems(items,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int item) {
if (item == 1) {
myStocksCtr.removeStock(holder.ric);
adap.notifyDataSetChanged();
} else if (item == 2) {
}
Toast.makeText(mContext, items[item],
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_FULLNAME");
holder.stockName.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_RIC");
holder.ric = result;
} catch (JSONException e) {
e.printStackTrace();
}
// + String.valueOf(position));
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_PRC");
if (String.valueOf(result.charAt(result.length() - 2)).equals(
".")) {
result += "0";
}
;
holder.stockPrice.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
holder.position = position;
return convertView;
}
static class ViewHolder {
String ric;
TextView stockName;
TextView stockPrice;
TextView stockPctChange;
TextView stockChange;
int position;
}
@Override
public Filter getFilter() {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public int getCount() {
return myStocksCtr.getArray().size();
}
@Override
public JSONObject getItem(int position) {
return myStocksCtr.getArray().get(position);
}
}
This is some of the things in my stocks controller (where the array is):
public class MyStocksCtr {
private static MyStocksCtr INSTANCE = null;
ArrayList<String> myStocksArray;
JSONCtr jsonCtr;
static Context mContext;
boolean isRunning = false;
ArrayList<JSONObject> myArray;
MyStocksCtr(Context mContext) {
this.mContext = mContext;
jsonCtr = new JSONCtr(mContext);
myStocksArray = new ArrayList<String>();
myArray = new ArrayList<JSONObject>();
}
}
public static MyStocksCtr getInstance(Context context){
mContext = context;
if(INSTANCE == null) {
INSTANCE = new MyStocksCtr(mContext);
}
return INSTANCE;
}
public ArrayList<JSONObject> getArray() {
return myArray;
}
public boolean downloadJson() {
if (!myStocksArray.isEmpty()) {
String myStocksString = "";
for (String s : myStocksArray)
myStocksString += (s + "%2C");
myStocksString = myStocksString.substring(0,
myStocksString.length() - 3);
jsonCtr.getJSON(preStocksUrl + myStocksString + postStocksUrl);
myArray.clear();
myArray.addAll(jsonCtr.getArray());
return true;
} else {
return false;
}
}
public void removeStock(String newStock) {
JSONObject toRemove = null;
for (JSONObject obj : myArray) {
try {
if (obj.getString("FH_RIC").equals(newStock)) {
toRemove = obj;
}
} catch (JSONException e) {
Toast.makeText(mContext, "Kunne ikke fjerne objekt", 1000)
.show();
}
}
if (toRemove != null){
myStocksArray.remove(newStock);
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
saveMyStocks();
}
}
}
In my jsonCtr I remove and get the array:
public ArrayList<JSONObject> getArray() {
return rics1;
}
public void removeRic(Object o){
rics1.remove(o);
}
When i have removed an object from the list, the list is updated, so the item is no longer there. But the positions of the views are all messed up, and some of them are outofbounds.
I'm guessing it has something to do with the position in GetView is final, but I'm not sure? And if that is the problem, how do I correct it?
A: Hmm, I didn't looked at every detail of your code but i think you're missing to call myAdaper.notifyDataSetChanged() after changing your array.
Edit
That*s really tough to look trough because it's a lot of code you post here. So here is what I got. I can't see what's going on in here (on stock remove) but there must be something wrong I think:
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
Please don't post the whole code of that too, try to reduce it to the actual problem. I wont check the whole code again...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the least memory demanding methods to do these steps? I have posted a question yesterday, and got wonderful response from the experts. However, I am facing another question now, I found the jobs cannot be done in my real data as my starting file (df1) are too large. I wonder if there are faster method to do the same job without using adply or for loop?
My original questions is listed as below:
Step 1: I have a simplified dataframe like this:
df1 = data.frame (B=c(1,0,1), C=c(1,1,0)
, D=c(1,0,1), E=c(1,1,0), F=c(0,0,1)
, G=c(0,1,0), H=c(0,0,1), I=c(0,1,0))
B C D E F G H I
1 1 1 1 1 0 0 0 0
2 0 1 0 1 0 1 0 1
3 1 0 1 0 1 0 1 0
Step 2: I want to do row wise subtraction, i.e. (row1 - row2), (row1 - row3) and (row2 - row3)
row1-row2 1 0 1 0 0 -1 0 -1
row1-row3 0 1 0 1 -1 0 -1 0
row2-row3 -1 1 -1 1 -1 1 -1 1
step 3: replace all -1 to 0
row1-row2 1 0 1 0 0 0 0 0
row1-row3 0 1 0 1 0 0 0 0
row2-row3 0 1 0 1 0 1 0 1
Could you mind to teach me how to do so in a less memory-demanding approach?
A: The fastest way I know to do step 2 is to use indices into df1 for the various pairwise comparisons you want to do. The combn() function can be used to generate the set of row-by-row comparisons required. (Using this will be the rate limiting step for big data sets.)
For the combinations of row-by-rows operations we want to form:
> cmb <- combn(as.numeric(rownames(df1)), 2)
> cmb
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 2 3 3
The rows of cmb represent the two sets of indices required from df1 required to form the three rows of your requested output. (The columns, 3, represent the 3 rows in your expected result.)
The next step is to use the two rows of cmb to index df1 and use a standard vectorised operation in R via -, e.g.:
> (out <- df1[cmb[1,], ] - df1[cmb[2,], ])
B C D E F G H I
1 1 0 1 0 0 -1 0 -1
1.1 0 1 0 1 -1 0 -1 0
2 -1 1 -1 1 -1 1 -1 1
Step 3 can now be done, although I am assuming that there can only be 1, 0, and -1 values in the resulting output:
> out[out < 0] <- 0
> out
B C D E F G H I
1 1 0 1 0 0 0 0 0
1.1 0 1 0 1 0 0 0 0
2 0 1 0 1 0 1 0 1
Which is consistent with the output you requested.
For big operations, doing this with matrices might be faster overall. So we could do:
> mat <- data.matrix(df1)
> cmb <- combn(seq_len(NROW(mat)), 2)
> cmb
[,1] [,2] [,3]
[1,] 1 1 2
[2,] 2 3 3
> out2 <- mat[cmb[1,], ] - mat[cmb[2,], ]
> out2[out2 < 0] <- 0
> out2
B C D E F G H I
[1,] 1 0 1 0 0 0 0 0
[2,] 0 1 0 1 0 0 0 0
[3,] 0 1 0 1 0 1 0 1
If you need the rownames as you show, then you can easily generate these at the end:
> apply(cmb, 2, function(x) paste("row", x[1], "-row", x[2], sep = ""))
[1] "row1-row2" "row1-row3" "row2-row3"
which can be used as:
> rownames(out) <- apply(cmb, 2, function(x) paste("row", x[1], "-row", x[2], sep = ""))
> out
B C D E F G H I
row1-row2 1 0 1 0 0 0 0 0
row1-row3 0 1 0 1 0 0 0 0
row2-row3 0 1 0 1 0 1 0 1
A: Using the sqldf package or RSQLite directly would allow one to do this with all computations done outside of R so that there would be no intermediate storage required. We illustrate using sqldf. See the sqldf home page for more info.
Alternative 1 In this approach note that we use dbname = tempfile() so that it performs all computations in an external database (which it creates on the fly and automatically deletes) rather than doing it in memory.
library(sqldf)
gc()
DF <- sqldf("select x.rowid x, y.rowid y,
max(x.B - y.B, 0) B, max(x.C - y.C, 0) C,
max(x.D - y.D, 0) D, max(x.E - y.E, 0) E,
max(x.F - y.F, 0) F, max(x.G - y.G, 0) G,
max(x.H - y.H, 0) H, max(x.I - y.I, 0) I
from df1 x, df1 y
where x.rowid > y.rowid", dbname = tempfile())
This would only require that we are able to store df1 and DF in our workspace.
Alternative 2. If even that overflows we can write out df1, remove it, perform the calculation below and then we would only need sufficient storage to store the result, DF.
read.csv.sql uses dbname = tempfile() by default so in this case we do not need to specify it.
write.table(df1, "data.txt", sep = ",", quote = FALSE)
rm(df1)
gc()
DF <- read.csv.sql("data.txt", sql = "select
x.rowid x, y.rowid y,
max(x.B - y.B, 0) B, max(x.C - y.C, 0) C,
max(x.D - y.D, 0) D, max(x.E - y.E, 0) E,
max(x.F - y.F, 0) F, max(x.G - y.G, 0) G,
max(x.H - y.H, 0) H, max(x.I - y.I, 0) I
from file x, file y
where x.rowid > y.rowid")
(Of course, if its really this large then you might have trouble doing any subsequent calculations on it too.)
Output. At any rate, both alternatives give the same result shown below. x and y show which input rows were subtracted.
> DF
x y B C D E F G H I
1 2 1 0 0 0 0 0 1 0 1
2 3 1 0 0 0 0 1 0 1 0
3 3 2 1 0 1 0 1 0 1 0
Note. Although the question asked for optimizing memory rather than speed if speed were an issue one could add indexes.
A: Since the data is homogeneous, use a matrix representation. Organize it so that the 'rows' are columns, as
m <- t(as.matrix(df1))
mode(m) <- "integer" # maybe already true?
pre-allocate the space for an answer
n <- ncol(m) - 1
ans <- matrix(0L, nrow(m), (n+1) * n / 2)
We want to compare column 1 to columns 1:n + 1L (the 1L treats the number one as an integer value, rather than real). This is m[,1] - m[, 1:n + 1L], using R's recycling. Iterating over columns, with idx and off helping to keep track of the index of the columns we want to compare to, and the placement columns in the answer
off <- 0
for (i in 1:n) {
idx <- i:n + 1L
ans[, off + seq_along(idx)] <- m[, i] - m[, idx]
off <- off + length(idx)
}
The final step is
ans[ans<0L] <- 0L
Maybe there are additional efficiencies from realizing that the truth table under the original operation is 0 unless m[,1] == 1 & m[, 1:n + 1L] == 0. Likewise if space were a serious issue then the data might be represented as mode(m) <- "raw" and the arithmetic operations replaced with the comparison just suggested, along the lines of:
m <- t(as.matrix(df1))
mode(m) <- "raw"
off <- 0
x0 <- as.raw(0); x1 <- as.raw(1)
ans <- matrix(raw(), nrow(m), (n+1) * n / 2)
for (i in 1:n) {
idx <- i:n + 1L
updt <- which((m[, i] == x1) & (m[, idx] == x0))
ans[off + updt] <- x1
off <- off + length(idx) * nrow(ans)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to select a tree view node in asp.net I have the the following code sample
private TreeNode AddNode(TreeNode node, string key)
{
var child = node.ChildNodes.Cast<TreeNode>().FirstOrDefault(_ => _.Value == key);
if (child != null)
return child;
child = new TreeNode(key, key);
child.SelectAction = TreeNodeSelectAction.SelectExpand;
child.Selected = true;
node.ChildNodes.Add(child);
return child;
}
I'm not able to select the node. When I invoke treeview_SelectedNodeChanged, I'm getting NULL..
string v = ((TreeView)sender).SelectedNode.Value;
A: Use treeview.SelectedNode and check the code in page_load handler,
if(!IsPostBack)
{
//code to add nodes
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: To parse with the help of atom parsing i have to parse this type of xml..
<content type="xhtml">
<apxh:div>
<apxh:p>blah..blah...blah</apxh:p>
<apxh:p>blah..blah...blah</apxh:p>
</apxh:div>
</content>
How can i parse it by atom parsing (root handler, element handler).
A: I'd recommend you take a look at this article.
http://www.ibm.com/developerworks/opensource/library/x-android/
also just found this
Open Source Android atom \ rss reader
http://code.google.com/p/android-feed-reader/source/browse/#
How to create and parse Rss Feed
http://www.rgagnon.com/javadetails/java-0556.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Writing to Core Data from a secondary thread I have an HTTP call to a URL, which returns my data in JSON format, I parse it, then I have to load it in my Core Data context.
Now I am doing it (parsing - entities creation - commit) on the main thread, by using GCD (grand central dispatch) to dispatch a block on the main queue.
The http call is asynchronous, so it's ok, but the db loading is not, so it freezes my user interface: a UITableView backed by a NSFetchedResultsController.
What I'd like to do, is making these last tasks on a secondary thread, but don't know how!
I heard something about creating a second context, using that on the secondary thread, then trash it and "refresh" the "main" context, don't know how to explain.
Maybe is there a wwdc ed. video on this argument, too? I can't find valid documentation.
Can you help me, loading data in asynchronous way, so my table never stop scrolling?
A: There is a rule: One context for one thread. Create new context in your not main queue and work with it.
Add observer for this context:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(<#Selector name#>)
name:NSManagedObjectContextDidSaveNotification
object:<#A managed object context#>];
After your parser is done and objects in context, save that context which will kick out notification. In main queue, catch this notification and on main queue context call - (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I call a base class implementation of an explicitly impemented interface method? I'm trying to call an explicitly implemented interface method implemented on the base class but just can't seem to get it to work. I agree the idea is ugly as hell, but I've tried every combination I can think of, to no avail. In this case, I can change the base class, but thought I'd ask the question to satisfy my general curiosity.
Any ideas?
// example interface
interface MyInterface
{
bool DoSomething();
}
// BaseClass explicitly implements the interface
public class BaseClass : MyInterface
{
bool MyInterface.DoSomething()
{
}
}
// Derived class
public class DerivedClass : BaseClass
{
// Also explicitly implements interface
bool MyInterface.DoSomething()
{
// I wish to call the base class' implementation
// of DoSomething here
((MyInterface)(base as BaseClass)).DoSomething(); // does not work - "base not valid in context"
}
}
A: You cannot (it is not part of the interface available to subclasses). In that scenario, use something like:
// base class
bool MyInterface.DoSomething()
{
return DoSomething();
}
protected bool DoSomething() {...}
Then any subclass can call the protected DoSomething(), or (better):
protected virtual bool DoSomething() {...}
Now it can just override rather than re-implement the interface:
public class DerivedClass : BaseClass
{
protected override bool DoSomething()
{
// changed version, perhaps calling base.DoSomething();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: UITableView always in plain mode though defined otherwise in the XIB I've created a UITableView using the presets using the UITableViewController option in the New File dialog. I set the style to grouped using the Interface Builder.
However, the table always shows up in plain style.
The data source consists of two sections with two items each and a section header. It all shows up OK, but the style is wrong. Via NSLog I validated that the style is really set to plain at runtime. Am I missing something?
EDIT: Here my code. As I mentioned the NSLog calls return the expected values.
@implementation EventTableView
@synthesize tableView = _tableView;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[[self navigationItem] setTitle:@"Events"];
self.clearsSelectionOnViewWillAppear = YES;
NSLog(@"Table view style: %@.", (self.tableView.style == UITableViewStylePlain ? @"Plain" : @"Grouped"));
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (_appDelegate == nil) {
_appDelegate = (MyAppDelegate *) [[UIApplication sharedApplication] delegate];
}
return _appDelegate.model.eventSections.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
Section* eventSection = [_appDelegate.model.eventSections objectAtIndex:section];
NSInteger result = [eventSection getCountAsInteger];
if (eventSection != nil && result >= 0) {
NSLog(@"Got %d rows in event section %d.", result, section);
return result;
} else {
NSLog(@"Can't get event section row count. Defaulting to 0.");
return 0;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EventCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = @"Test";
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
Section* eventSection = [_appDelegate.model.eventSections objectAtIndex:section];
return eventSection.name;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"Pressed row...");
}
@end
EDIT: To help things, I included a screenshot of the Interface Builder (style set to group).
A: Updated:
Find
- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
in your controller, set there style = UITableViewStyleGrouped; before calling to super
A: If you don't have any code somewhere that calls the - (id)initWithStyle:(UITableViewStyle)style method of your view with the wrong style (which I kind of expect),
you could rewrite your init method to
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:UITableViewStyleGrouped];
return self;
}
First, though, you might try to ensure that you've saved your .xib in Xcode, clean and rebuild your app, so that you're sure that your changes are what's actually running on the device/simulator.
A: That's really crazy. I found a kind of a work around.
I added a standard UIViewController and implemented the protocols UITableViewDelegate and UITableViewDataSource on it.
In the XIB/NIB I removed the standard UIView and added a UITableView. I connected the view's outlets datasource and delegate to the File Owner object and the File Owner's view outlet to the UITableView.
Now I am able to set the style of the table to grouped. Everything works great so far. However, I don't get what's really different to using a UITableViewController...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to mock SerialDataReceivedEventArgs I have a peripheral driver that uses the serial port to communicate with the peripheral device. I want to unit test this driver and tried to mock the serial port. Therefore I created a wrapper for the framework type SerialPort to have it implement an interface:
public interface IScannerPort
{
Handshake Handshake { get; set; }
bool IsOpen { get; }
event SerialDataReceivedEventHandler DataReceived;
void Close( );
void Open( );
string ReadLine( );
}
Now I created a mock using moq:
Mock<IScannerPort> scannerPort = new Mock<IScannerPort>( );
I then want to raise the DataReceived event. But SerialDataReceivedEventArgs doesn't let me set the EventType property. So I tried to mock SerialDataReceivedEventArgs as well, ending up with
Mock<SerialDataReceivedEventArgs> args = new Mock<SerialDataReceivedEventArgs>();
args.SetupProperty(a => a.EventType, SerialData.Eof);
But the second line raises a NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: a => a.EventType
How can I raise the event? Or how can I mock the event args?
A: I think i may have partly solved your problem by answering how to raise the event, as follows:
var mockedScannerPort = new Mock<IScannerPort>();
mockedScannerPort.Setup(sp => sp.ReadLine())
.Returns("123")
.Raises(sp => sp.DataReceived += null, new object[] { this, It.IsAny<SerialDataReceivedEventArgs>() });
bool mockEventWasInvoked = false;
mockedScannerPort.Object.DataReceived += (sedner, e) => mockEventWasInvoked = true;
var retVal = mockedScannerPort.Object.ReadLine();
Assert.AreEqual( "123", retVal );
Assert.IsTrue(mockEventWasInvoked);
Mocking SerialDataReceivedEventArgs is a bit tricky, since it doesnt have a default constructor. I'll try a workaround shortly.
EDIT: Thanks @PVitt for providing the workaround for stubbing SerialDataEventArgs. Posting this here just for the sake of completeness.
[Test]
public void Test()
{
var mockedScannerPort = new Mock<IScannerPort>();
var constructor = typeof(SerialDataReceivedEventArgs).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(SerialData) }, null);
var eventArgs = (SerialDataReceivedEventArgs)constructor.Invoke(new object[] { SerialData.Eof });
mockedScannerPort.Setup(sp => sp.ReadLine())
.Returns("123")
.Raises(sp => sp.DataReceived += null, new object[] { this, eventArgs });
bool mockEventWasInvoked = false;
SerialDataReceivedEventArgs ea = null;
mockedScannerPort.Object.DataReceived += (sedner, e) =>
{
mockEventWasInvoked = true;
ea = e;
};
var retVal = mockedScannerPort.Object.ReadLine();
Assert.AreEqual( "123", retVal );
Assert.IsTrue(mockEventWasInvoked);
Assert.IsNotNull( ea );
Assert.AreEqual( ea.EventType, SerialData.Eof );
}
A: The SerialDataReceivedEventArgs doesn't necessarily be mocked. One can create an instance of it using reflection:
ConstructorInfo constructor = typeof (SerialDataReceivedEventArgs).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new[] {typeof (SerialData)},
null);
SerialDataReceivedEventArgs eventArgs =
(SerialDataReceivedEventArgs)constructor.Invoke(new object[] {SerialData.Eof});
Then the event can be raised on the mocked instance using the "real" instance of the vent args:
scannerPort.Raise( s => s.DataReceived += null, eventArgs );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Anyone had any luck integrating SQL unit tests to run with CI build tool? Goal is to run a few queries against a database on each new build? Has anyone had any luck without having to put sql in java classes or creating entire new schemas to hold stored procs? Ideally you can include some SQLs in separate files that get run as soon as the build completes.
Might be using maven,bamboo but would love to hear any experiences/successes/difficulties that people have encountered.
A: You don't say what tools you use for writing you SQL unit tests. If you're using Steven Feuerstein's utplsql tool you should read this artcle on Continuous Integration with Oracle PL/SQL, utPLSQL and Hudson. And even if you're not it might provide some useful insights.
A: Maybe Team City (Jetbrains) is what you're looking for. It has various build runners, including but not limited to Ant, MS Build, NUnit, Maven and Command Line.
Just configure a TC-project to listen to your svn/git/hg repository for changes, then run a build: first compilation and if successful then Maven (or whatever). Or which-ever way you want to do it.
/mikkel
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What happens on the stack with ref parameters in c#? Im reading some C# documentation about WCF and IDispatchMessageInspector and the interface defines a 'Message' object that is passed by reference so that it can be manipulated.
What actually happens on the stack when you pass something by ref as opposed to passing normally?
A: By reference means you can change the original variable passed to the item. It basically passes the address of the variable on the stack rather than the variable value.
IL Dump:
As you actually asked what actually happens on the stack here is an IL dump of a by ref and by value method:
.method private hidebysig instance void ByRef(string& s) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldstr "New value"
IL_0007: stind.ref
IL_0008: ret
} // end of method Class1::ByRef
vs.
.method private hidebysig instance void ByValue(string s) cil managed
{
// Code size 9 (0x9)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "New value"
IL_0006: starg.s s
IL_0008: ret
} // end of method Class1::ByValue
As you can see the main difference is the parameter type (string& instead of string) and that it does extra steps to load and store the values indirectly.
The simple C# source is shown below for reference:
void ByRef(ref string s)
{
s = "New value";
}
void ByValue(string s)
{
s = "New value";
}
A: It's not the object that's passed by reference - it's the variable.
Basically it aliases the variable used as the argument from the calling side, and the parameter in the method that you call:
public void Foo()
{
int x = 10;
Bar(ref x);
Console.WriteLine(x); // Prints 20
}
public void Bar(ref int y)
{
y = 20;
}
Here, x and y are essentially the same variable - they refer to the same storage location. Changes made to x are visible via y and vice versa. (Note that in this case it's a local variable in the caller, but it doesn't have to be - if you'd passed an instance variable by reference, then Bar might call another method which changes the same variable, and then y would be seen to "magically" change...)
For more about parameter passing in C#, refer to my article on the subject.
A: When you pass something by value; a copy of the value type is made and put on stack before the function is called. When you pass something by reference then the address of that is pushed on stack instead of creating a copy and when you modify the object in the function then the original object is being modified instead of the copy.
The way it works is that compiler translates your references to variable to indirect memory access when it sees that the argument was passed by ref.
For example let us assume at memory location 100 you have an integer 123; now when you call a function which accepts in by value (which is default) then copy of 123 will be made and pushed on stack before the function is called which means the copy will now be at (lets say) 160 address. However when you pass something by reference then address 100 will be pushed on stack and will reside on location 160.
Now the instructions generated will read 160 to get the location of object and then modify the data at 100. Indirection will happen same as it is done for pointers when you use * operator.
A: by ref means you can create new instance to the object passed,
by value cant do that just change the object properties
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using javascript to apply the users timezone diff? I thought about letting my users having to select their own timezone in my application, but what about instead making it automatic with some javascript?
Some psuedocode:
A date is printed serverside as <p class="utcDate">2011-09-28 11:00 UTC</p>. When the user loads the page, jquery walks through all elements with the utcDate class and replaces the UTC date/time with a date where the diff between UTC & the users local timezone has been applied.
What should I be aware of when doing this? Are there any obvious drawbacks to this?
Thanks
A: If you do this (which there is nothing wrong with) be aware that it can affect perceived page-load time if there is a lot of elements involved.
Be sure to do the replacement in a DOM-ready event handler and not on page load, since this would be very visible to the users.
Alternativly instead of outputting the UTC date and then changing it, why not just output a js.snippet that will write the correct date inline via document.write? - This will be faster for pageload.
If it's the same date/time everywhere you use it on a page, you can just generate it once via js, and then simply output the value stored in a variable.
A: I'd recommend outputting the Unix timestamp instead. The js Date object doesn't have the capabilities to consume a UTC string directly (you'd have to parse out each component), but it can consume a timestamp using the setTime function.
The Date object automatically localizes to the user's settings and can be cast to a string directly (although that's probably more verbose than you'd like: "Wed Sep 28 2011 07:03:26 GMT-0400 (Eastern Daylight Time)"), so you'll likely want to format the string yourself:
$('p.utcDate').each(function () {
var time = new Date();
time.setTime(this.innerHTML);
this.innerHTML = time.toDateString();
});
As an added benefit, toDateString will handle local conventions around m-d-y vs d-m-y, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Acid testing a http server Is there any apps that can test a http server for robustness.
It would be great if it can send corrupt headers, missing headers,
thrashing, attempting to keep connections open etc..
I'm writing a embedded http server in C..
A: I'd throw the Apache test at it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: IBOutlet not showing in File's Owner/ IB In my .h file I have this:
@interface {
UILabel *questionLabel_;
}
@property (nonatomic, retain) IBOutlet UILabel *questionLabel;
In my .mm file I have this:
@synthesize questionLabel = questionLabel_;
When I go to the xib file I see no evidence of questionLabel in the File Owner. Nor can I connect a UILabel by ctrl dragging to File Owner or First Responder.
It is though working with two UIButtons I have created.
Ideas?
A: You should set appropriate class of your File's Owner.
Open Utilities -> Identity Inspector -> Custom Class -> Class -> Select your class.
After that you will be able to set outlets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Performance issue with my query.Please suggest MERGE INTO Analysis a
USING ( SELECT * FROM Data ) b
ON ( a.User_Id = b.User_Id AND a.Upgrade_Flag = 0 )
WHEN MATCHED THEN
UPDATE SET Status = NVL(a.Status, 'ACTIVATE');
The above query works fine.But when millions of records are present this may lead to performance issue.Is there any alternative for the above query to get a better performace.Please suggest me on this.Thanks for your time
A: Without seeing the execution plans I can't predict whether an alternative would be any more efficient. But I note that you are not using the merge source in the update, which indicates that this could rewritten as a simple update statement:
UPDATE Analysis a
SET Status = NVL(a.Status, 'ACTIVATE')
WHERE a.Upgrade_Flag = 0
AND a.User_Id IN (
SELECT b.User_Id FROM Data b
)
As is always the case with these things, you have a choice between using an IN clause, as I have shown, or an EXISTS clause with a correlated subquery. Usually it's worth testing both options when trying to tune performance, although in at least some cases the optimizer will try that transformation on its own.
A: The query looks fine to me. Maybe you should create some indexes?
Create index for Analysis.User_Id and index for Data.User_Id if not yet created (primary key creates index automatically).
Or maybe also create index for Analysis containing both columns User_Id and Upgrade_Flag.
A: It's really not at all obvious why you are using MERGE instead of a simple UPDATE.
update analysis a
set a.status = 'ACTIVATE'
where a.status is null
and a.upgrade_flag = 0
and a.user_id in ( select b.user_id from data b )
/
Selecting only the USER_ID from DATA instead of the entire record could speed things up, presuming DATA.USER_ID is indexed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how do I call my theme preprocess function for a specific field? i'm on Drupal 7 and i have aspecific tpl.php file for a content field_image: "field--field_image.tpl.php". I need to create a preprocess function for this field and for my theme.
Supposing my theme name is "My Theme"
It should look like
function my_theme_preprocess_field(&$variables, $hook) {
$variables['classes_array'][] = 'aClassName';
}
but it doesn't work. I am wrong. But where?
Thanks
A: You could declare a mytheme_preprocess_field(&$variables, $hook) in your theme's template.php where you can check your field and do operations on its label or markup, add classes, anything. So you wouldn't need field specific tpls. - eg.
function mytheme_preprocess_field(&$variables, $hook) {
if ($variables['element']['#field_name'] == 'field_machine_name') {
$variables['items'][0]['#markup'] = 'add custom markup';
}
}
Hope this helps someone.
A: You can use template_preprocess_field() (like you do in your code above) but just test the particular field is the right one for you:
function my_theme_preprocess_field(&$variables, $hook) {
$element = $variables['element'];
if (isset($element['#field_name'])) {
if ($element['#field_name'] == 'field_image') {
$variables['classes_array'][] = 'aClassName';
}
}
}
Once you've implemented the hook don't forget to clear your caches, hook implementations are cached in Drupal 7 so won't be picked up until the cache is cleared.
A: In drupal 7 you can rewrite output of the field in template_preprocess_node() by altering "#markup" value of the field.
Also you can use regexp to change whatever you want in page content :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Problem with WP get_categories and even odd increment selector I have a small function in my WordPress theme which generates a list of menus depending on category id. I have also setup an even/odd identifier to add spacers in between, the last one is removed via jQuery (unless you can provide a way of doing this in PHP code).
Each menu shows the spacers accordingly apart from one random one?
function momentmag_tertiary_nav($cat_ID, $name = '') {
$categories = get_categories( array('child_of' => $cat_ID, 'hide_empty' => false) );
$siteurl = get_bloginfo('url');
$i = count($categories);
$catparent = get_categories( array('include' => $cat_ID, 'hide_empty' => false) );
echo '<ul class="'.$name.'-drop">';
foreach($categories as $category) {
echo '<li><a href="'.$siteurl.'/'.$catparent[0]->slug.'/'.$category->slug.'" title="View Articles in: '.$catparent[0]->cat_name.' → '.$category->cat_name.'">'.$category->cat_name.'</a></li>';
if ($i % 2 != 0) {
echo '<li class="spacer"></li>';
}
}
echo '</ul>';
}
Example of working menu:
Then this one randomly doesn't apply the spacers where as all the others do, there is 10 in total:
any ideas? this is really dodgy!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Propel 1.5 How to make join with OR condition I need to generate such SQL using Propel build criteria:
"SELECT *
FROM `table1`
LEFT JOIN table2 ON ( table1.OBJECT_ID = table2.ID )
LEFT JOIN table3 ON ( table1.OBJECT_ID = table3.ID )
LEFT JOIN table4 ON ( table4.USER_ID = table2.ID
OR table4.USER_ID = table3.AUTHOR_ID )"
Is it possible to make join with or condition? Or maybe some other ways?
Propel 1.5
A: Table1Query::create()
->leftJoinTable2()
->leftJoinTable3()
->useTable2Query()
->leftJoinTable4()
->endUse()
->condition('cond1', Table4::USER_ID . ' = ' . Table2::ID)
->condition('cond2', Table4::USER_ID . ' = ' . Table3::AUTHOR_ID)
->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR, 'onClause')
->setJoinCondition('Table4', 'onClause')
->find();
useTable2Query() is necessary because your information seems to imply that Table4 is related to Table2 and not to Table1, and so joining Table4 directly to Table1 will result in a series of fatal Propel errors. The "use" functionality bridges that relationship.
A: The first two joins (table2, table3) are easy, if I recall correctly. Just make table1.OBJECT_ID non-required in your schema, and the left join will be used automatically.
Not immediately sure about the OR join. If you get stuck, one way to do it is to use the above in a raw query, and then "hydrate" objects from the resultset. Another way (very good for complex queries that are a pain to express in an ORM) is to create a database view for the above, and then add a new table in your schema for the view. It's cheating a bit for sure, but for some really complex master-detail things I did in a large symfony project, it was great - and it made query debugging really easy as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Detect soft reset on Windows Mobile device Is there a way to make my Windows Mobile 6.1 application react to system reset?
If it matters, I am using Compact Framework 3.5.
A: A system reset (i.e. a call to the kernel with IOCTL_HAL_REBOOT) goes through the power manager (well it should, the OEM might have opted otherwise but that would be rare). During the reset, the PM broadcasts a power manegment notification which you can requent to receive by calling the RequestPowerNotifications APIs. One of the last things the power manager does is goes single-threaded and calls all drivers' Xxx_PowerDown methods. The drivers at this point have the option of doing clean up, final flushing, etc. to get into a stable state and then the device restarts.
From an app perspective, the RequestPowerNotifications call is the only thing you can do. Be aware that the PM broadcasts the notification and just keeps on moving. It does not wait for anyone to complete any activity (like it does in calling Xxx_PowerDown). This often means that your application will never get the notification, or if it does you may only get the opportunity to run a couple lines of code (I think the most I've seen was about 4 lines). On a suspend/resume, the app code typically runs after you wake back up. With a reset, since RAM and processor are reset, you don't get that opportunity.
So, after that long-winded response, the short answer is that you might be able to get the notification, but even if you do it's unlikely you'll actually be able to do anything in response to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .NET ZIP library working inmemory Is there a ZIP library for .NET working inmemory?
I need to zip and unzip files without temporary files stored on hdd. Just build archive in memory and return memory stream. Then receive memory stream and without storing zip archive on hdd unzip file and save it.
A: The DotNetZip Library supports working In-Memory.
Here are some Examples
A: SharpZipLib should work fine writing to a MemoryStream as far as I'm aware. To be honest, I'd be quite surprised to see any zip library which required you to write to a physical file. There may well be convenience methods to "add a file to the archive" but all the APIs I've seen on various platforms have allowed you to add a manually-created zip file entry with custom data.
A: The WindowsBase dll in the .NET framework has had a ZipPackage class since v 3.0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MSSQL Operation within OUTER JOIN I am trying to join two tables using a unique value, however in one table it is part of a field with different lengths, e.g.:
Table one:
Block_Run_No Vehicle_No
200001.412.20110104 1001
20002.412.20110104 1002
Table 2
Block_No Departure
200001 3600
20002 7200
Now I want to join them by Block_No and try this:
SELECT Block_No, Vehicle_No, Departure
FROM Table1,
FULL OUTER JOIN Table2 A on LEFT(Table1.Block_Run_No,CHARINDEX('.',Table1.Block_Run_No)-1) = A.Block_No
However, It claims to not recognize the expression Table1.Block_Run_No within the JOIN. Anyone can help me out here?
Thanks!
A: WITH Table1( Block_Run_No,Vehicle_No) AS
(
SELECT '200001.412.20110104', 1001 UNION ALL
SELECT '20002.412.20110104', 1002
),Table2(Block_No, Departure) AS
(
SELECT 200001,3600 UNION ALL
SELECT 20002,7200
)
SELECT Block_No, Vehicle_No, Departure
FROM Table1
FULL OUTER JOIN Table2 A on
LEFT(Table1.Block_Run_No,CHARINDEX('.',Table1.Block_Run_No)-1) = A.Block_No
Works fine for me. You have a rogue comma here
FROM Table1, FULL OUTER JOIN
Maybe that's the source of the complaint? (Intellisense complains that Table1.Block_Run_No cannot be bound until this is removed but also red underlines FULL)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to self-destruct application? I have pretty unusual task: customer would like to have application which can be self-destructed. Like with one BIG RED MAGIC button, pressing on which should completely destroy (possibly uninstall) application including any DBs, files, traces in logs and so on.
Does someone knows is it really possible, if yes - how?
A: You can purge application files by enumerating app directory and deleting everything in there plus removing your application files on SD card. Uninstalling application itself is a different beast altogether. Non system apps cannot do that AFAIK (starting from android 2.0?).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: extjs4 - changing the default id/text fields in a Tree Panel / Store The extjs 4 tree panel uses the record properties id & text by default for the nodes of the tree.
Is there any way to change it to some different property names?
There's a way to specify the root element but I can't see any config setting for those properties.
A: You can use the displayField config for treePanel, in the extjs api they say it;s a boolean value with default value text... That's just wrong :P, actualy you can put something like displayField: 'name' and it will show the name field from the store. But i don't think you can change the id property.
If you want to change the id property you can use the mapping config on the model fields and let the treePanel configs as they are. something like
fields : [
{ name: 'id', type:'int',mapping: 'yourId'},
{ name: 'text', type: 'string', mapping: 'yourText'}
]
Edit As Ben suggested you can change the property names of a tree panel by using the displayField config for the tree panel and the idProperty for the model of the treeStore.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: serialize from a table element and not the whole form Trying to serialize just the elements from a specific table but it only returns a result if i do the whole Form
in the below code, i want to ajax just the elements in tbl2
<form>
<input type="text" id="tb1" name="tbl1"/>
<table name="tbl1">
<tr><td><input type="text" name="tb2"/></td></tr>
</table>
<table name="tbl2">
<tr><td><input type="text" name="tb3"/></td></tr>
<tr><td><input type="text" name="tb4"/></td></tr>
</table>
</form>
the code
var params = $("#tbl2").serialize();
var resp = $.ajax({
async: false,
type: "POST",
url: AppRoot + "webhandlers/postback.ashx",
data: params
});
A: First and foremost, a <table> cannot have a name attribute, and even if it could, the jQuery ID selector (#) would not match it.
If you use id instead (<table id="tbl2">), it will work like this:
var params = $("#tbl2 :input").serialize();
The :input selector selects all the form elements (here, inside #tbl2), it is needed because serialize() will only work on those.
Please also check out my jsFiddle Demo.
A: you cannot serialize a table -- that method doesn't apply to that kind of DOM object, only forms and form fields can be serialized.
if you really want to do what you're proposing, you need the proper selector to pick just the children of tbl2 that are also form elements, and then you'll have to serialize each one of those by hand. someone did it in another question, here: serialize without a form?
a better way might be to disable all the form elements that are NOT in the table you're interested in -- you'll need a selector to pick all form elements that are not child elements of tbl2 -- and THEN serialize the form. the disabled elements will be omitted.
A: you can use the serializeArray method, which will give you the array of input fields and can be used with the data.
var params = $("#tbl2 input").serializeArray();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to skip bad dates in DBpedia SPARQL request? I need to get data about films from DBpedia.
I use SPARQL query as follows on http://dbpedia-live.openlinksw.com/sparql:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?subject ?label ?released WHERE {
?subject rdf:type <http://dbpedia.org/ontology/Film>.
?subject rdfs:label ?label.
?subject <http://dbpedia.org/ontology/releaseDate> ?released.
FILTER(xsd:date(?released) >= "2000-01-01"^^xsd:date).
} ORDER BY ?released
LIMIT 20
I tried to get films that were released after 01.01.2000.
But the engine answers as follows:
Virtuoso 22007 Error DT006: Cannot convert 2009-06-31 to datetime :
Too many days (31, the month has only 30)
SPARQL query:
define sql:big-data-const 0
#output-format:text/html
define sql:signal-void-variables 1 define input:default-graph-uri <http://dbpedia.org> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?subject ?label ?released WHERE {
?subject rdf:type <http://dbpedia.org/ontology/Film>.
?subject rdfs:label ?label.
?subject <http://dbpedia.org/ontology/releaseDate> ?released.
FILTER(xsd:date(?released) >= "2000-01-01"^^xsd:date).
} ORDER BY ?released
LIMIT 20
As far as I can understand there are some errors in data in DBpedia and the engine cannot convert string data to date type in order to compare with the date I set. And the engine breaks the query execution.
So, the question is: is there any way to tell the engine to skip all the erroneous data and return to me all that could be processed?
A: You can use COALESCE function in order to define a default date for invalid ones:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?subject ?label ?released ?released_fixed WHERE {
?subject rdf:type <http://dbpedia.org/ontology/Film>.
?subject rdfs:label ?label.
?subject <http://dbpedia.org/ontology/releaseDate> ?released.
bind ( coalesce(xsd:datetime(?released), '1000-01-01') as ?released_fixed)
FILTER(xsd:date(coalesce(xsd:datetime(?released), '1000-01-01')) >= "2000-01-01"^^xsd:date).
} ORDER BY ?released
LIMIT 20
This query provides following SPARQL Results on DbPedia Live Endpoint
The bind construct is only for presenting the fixed dates which are set to '1000-01-01' and stored in the variable ?release_fixed. The bind is not necessary for the query and can be omitted together with ?release_fixed in the SELECT clause
A: One way is to filter using the datatype, as you can see below:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?subject ?label ?released WHERE {
?subject rdf:type <http://dbpedia.org/ontology/Film>.
?subject rdfs:label ?label.
?subject <http://dbpedia.org/ontology/releaseDate> ?released.
FILTER(datatype(?released) = <http://www.w3.org/2001/XMLSchema#dateTime>)
FILTER(xsd:date(?released) >= "2000-01-01"^^xsd:date).
} ORDER BY ?released
LIMIT 20
SPARQL results
A: Discarding a result with a date that is off by a day seems silly to me (like Windows doing a bugcheck whenever it feels something is wrong, eg your GPU video adaptor hanging 5 times in a row).
Since you only care about the year, isn't it better to compare string-wise?
str(?released) >= "2000"
XSD says "at least 4 digits for the year" so this works for all positive years (AD).
BTW this will also work if the DBpedia extraction framework found only a year in that field.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Dynamically create java class for a Lotus Notes form I want to migrate Lotus Notes database to salesforce. using domingo I am able to retrieve the forms , form fields ,documents and etc. As soon as I get the form with its fields & their datatypes, I want to create a class for this form. Like this I want to create a class for each form. Each document can then be made as an instance to this class. I am looping the database to get forms and then looping forms to get their fields(using for loops), now is there a way to create a class for this form right in this for loop dynamically so that each form can be exposed as a class. Please kindly help
A: This certainly is possible, but wouldn't it be better to use a data structure like nested maps/lists in this case? When you dynamically create classes, you also have to dynamically create the code that works with these classes, otherwise you do not gain anything over a generic data structure.
A: I believe that it might be possible to do this via the Salesforce metadata API, but I haven't personally used that API yet. I've had people recommend it to me as a means for handling similar tasks.
I'd question the benefits of doing a migration so generically. Unless you have so many objects and fields to create that the simple task of object and field creation will take significant time, what's the advantage? Remember, you can get and set fields on Salesforce standard and custom objects without writing code to go with those objects (at least you can in Apex). Likewise, each object automatically gets a standard controller to handle display and standard operations.
You should ask yourself if your data and data model are clean enough to generate code from. Are you sure? Really really sure? What about that widget count field that got added to the shipment object back in 2005 to solve a reporting issue? Nobody uses it anymore. Still want it in your new db?
Both times I've migrated Notes databases to Salesforce, I've exported to CSV and someone else has loaded the data. The first export was just a simple export of contacts and accounts. The second time I wrote my own Lotusscript exporter since I needed to fix certain data problems before doing the Salesforce import. The second time the load was done with the data loader. If I was loading the data myself, I'd use Demand Tools. It's much more industrial-strength tool. The de-duplication features alone can save you writing a lot of custom code.
A: I believe the word 'dynamically' is misleading in this case. Perhaps I am reading the question wrong, but it seems that the forms in question are of fixed format and the word 'dynamically' is used in place of the ability to instantiate an object of a given class (aka how Java and many other languages work).
That being said, I would agree with michael667 in that this is certainly possible. Converting Form data (View) to an in memory Object (Model) via code logic (Controller) is what I (and many MANY others) do as a day job. Keep MVC in mind while developing and you should be just fine.
A: You will need to code this yourself by exporting Lotus Notes domino form elements as DXL and then translate that into you're own custom form objects for use with SalesForce.
A: Code java skeleton classes creation what you are doing is correct. Below is my quick and untested version:
Sub Initialize
Dim session As New NotesSession
Dim db As NotesDatabase
Dim view As NotesView
Dim views As Variant
Dim notesToJavaFieldMap List As String
Dim doc As NotesDocument
Dim count As Integer
count = 0
Dim formsAlreadyProcessed(count) As String
Set db = session.CurrentDatabase
views = db.Views
Forall v In views
If v.IsDefaultView Then
Set view = v
Exit Forall
End If
End Forall
'Declare a complete on to one mapping here for all Notes item types to Java datatypes
notesToJavaFieldMap(" RichText") = "String"
notesToJavaFieldMap("Text") = "String"
notesToJavaFieldMap("Time/Date") = "Date"
Dim authorItem As NotesItem
Dim itemType As String
Dim itemName As String
Dim formName As String
Dim fileNum As Integer
Dim fileName As String
Set doc = view.GetFirstDocument
While Not(doc Is Nothing)
fileNum% = Freefile()
If Arraygetindex(formsAlreadyProcessed,doc.form(0)) Is Not Null Then
formsAlreadyProcessed(Ubound(formsAlreadyProcessed)) = doc.form(0)
Redim Preserve formsAlreadyProcessed(Ubound(formsAlreadyProcessed) + 1)
fileName$ = doc.form(0) +".java"
Open fileName$ For Output As fileNum%
Write #fileNum%, "package com.mypackage;"
Write #fileNum%, "\n \r"
Write #fileNum%, " public class " + fileName
Write #fileNum%, "\n \r"
Forall item In doc.Items
itemType = item.type
itemName = item.name
Write #fileNum%, "private " +notesToJavaFieldMap(itemType) + " " +itemName
Write #fileNum%, "\n \r"
End Forall
Close fileNum%
End If
Wend
End Sub
You can them open these class java files with an IDE like eclipse and import missing imports by going Ctrl+ O and generate get and sets as well.
For the data itself dump it out as cvs and export it in.
I did not have lotus notes designer with me so this code is not tested .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Check textarea text for required words So, I'm working on a writer panel, where I have limited the maximum and minimum number of words in a textarea. The next thing I would like to do is to make sure it checks if the writer has used all the required words (keywords) in the text.
For example
The required keywords for the text is: word1, word2, word3
i want something to check the text and make sure these words have been used before adding it into the database.
i've been searching for a solution like this for hours, but non of the examples i found really covers my needs.
any help appreciated,
regards,
Tamas
A: Using a datasource such as an array to store the required words you could check your input for the values required.
Consider the following:
var requiredWords = ['hello','javascript','array'];
$(document).ready(function(){
$('#checkEssay').bind('click',function(){
enteredText = $('#essay').val();
$(requiredWords).each(function(){
if(enteredText.indexOf(this) == -1){
alert(this + ' not found!');
}
});
});
});
I have made a small mock up of this functionality here: JSFiddle
Edit:
I have added functionality for different word cases : JSFiddle 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Amazon EC2 and EBS disk space error? This is the results, df show /mnt used 381G, but du show only 57G. Any one know how this happend?
df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda1 15G 8.1G 6.0G 58% /
none 3.8G 0 3.8G 0% /dev/shm
/dev/sdc 414G 381G 13G 97% /mnt
du -smh /mnt
57G /mnt
du -smh /
74G /
A: Try running du as root. Some directories may be restricted
A: Sometimes open file descriptors can cause the outputs to differ. Try:
lsof | grep tmp
to see if there's any such files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery-ui buttons as array - example of setting label? See Edit below initial question for a revised version of the original problem
Using a jquery-ui dialog I want to be able to specify the label on the button dynamically.
To do this I'm specifying an array of buttons like this :
var arrbuttons = {};
arrbuttons.cancel = function() { alert('test1');};
arrbuttons.update = function() { alert('test2');};
$(function() {
$( "#dialog" ).dialog({buttons: arrbuttons});
});
I got that from this stackoverflow answer and it works fine as far as it goes.
What I would like to know now is how I can setup the array so the label of each button is specified for each element of 'arrbuttons'.
The jquery-ui documentation shows how to do this with an inline array like this :
$( ".selector" ).dialog({ buttons: [
{
text: "Ok",
click: function() { $(this).dialog("close"); }
}
] });
But there's no example in the jquery doco which corresponds to the answer I'm basing my attempt on.
Anyone know ?
OK I've now worked on this a little more. By doing the following I can specify the text of the buttons. The trouble is the function part no longer works (ie the buttons are labelled 'wow!' and 'kapow!' but when you click on them nothing happens.
var arrbuttons = {};
arrbuttons.cancel = {click: "function() { alert('test1');}", text:"wow!"};
arrbuttons.update = {click: "function() { alert('test2');}", text:"kapow!"};
$(function() {
$( "#dialog" ).dialog({buttons: arrbuttons});
});
Any ideas of how to do this ?
A: your "array" of buttons is actually a javascript object.
If you changed the latest code snippet you posted to this, it should work alright:
var arrbuttons = [];
arrbuttons.push({click: "function() { alert('test1');}", text:"wow!"});
arrbuttons.push({click: "function() { alert('test2');}", text:"kapow!"});
$(function() {
$( "#dialog" ).dialog({buttons: arrbuttons});
});
Here, you see that arrbuttons is actually an array of javascript objects that jQuery will recognize as having both a click and a text property, which is what the api is expecting when passing in an array. I think you've mixed up your method signatures and that made jQuery angry.
A: remove the double quotes around function statement
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ajax wont work by first page load I created a discussion form below an article. It's possible
to discuss about the article by writing some story and submit this. The article will be
inserted by an ajax call with jQuery.
The problem I have. The ajax call to show the discussion who is written wont show after the submit, after I do a page reload and put another discussion it works all perfect (with ajax also).
$(function() {
$(".submit-<?php echo $article['id']; ?>").click(function() {
var discussion = $(".discussion-<?php echo $article['id']; ?>").val();
var article = $(".article-<?php echo $article['id']; ?>").val();
var dataString = 'discussion=' + discussion +
'&article=' + article +
'&post=' + <?php echo $this->post['id']; ?>;
if (discussion == '' || article == '') {
}
else {
$.ajax({
type: "POST",
url: "http://dev.localhost:10088/post/validate",
data: dataString,
cache: false,
success: function(html) { $("ul.<?php echo $article['id']; ?>").append(html); }
});
$('.discussion-<?php echo $article['id']; ?>').val('');
}
return false;
});
});
With kind regards,
Nicky
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: managing document.ready event(s) on a large-scale website NOTE: I have now created a jQuery plugin which is my attempt of a solution to this issue. I am sure that it could be improved and i've probably overlooked lots of use cases, so if anyone wants to give feedback feel free :-) https://github.com/WickyNilliams/ReadyBinder
I don't have a problem as such, but thought this would be an interesting point for discussion, and i hope people have some interesting ideas for this.
Basically, i work on a large-scale website and increasingly we are writing more and more JavaScript. This is fine, i enjoy JS' unique approach and i find the quirkiness in some of the darker annals of the language to be endearing ;-) However one thing that has always bugged me is how to manage document ready events as they get increasingly large over time (and as a result less focused/specific to the page being served)
The problem is that we have one JS file (merged & minified, though that's kind of inconsequential for my questions). Most of the JS is written using the revealing module pattern, and jQuery is our framework of choice. So all our JS funcitonality is logically grouped into methods, namespaced, and then right at bottom of the script file we have this
$(function(){
//lots of code here, usually calling encapsulated methods
//on our namespaced revealing module
});
The problem is that not all of the code in this document ready handler pertains to every page. For instance, on one page only 10% of it might be relevant, on another perhaps 80% might be relevant. To me, this feels incredibly wrong, i feel i should only execute the code i need per page, mainly for efficiency, but also maintainability.
I've searched google for approaches to this issue, but cannot find anything, maybe i'm just searching for the wrong thing!
Anyway, so my questions are:
*
*Has anybody ever thought about this issue?
*Is it actually an issue in other people's opinion?
*Do you have a large, all-encompassing document ready handler in your code or is it more focused for the type of page being served?
*If the latter, how do you manage this? Multiple handlers which get switched in JS or dynamically spitting out the document ready handler server-side?
Look forward to people's thoughts on the matter.
Cheers
A: This is what i have done in my rails mvc project with heavy javascript, i have created a separate namespace for the controllers in js which resembles the rails controller
class BusinessController
def new
end
def index
end
end
and
Var Business = {
init : function(action) {
//code common to the Business module
//even add the common jquery doc ready here, its clean
//and call the page specific action
this[action]();
},
new : function() {
// check jquery document ready code here, thats relevant to this action
//New rental page specific code here
},
index : function() {
// check jquery document ready code here, thats relevant to this action
//index rental page specific code here
}
}
and on the view code(server side) just initiate the page specific js code by
<script type="text/javascript">
<%= controller_name %>.init('<%= controller.action_name %>');
//which will render to
// Business.init(index);
</script>
You can pretty much tweak this to make it work in any language. And this approach doesn't care whether you have a single file or multiple files.
A: I think the must intuitive solution to this problem is, simply, to reduce the amount of work performed at load time.
If your code looks something like:
$(function () {
// Binds a single click event (which will never be triggered if the hypothetical
// widget is never used), regardless of how many widgets are used on the page.
$(document).delegate('.rating-widget', 'click', namespace.rating.handler);
// and so on for similar things which simply require event handler registration
// Initializes each of the forms on the page, letting the initializer take care
// of any details (datepicker widgets, validation, etc) based on the root element
$('form.fancy').each(namespace.fancyform.initializer);
// and so on for similar things that require initialization
// ... (for each type of thing on the page requiring initial setup,
// find the most general/high level pattern that sufficient)
});
things should be relatively maintainable, even if there are a few dozen lines. There's no complicated/interesting logic at this level to update/remember when working with the component code and, because everything at this level is trivial, it's easy to read. At this point, there's no need to invent some complicated registration system; it's not going to be any simpler than .delegate and .each.
Note as well that all of the above gracefully handles the case where the component is not used. In those cases, little or no work is done and no conditional logic is necessary.
For interesting ideas about how you might implement the handlers/initializers, you might want to take a look at, for example, the "Contextual jQuery in practice" talk Doug Neiner gave at jQuery Boston last week.
A: Great question. I actually handle this by using custom page load events.
So in my core .js file I have a class like the following:
var Page = {
init: function(pageName) {
switch (pageName)
{
case: 'home': {
// Run home page specific code
}
case: 'about': {
// Run about page specific code
}
...
}
}
}
You can call this a bunch of ways, either in a page-specific $(document).ready() or from the core script using some kind of URL parser (literally anything is possible with a URL parser):
$(document).ready(function() {
// http://www.mydomain.com/about
var currentPage = window.location.pathname; // "about"
Page.init(currentPage);
});
window.location DOM reference: https://developer.mozilla.org/en/DOM/window.location
A: First I put specific classes on the body or on specific containers e.g. articles, form-validation, password-meter, … . If I have an MVC app, I prefer to put the controller name into a body class. This does not hurt a lot and can be useful for styling, too.
Then on each document.ready block I check for the existence of such a class, and if it does not exist I return from this function. This approach is simpler as it does not have the main code inside an if clause. This approach resembles to assertions that are used to check prerequisites of a function.
Example:
$(function(){
if($('body').hasClass('articles') === false){ return; }
//body of the articles code
});
$(function(){
if($('body').hasClass('password-meter') === false){ return; }
//include password meter in page
});
The bonus of this approach is that no unwanted code can sneak into a ready callback, which makes it easier to reuse. The downside is that you get many callback blocks and if you do not pay attention duplicate code can easily sneak into your app.
A: I know where you're coming from. Right webapps for mobile use it can feel silly making the user download a massive JS file full of irrelevant code (the JQuery API for one is a bad start!).
What I do, which may be right or wrong but certainly seems to work is include required functions on a page by page basis before the tag. (This position for the most part, gets around the document.ready issue). Yet can't help but feel this approach is too simple.
I am interested in hearing other answers though so it's a good question, +1.
A:
"The problem is that we have one JS file"
I'm not sure how you can avoid it as long as you are including the same (merged) JS file for all pages. You could use some server-side logic to merge different pieces to go with different pages, but then you presumably lose the benefits of client-side caching of the JS, so...
Projects I've worked on have (typically) used multiple JS files, a couple being common to every page, and the others being included or not as appropriate - some JS files included by only one page. This means that pretty much every page includes the common library functions whether they use them or not, but the common JS file gets cached so it doesn't really matter. Page-specific code really is page-specific.
I can't tell from your question whether you are aware of it, but you can have multiple document ready handlers (I believe jQuery executes them in the order they were bound?). So if you do split the JS up each JS file can include its own document ready. Of course that approach has its own overhead, but I think it's better than putting everything in the same file.
A: Firstly, if you're using jQuery, document.getElementsByTagName isn't really necessary, you can just use $("tagname"). Have a look at the jQuery Selectors documentation for even more magic!
Your work-in-progress solution is the way I would go about it, but you don't need to go to the trouble of defining extra functions, getting bodyClasses, running a loop, or any of that jazz... why not just use jQuery's .hasClass() function?
$(function() {
if($("body").hasClass("article")) {
alert("some article specific code");
}
if($("body").hasClass("landingPage")) {
alert("some landing specific code");
}
});
Bam. All you need. If you want to be even more efficient, you can reuse one body query:
$(function() {
var body = $("body");
if(body.hasClass("article")) {
alert("some article specific code");
}
if(body.hasClass("landingPage")) {
alert("some landing specific code");
}
});
Here it is on jsfiddle: http://jsfiddle.net/W8nx8/6/
A: Having less javascript files minimizes the number of requests sent to the server and caching the files makes the second and third pages load faster.
Usually, I think about the likelihood of some parts of a js file will be needed in the following pages (and not just the current page). This makes me categorize my js code into two types:
code that goes in my "main.js", and even if not used, it is going to be downloaded by the client (but not necessarily executed, I will explain), and the second category of code goes in separate files. You could actually create multiple files grouped by probability. This depends on the details of your project. If it's a large scale project, running some statistical analysis on user behavior might reveal interesting ways of grouping js code.
Now that the code has been downloaded to the client, we do not want to execute all of it.
What you should do is have different layouts or pages. Place a partial in the layout or page. Inside the partial set a javascript variable. Retrieve the javascript variable in the javascript code and determine whether you want to execute some code or not.
i.e:
Create partial "_stats.html.erb", place this code in it:
<script type="text/javascript">
var collect_statistics = <%= collect_statistics %>;
</script>
Place the partial in the pages you would like to collect statistics:
show.html.erb
<%= render "_stats", :collect_statistics => false %>
Now in your js file, do the following:
$(document).load( function() {
if (typeof collect_statistics != "undefined" && collect_statistics) {
// place code here
}
});
I hope this helps!
A: I like the RameshVel approach. I also found the Paloma gem to create page-specific JavaScript. For instance:
Paloma.controller('Admin/Users', {
new: function(){
// Handle new admin user
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: File API upload file I am aware that the File API only exposes the name, contents, size and modified date of a file.
I was wondering if it was possible to do the equivalent of reading a file straight into a byte[] and streaming it to a php server where the file can be recreated/saved keeping things like Creation Date intact or at least readable.
A: Not if you use javascript only. Using flash it should be trivial, but since 'Create date' and similar attributes are not part of the file, but the file system it resides on, js can't see them.
A: Since the File API indeed does not support determining the creation date. There is no way to get that.
In general, many filesystems don't even store it, so even the API would include the creation date, it would be undefined in many cases.
Some file formats contain a section of metadata which you can parse on the server. For example, if your uploads are images, have a look at php's exif and/or iptcparse functions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Detecting if click is not some specific divs I am developing a sort of horizontal menu but visible on click and hide on click but visible when click is on some arrow while hide when click is on document but not some div container. In that div container there are also some other elements. If we write document.onclick=closingfunction then it close whether user click in that div itself. I want to call closefunction when user click anywhere but not in that div itself or on arrow.
It seems that there will be its solutions, but I haven't found one, so that's why posting it here.
A: using Prototype you can do something like this
document.observe('click', function(ev) {
var el = Event.element(ev);
if ((el !== $('thediv'))
&& !el.descendantOf(thediv)) {
// hide div here
}
});
A: You can use jQuery's closest() to see if the click is inside the menu:
http://api.jquery.com/closest/
$('body').click(function(e){
if($(e.target).closest('.myMenuDiv,.myMenuArrow').length === 0){
// Close it
}
});
A: You can use jQuery is() function to detect if current target matches specific selector:
$('ul.container li').click(function(e){
if ($(e.target).is('.dropdown')) {
//do something when clicked inside dropdown
}
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Nginx + uWsgi + Django strange json response behavior Some tech specifications:
*
*CentOS 6.0
*uWSGI 0.9.9.2
*Nginx 1.0.5
*Django 1.3.1
uWSGI:
[uwsgi]
socket = 127.0.0.1:3031
master = true
processes = 5
uid = xx
gid = xx
env = DJANGO_SETTINGS_MODULE=xx.settings
module = django.core.handlers.wsgi:WSGIHandler()
post-buffering = 8192
harakiri = 30
harakiri-verbose = true
disable-logging = true
logto = /var/log/xx.log
vacuum = true
optimize = 2
JSON serializer:
class LazyEncoder(simplejson.JSONEncoder, json.Serializer):
def default(self, obj):
if isinstance(obj, Promise):
return force_unicode(obj)
if isinstance(obj, Decimal):
u_value = force_unicode(obj)
if u'.' in u_value:
return float(u_value)
return int(u_value)
return super(lazy_encoder, self).default(obj)
JSON HttpResponse:
class JsonResponse(HttpResponse):
status_code = 200
json_status_code = 200
message = _('OK')
def __init__(self, json={}, *args, **kwargs):
mimetype = kwargs.pop('mimetype', 'application/json')
if not 'status' in json:
json['status'] = {'code': self.json_status_code, 'message': self.message}
super(JsonResponse, self).__init__(LazyEncoder(indent=settings.DEBUG and 4 or None, separators=settings.DEBUG and (', ', ': ') or (',', ':')).encode(json), mimetype=mimetype, *args, **kwargs)
I have a few subclasses of JsonResponse with other json_status_code and message.
View:
....
if application.status == Application.STATUS_REMOVED:
return JsonApplicationSuspendedResponse()
....
return JsonResponse()
PROBLEM:
Even when the application status is changing it happens that I receives old json lest say for 3 - 4 seconds and then it returning JsonApplicationSuspendedResponse() correctly.
I checked the database application status update takes place immediately,
also noticed that if I reboot uWSGI and send request response is correct and the opposite situation happens. Second request after status change can have old json.
It looks as if they write the response for few sencods and had a problem with her refresh (Cache is disabled).
Any ideas where it might be the problem ?
The same code works fine on Apache2 and mod_wsgi
fixed
This was a really stupid bug, in JsonResponse I had:
def __init__(self, json={}, *args, **kwargs):
part json={} is quite important here, JsonResponse and each subclass of JsonResponse after init shared initial dict and its contents, so the answer looked like a did not change.
def __init__(self, json=None, *args, **kwargs):
mimetype = kwargs.pop('mimetype', 'application/json')
if not json:
json = {}
if not 'status' in json:
json['status'] = {'code': self.json_status_code, 'message': self.message}
Thanks for your time
A: have you tried disabling the python optimizer (remove the optimize option from the uWSGI config file)?
Even if it looks like more a js/html/client issue some object can make some sort of mess with optimizations enabled. And please do not follow silly advise like downgrading to unsupported more than 1-years-old versions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Background image not showing up in span tag Im having trouble with a span tag showing a background image in the latest FF on windows 7.
It seems to work and show everything fine in earlier FF, Chrome, Safari and IE but handheld devices and windows 7 it seems to fail.
Sorry if this seems vague I just cant figure it out, the images were originally pngs with no height specified and ive since made them gifs and applied a height.
<span class="design">Design Viz</span>
<style>
.design {
background:url(_includes/images/agenda-design.gif) no-repeat top left;
display: inline-block;
height: 17px;
padding-left:25px;
}
</style>
A: The background-image CSS property only puts an image as the background. The width and height of an object is always defined either by static settings via CSS/inline styling, or by the actual size of the content displayed in it.
In your case, since you haven't added any content between your tags, its x/y dimensions will be 0, but there is no bug with the background. It's there, only you can't see it unless you define (somehow) a size for the element.
<span class="design">Design Viz</span>
.design {
padding-left:25px;
background:url(_includes/images/agenda-design.gif) no-repeat top left;
display: inline-block;
height: 17px;
width: 50px;
}
Where 50 can be any helpful value suited for your case.
A: display:inline-block; is not supported by IE7. You can fix it by adding:
.design {
padding-left:25px;
background:url(_includes/images/agenda-design.gif) no-repeat top left;
display: inline-block;
height: 17px;
width: 50px;
zoom: 1;
*display:inline;
}
A: You cannot set attributes no-repeat top left if you declare background-image. In background-image you must only set the link to your image.
Or you could use background like this:
background: url(...) no-repeat top left
A: use padding like
padding-left:25px;
padding-top: 6px;
padding-bottom: 10px;
padding-right: 5px;
A: Add width: 17px to your css style too (or whatever width it is)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: Track MSSQL 2008 table changes, what is the best method? I need to track records changes in one MSSQL table from .NET 4.0 application. What is the best method to do that?
More description about the app. We have membership table which is updated from application #1. We also developing application #2, which should track membership table and send e-mail notification on certain membership data changes.
A: For DML changes:
In SQL Server 2008, you have a built-in feature for this purpose: Change data capture.
For DDL changes: Starting with SQL Server 2005 you have DDL triggers, Example
A: If you have a history table (A table with the same columns as the original table, plus an auto-increment ID column), you can track everything about changes to the original table. You can track inserts, deletes, and every change. Use triggers for insert, update, and deletes to put a row into the history table. If you don't need all these options, then use those that you do need.
If you choose to use an IsDeleted flag in the original table, it complicates every query, and leaves your active table with lots of unneeded rows. But that can work, depending on your needs.
check out this link.. for more information....
http://www.codeproject.com/KB/database/DTS_SQLExpress.aspx
A: This is what i think you need to do.
Create a trigger on SQL tables which will create a file in one folder everytime the data is updated.
Create FileSystemWatcher in Application 1 and 2 which will monitor that folder.
In the callback function of FileWatcher, write code to send email notifications.
A: Use an Open-Source class SqlDependencyEx. It is pretty easy to configure and use:
// See constructor optional parameters to configure it according to your needs
var listener = new SqlDependencyEx(connectionString, "YourDatabase", "YourTable");
// e.Data contains actual changed data in the XML format
listener.TableChanged += (o, e) => Console.WriteLine("Your table was changed!");
// After you call the Start method you will receive table notifications with
// the actual changed data in the XML format
listener.Start();
// ... Your code is here
// Don't forget to stop the listener somewhere!
listener.Stop();
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How I can integrate my media queries with java script for supporting @media Queries in IE? I wrote these media queries for re-size my browser window
@media screen and (min-width:768px) and (max-width:1023px) {
#wrapper {
width:621px;
padding-left: 50px;
margin:0 auto; background:red;
}
}
@media screen and (min-width:1024px) and (max-width:2047px) {
#wrapper {
margin:0 auto;
padding-left: 50px;
width: 925px; background:yellow;
}
}
its working but in IE its not working then i read on Google that media query is not supported in Internet Explorer 8 or older. we can get this using java script , i am not able to write and integrate my above code with java-script. can anybody help me ?
A: A simple and lightweight solution is Respond.js.
All you have to do is include the script after your CSS, and it Just Works.
Here's a demo, check it in an older version of IE: http://scottjehl.github.com/Respond/test/test.html
A: @jamman; check this article they use java script & media query in there example may that help you http://css-tricks.com/6206-resolution-specific-stylesheets/
in it you have to call a different css according to the screen size change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: gcc: Compile a 64-bit binary on 32-bit platform Is it possible to compile a 64-bit binary on a 32-bit Linux platform using gcc?
A: If you have a multilib GCC installed, it's as simple as adding -m64 to the commandline. The compiler should complain if it is not built with multilib support.
In order to link, you'll need all the 64-bit counterparts of the standard libraries. If your distro has a multilib GCC, these should also be in the repositories.
A: Go into Synaptic and search for gcc-multilib or g++-multilib and install the package, if the -m64 option does not work. Then, compile with the -m64 option.
A: You will need a gcc that will compile on 64 bits machines, eg x86_64-linux-gcc. Check your distribution package manager.
A: I think you could install gcc-multilib pachage first.
And then compile your code using gcc -m64 yourcode, you cound check the ELF file using file yourprogram, the output should be like this
yourprogram: ELF 64-bit LSB executable,.......
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Method that returns the yield for an object in Ruby Is there a method in Ruby that returns the content of the block passed on to an object?
For example, what if I have an object which I want to put in an array?
In an ideal world, we would do (what I'm looking for):
"string".reverse.upcase.something{ |s| send(s) }
which would return an array with my object, as equivalent to:
send("string".reverse.upcase)
which isn't chainable if I have my object to start with and can get messy in more complex scenarios.
So the something method would return the evaluation of the block, like Array#map, but for one element only.
A: I don't know of such a thing built-in but you can easily do it yourself:
class Object
def something(&block)
block.call(self)
end
end
p "foo".something { | o | [o] }
p 23.something { | x | p x; 42 }
gives
["foo"] # object "foo" put into an array
23 # object handed to block
42 # something return block's result
A: Six years after the original question, Ruby 2.5.0 introduced Object#yield_self, then shortened in Ruby 2.6 as #then:
class Object
def yield_self(*args)
yield(self, *args)
end
end
[...]
It executes the block and returns its output.
(Ruby Feature #6721)
For example:
2.then{ |x| x*x } # => 4
A: Are you looking for Object.tap ?
A: I sometimes wish for a similar function in the standard library. The name could for example be with or with_it
(Repeating previous code with new name)
class Object
def with_it(&block)
block.call(self)
end
end
Example usage:
x = [1, 2, 3, 4, 5].map {|x| x * x }.with_it do |list|
head = list.unshift
list << head * 10
list.join " / "
end
As opposed to:
list = [1, 2, 3, 4, 5].map {|x| x * x }
head = list.unshift
list << head * 10
x = list.join " / "
While the latter is easier to understand, the former has the benefit of keeping the variables list and head scoped and the assignment to x is more clear in my opinion (the assignment to x has to be inserted into the last line of the code). Scoping would be a benfit if the code was a part of a larger method.
Another option to using with_it would thus be putting the code in a separate method. Eg:
def mult_head_and_join(list)
head = list.unshift
list << head * 10
list.join " / "
end
x = mult_head_and_join [1, 2, 3, 4, 5].map {|x| x * x }
Not sure what to conclude with here, but I guess I'd vote for with_it to be included in the standard library
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Method Parameters C# I wrote a method like this in C#.
MethodBase method = MethodBase.GetCurrentMethod();
string key ="";
for (int i = 0; i < method.GetParameters().Length; i++)
{
key=method.GetParameters().Name;
// need value of parameter here
}
I'm getting parameter names through the above code. My question is: How can I get the values of the parameters which are coming to my method?
A: You can't - not without using the debugger API, at least (which is distinctly non-trivial). That information isn't available via reflection. In particular, the MethodBase object you're fetching is probably going to be the same one on every invocation.
(I don't think the method you've written is quite as you've shown either, and I really hope you're not calling GetParameters inside a loop like that, but that's a side issue.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: not able to access label text Please take a look at my code. I'm not able to access the value of the Label text in the Button1_Click, event but am able to access TextBox text that is set in the use function:
public partial class productDetail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = int.Parse(TextBox1.Text);
int pr = int.Parse(Label4.Text);
string s2 = System.Web.HttpContext.Current.User.Identity.Name;
string s1 = Request.QueryString["pName"];
Label1.Text = s1;
Label5.Text += Label4.Text;
}
protected void use(object sender, DataListItemEventArgs e)
{
Label prd = (Label)e.Item.FindControl("productNameLabel");
Label1.Text += prd.Text;
Label brd = (Label)e.Item.FindControl("brandLabel");
Label2.Text += brd.Text;
Image img = (Image)e.Item.FindControl("Image1");
Label3.Text += img.ImageUrl.ToString();
Label prc = (Label)e.Item.FindControl("priceLabel");
Label4.Text = prc.Text;
}
}
A: I think you forgot the runat="server" from the label.
Edit: why dont you set the labels like this:
protected void use(object sender, DataListItemEventArgs e)
{
Label1.Text += productNameLabel.Text;
Label2.Text += brandLabel.Text;
Label3.Text += Image1.ImageUrl.ToString();
Label4.Text = priceLabel.Text;
}
(ask these type of questions in the class instead)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to call a javascript function along with scope from Actionscript? I could call a javascript global function from ActionScript using ExternalInterface. Can I somehow call scope.method() instead without making the global function call scope.method() inside it?
A: I did something similar (I think) previously...
In Javascript:
function SomeObject()
{
this.someMethod = function()
{
//do something...
}
}
var obj = new SomeObject();
In actionscript:
ExternalInterface.call("obj.someMethod");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to change multiple form element using ajax, javascript and php i am using ajax and javascript to change form element based on select option but i cant change only one text field, While i want to change multiple field e.g. selection on product i want to change its cost and stock value.
here are my files
-----------ajax file--------------
function loadXML(str)
{
if (str=="")
{
document.getElementById("mygDiv").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","price.php?q="+str,true);
xmlhttp.send();
}
-----------php file--------------
<?php
include("connection.php");
@$m_id = $_GET['q'];
$btn = mysql_query("select distinct batch_no from purchase_info where medicine_id ='$m_id' order by batch_no")or die(mysql_error());
echo "<select name='batchno' >";
if(mysql_num_rows($btn))
{
while($rows = mysql_fetch_array($btn))
{
?>
<option value="<?php echo $rows['batch_no'] ?>"><?php echo $rows['batch_no'] ?></option> <
<?php
}
}?>
</select>
A: You can use XML format for ajax calls. Using PHP, output XML file instead of HTML.
This can be helpful If you don't know what I'm talking about.
http://www.v7n.com/forums/coding-forum/45263-create-xml-file-using-php.html
Then , in JavaScript, use xmlHttp.responseXML instead of responseHTML.
You will get an XML DOM structure in JavaScript that you can parse.
This can be helpful if you do not know how to parse XML document in JavaScript.
http://www.adobepress.com/articles/article.asp?p=425820&seqNum=7
The point is that you can have different XML nodes that represent different things. For example you could have a node
<value>25</value>
In Javascript, you read this node's text (25) and do something with it on the page - for example set value of some input field to 25.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Suspend the Undostack of Avalonedit?
*
*I perform a massive text-change on the editor
*i can not (or very difficult) determine when the changes begin end (the textchange is released by scrolling)
*i dont want to be able to undo the changes
for this reasons i want to suspend the listening of the stack (or do a pop after any textchange). but
*
*the stack offers no method to pop a stackelement without performing the undo
*i dont want to clear the stack completly
*there´s no method to detach the stack from the textdocument
*there´s no method to suspend the listening
do you know a possibility to solve this?
A: You want the undo stack to not record some changes, but don't want to be cleared it either?
That would mean the contents of the undo stack might be inconsistent with the document content - when the user then presses undo, it might end up crashing or changing text other than in the expected location.
For this reason, AvalonEdit does not support this operation.
We try very hard to avoid inconsistent undo stacks - for example, re-entrant updates (changing the document within a TextDocument.Changed event handler) are disallowed.
The closest you can get to disabling the undo stack is to set
document.UndoStack.SizeLimit = 0;
This will effectively disable listening for changes, but it'll also clear the undo stack.
As a side note: it is possible to 'detach' an undo stack (by setting document.UndoStack to another undo stack), but that will also clear the old undo stack.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Replace APK in remote devices I have devices running a APK-file that i have provided. (Non-market)
I now want to update the APK on those devices. To do this i send a email to the devices with an adress to the APK-file.
My problem is that when the users click the link, download the file, and start the installation process they get a error, "Application could not be installed" because the APK is already installed on the device.
BUT not all users get this error. It works for some and not for others.
And yes, the version is updated in the manifest.
Any suggestions to a fix, or a reason why this doesnt always work?
A: For you to be able to update your application old version to a new version you need to sign both versions with the same key. This explains how to do that in a detailed manner.
P.S. I read somewhere that it is worth uploading your application to Android Market even if you are not going to distribute it that way (just make it private). This way noone will be able to hijack your application.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing Border Color of AWT TextField In AWT application I need to set border color of TextField.
In JTextField, I know that we do can do the following
JTextField tf = new JTextField();
tf.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
But setBorder() method is not availiable in awt TextField. Is there any workaround for this problem?
A: The AWT TextField does not support borders, as you've found. You could emulate a border by putting the text field inside a Panel that's just slightly larger than the textfield and changing the background color of the panel.
A: For compatibility with look & feel variations, the setBorder() API recommends the following: "In general, when you want to set a border on a standard Swing component other than JPanel or JLabel, we recommend that you put the component in a JPanel and set the border on the JPanel."
Addendum: While this suggests an approach, it is irrelevant to a pure AWT application.
A: tf.setBorder(new LineBorder(Color.red,1));
//new LineBorder(color,width);
A: tf.setBorder(new LineBorder(Color.red,1));
//new LineBorder(color,width);
Because the method is overloaded you can define the Color, and leave the rest to the default.
Alternatively, you can define the whole method and choose the Color, line Thickness, and type of corners; rounded or not.
public LineBorder(Color color) {
this(color, 1, false);
}
public LineBorder(Color color, int thickness) {
this(color, thickness, false);
}
@ConstructorProperties({"lineColor", "thickness", "roundedCorners"})
public LineBorder(Color color, int thickness, boolean roundedCorners) {
lineColor = color;
this.thickness = thickness;
this.roundedCorners = roundedCorners;
}
A: Create a line border with the specified color and width
Border border = BorderFactory.createLineBorder(Color.BLUE, 5);
Set the border of this component
JTextField.setBorder(border);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Generate different pdf for each row in a datatable I need to have a functionality that on click of a button i need to generate pdf file for each record in the datatable.
I require to generate report card and then mail that report card to each person. the data for report card is fetched into a datatable for all students.
I just need a functionality that i can generate individual pdf from datatable.
Thanks
A: There's a page here that covers various solutions to creating PDF documents on the fly. One of particular note to you looks to be the ASP.NET FO PDF Report Server Control which can generate PDF files directly from a DataTable. It looks rather old but might suffice.
One additional tip is you will want to look at Caching solutions too, so that you are not always generating a new PDF every time the button is clicked, unless you specifically want that to happen (for instance if the server-load won't be that high and/or the data is changing frequently, though it doesn't sound like it is).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Differences between caching components in web config Whats the difference between these two caching components in the web config?
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="90.00:00:00" />
</staticContent>
and
<caching>
<profiles>
<add extension=".png" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
<add extension=".jpeg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
<add extension=".jpg" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
<add extension=".css" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
<add extension=".js" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" duration="00:00:30" />
</profiles>
</caching>
I'm having trouble really finding info on the second version. What constitutes a change when it says "CacheUntilChange" and why would it have a duration then?
Thanks
A: I am facing similar doubts. This is what I figured out from the vast content on the internet.
Please feel free to correct me if I'm wrong or add more information in case I've missed anything.
1) <staticContent><clientCache> caches only on the client side.
Caching profiles can be used to cache files on the client side as well as the server side.
To configure on both set location="ServerAndClient" .
The policy tag configures the client side caching policy, kernelCachePolicy tag configures the server caching policy.
2) StaticContent caching does not support caching based on file types or extensions.
Caching profiles support caching based on extensions.
3) To apply staticContent caching on files at a particular location you can either use the location tag in the main web.config so that staticContent caching applies to all the files in that location.
e.g.
<location path="Content/common/images">
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMaxAge="86400" cacheControlMode="UseMaxAge"/>
</staticContent>
</system.webServer>
</location>
The above tag will apply caching to all the files in the "Content/common/images" folder.
Or staticContent tag can also be specified in a local web.config in the folder whose contents need to be cached.
For caching profiles, to be applied to a particular folder you can specify the caching profiles section in the config file local to the folder.
All the profiles applied in the main web.config will be applied in addition to the location specific profiles.
4) To configure StaticContent caching through IIS, you need to use the HTTP Response Headers configuration window
To configure caching profiles through IIS, you need to use the OutputCaching configuration window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Assign Credentials to specific Database in SQL Server 2005 I want to assign user name and password on specific database in SQL Server 2005. Kindly tell me its solution. Thanks
A: Create new login like "test" by right click on Security >> Logins in SSMS. In "User Mapping" section select database for which you need to assign credentials and select required rights like below :
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Differentiated access rights in distributed VCS's I have currently collected a large part of my work under a single and nicely organized repository in subversion.
When another person, say X, needs to collaborate on a sub-project, say /path/to/my/subproject, I can simply give X permissions to read/write in that specific path.
From my point of view, I still have the nicely structured repository and doesn't need to do anything else than modify some simple permissions for everything to work for X - and from X's point of view, he has just access to the relevant part. Everybody is happy.
In a distributed VCS like git or Mercurial however, all access seems to be given per repository.
I therefore fail to see how to obtain similar functionality as described above in these systems. It seems that I have to create a whole new repository if person X suddenly needs access to parts of my original repository.
Furthermore, if another person, say Y, needs other access rights within the path that X has access to, I have a problem.
Can I obtain similar functionality with differentiated access rights in distributed VCS's as I currently have in subversion? If so, how?
A: One other option is to add an authorization layer like Gitolite.
It has settings for authorizing a user to:
*
*contribute to specific branches of a Git repo.
*and/or define personal branches.
But more generaly, yes, one project often equates one repo, in order for that "component" ("coherent set of files") to evolves on its own, independently of others.
You can then join those repos within one parent repo through submodules.
The lack of authentication and authorization is explained in "Distributed Version Control Systems and the Enterprise - a Good mix?".
A: This is not possible in git, or any other DVCS that I know of. The idea of a DVCS is to decentralize everything. This carries with it the fact that the repository has no central authentication. If joe clones your repo, he has full access to that entire repo. Now you can limit what you pull into your repository, but he can do anything he wishes with his.
There are 3rd party solutions like Gitolite that would allow you to get close to the behavior you wish, but it would require that you setup a server and track keys. Which may be worth it
The key thing is that, as far as I know, there is no way to limit read access to a sub directory of a repository. Write can be taken care of in Gitolite or by selectively doing your git fetch, but once a user has cloned a git repository, they have full control of the entire repository while it is on their machine.
From the Gitolite manual:
*
*Read access controlled at the repo level
*write access controlled at the branch/tag/file/directory level, including who can rewind, create, and delete branches/tags
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Linq and lambda, both neglects the identity colum when I perform basic operations - how to avoid it? I have a DataTable, say:
OrdersDataTable dtResults = Datalayer.Orders.GetOrdersByCustomer(1)
and then I am trying to select a part of that to tie to a data repeater like so
var CustomerOrdersByProduct = dtResults.Where(r => r.ProductId == ProductId);
// OR
var CustomerOrdersByProduct = from r in dtResults
where r.ProductId == ProductId
select r
rpOrders.DataSource = CustomerOrdersByProduct;
rpOrders.DataBind();
and the stored procedure, returns a table like this:
OrderId ProductId CustomerId .....(etc)
But I get an error when I try to access OrderId (which is the primary key) in my var CustomerOrdersByProduct, even when debugging, or in just intellisense.. What am I missing please?
thanks.
A: It sounds like your OrdersDataTable's row type doesn't have an OrderId property, even though the stored procedure is returning it.
Look at the design for OrdersDataTable, which I assume is a generated strongly-typed datatable. Perhaps you've mapped it to an Id property instead of OrderId, or something like that? Either way, I very much doubt that this is anything to do with LINQ directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7582257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.