text
stringlengths
8
267k
meta
dict
Q: Bind Dynamically Created Bitmap object to Image in WPF I have a bitmap object that is not a static resource. Normally, with image binding in WPF you can bind to a string path. However, I have a dynamically created bitmap object that I would like to bind to. Is it possible to do something like: <WrapPanel x:Name="imageWrapPanel" HorizontalAlignment="Center"> <Image Source="{Binding Material1}" Margin="10" /> <Image Source="/NightVision;component/Images/concrete_texture.tif" Margin="10" /> </WrapPanel> And in the code behind file I have a public accessor: public Bitmap Material1 { get { return new Bitmap(/* assume created somewhere else*/) } } The above is obviously not working however, is there a way to do something similar? A: The only thing you need to do is convert the Bitmap to an ImageSource which can be used in the Image control. So in your binding you can add a Converter which accomplishes that. The implementation of the conversion is likely to be found in the answers to this question. (If you have a chance to work directly with BitmapImage (WPF) instead of Bitmap (WinForms) that might be quite a good idea)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Changes in CvRect values not being reflected in image The minimum bounding rectangle of a contour is returned by OpenCv as a CvRect structure. I'm trying to have an m pixel thick margin/border around the sub-image that corresponds to this CvRect on the original image, i.e. instead of the exact bounding rectangle of a component(contour) we get something larger containing the component and also its immediately surrounding pixels. Taking care of the image bounds, I'm using the following code to increase size of the CvRect which is later applied with CvSetImageROI() to get the sub-image: //making m px border around subimg CvRect box_swt = box1; box_swt.x = (box1.x)>m ? box1.x-m : box1.x; box_swt.y = (box1.y)>m ? box1.y-m : box1.y; box_swt.width = (box1.x + box1.width) < img->width-m ? box1.width+m : box1.width; box_swt.height = (box1.y + box1.height) < img->height-m ? box1.height+m : box1.height; Here, box1 stores the return from cvBoundingRect(ptr, 0) where ptr is a pointer to detected contours. The problem is that the resulting sub-image is larger only in the upper and left borders, the others remain unchanged. I'm not getting a sub-image with a uniform m pixel thick border around all its sides. This happens for all cases, not just for those on the boundary. Is there any logical error? A: When you are modifying the x and y of the rectangle you are not increasing it's size, just moving it, and then you increase the width and the height by just m. I think what you want is to increase it by 2m to have the desired effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Client/Server to stream logfile updates in realtime? We have applications on Solaris 10 servers that generate text logfiles. We need to stream these logfiles in realtime to a central server for monitoring of new events. Ideally we'd have a NFS-mount, and all our system would write their logs to there, and the monitoring server could just pull them up from there. Unfortunately, for technical and non-technical reasons that's not an option here. At the moment, we're using a backgrounded tail -f to pipe the data over an SSH tunnel. However, we were looking at whether it's worth putting together something a bit more robust. I was thinking of writing a simple Python client/server with Twistedb (or something similar - recommendations?) to stream the log data. Is this something that's easily achievable? Any existing libraries/tools I could look to for ideas? Any issues I should be aware of? Also, this is Solaris 10, so I'm not familiar with the state of filesystem monitors. I do know Gamin is available via OpenCSW. however, are there any other choices out there? A: Check out Python's logging module. http://docs.python.org/library/logging.html It contains the capability to log to files, streams, syslog, networked servers, and more. The cookbook contains examples or logging over the network. http://docs.python.org/howto/logging-cookbook.html#logging-cookbook The module is fairly easy to extend also. A: Do consider zeromq, instead of raw sockets. Its no message broker server, its a library to let you write your message passing system. It enables easy cross-platform and language-agnostic communication over TCP, IPC (yes,inter-process!), multicast and other protocols. Simply swap a python component with a C component and it just works as before. Its the perfect software to satisfy your "..excuse to learn.." ;-) But the show-stopper would be building it in your Solaris setup. Python bindings are at http://pypi.python.org/pypi/pyzmq/2.1.9
{ "language": "en", "url": "https://stackoverflow.com/questions/7563560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ABPeoplePickerNavigationController saving larger image takes a LONG time I use ABPeoplePickerNavigationController to import iPhone Contacts into my app. I recently decided, instead of just saving the thumbnail image, to save the entire image as well. With iPad and possibly needing larger images with different cropping, I think this is the way to go. However, when saving some new contacts after importing, the save is LONG, depending on the size of the photo. No photo and the save is immediate, so I know it has to do with the size of the photo and what I am doing with it. Relevant code is below in case anyone can point out what I am doing wrong... - (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)contact { NSLog(@"%s", __FUNCTION__); self.selectedThumbnailImage = nil; self.selectedImage = nil; if(ABPersonHasImageData(contact)){ self.selectedThumbnailImage = nil; NSData *imgData = (NSData *)ABPersonCopyImageData(contact); UIImage *pickedImage = [UIImage imageWithData:imgData]; [imgData release]; self.selectedImage = pickedImage; CGSize imageSize = pickedImage.size; CGSize targetSize = CGSizeMake(110.0,120.0); CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor > heightFactor) scaleFactor = widthFactor; // scale to fit height else scaleFactor = heightFactor; // scale to fit width scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // center the image if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [pickedImage drawInRect:thumbnailRect]; self.selectedThumbnailImage = UIGraphicsGetImageFromCurrentImageContext(); [[NSNotificationCenter defaultCenter] postNotificationName:@"personChanged" object:nil]; UIGraphicsEndImageContext(); } self.nameFirstString = (NSString *)ABRecordCopyValue(contact, kABPersonFirstNameProperty); self.nameLastString = (NSString *)ABRecordCopyValue(contact, kABPersonLastNameProperty); [nameFirstTextField setText:nameFirstString]; [nameLastTextField setText:nameLastString]; self.person.birthday = (NSDate *)ABRecordCopyValue(contact, kABPersonBirthdayProperty); [self updateRightBarButtonItemState]; [self dismissModalViewControllerAnimated:YES]; return NO; } - (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{ NSLog(@"%s", __FUNCTION__); return NO; } - (void)saveImage { // Delete any existing image. NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext]; Image *oldImage = person.image; if (oldImage != nil) { [context deleteObject:(NSManagedObject*)oldImage]; } // Create an image object for the new image. UIImage *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:context]; [newImage setValue:selectedImage forKey:@"image"]; [self.person setValue:newImage forKey:@"image"]; } - (IBAction)save:(id)sender { NSLog(@"%s", __FUNCTION__); [self.person setValue:selectedThumbnailImage forKey:@"thumbnailImage"]; [self saveImage]; self.person.nameFirst = nameFirstString; self.person.nameLast = nameLastString; NSError *error; NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext]; if (![context save:&error]) { NSLog(@"AddPersonViewController - addViewControllerDidFinishWithSave - Person MOC save error %@, %@", error, [error userInfo]); exit(-1); // Fail } [self.delegate addPersonViewController:self didFinishWithSave:YES didEditPerson:person]; } EDIT: I changed the saveImage code to the following and got the error 'Illegal attempt to establish a relationship 'person' between objects in different contexts': - (void)saveImage { // Delete any existing image. //NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext]; NSLog(@"%s", __FUNCTION__); NSManagedObjectContext *savingPhotoContext = [[NSManagedObjectContext alloc] init]; self.savingPhotoMOC = savingPhotoContext; [savingPhotoMOC setPersistentStoreCoordinator:[[[UIApplication sharedDelegate] managedObjectContext] persistentStoreCoordinator]]; [savingPhotoContext release]; Image *oldImage = person.image; if (oldImage != nil) { [savingPhotoMOC deleteObject:(NSManagedObject*)oldImage]; } // Create an image object for the new image. UIImage *newImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:savingPhotoMOC]; [newImage setValue:selectedImage forKey:@"image"]; [newImage setValue:self.person forKey:@"person"]; //[self.person setValue:newImage forKey:@"image"]; NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter]; [dnc addObserver:self selector:@selector(addControllerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:savingPhotoMOC]; NSError *error; if (![savingPhotoMOC save:&error]) { NSLog(@"Occasion View Controller - addViewControllerDidFinishWithSave - Adding MOC save error %@, %@", error, [error userInfo]); exit(-1); // Fail } [dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:savingPhotoMOC]; self.savingPhotoMOC = nil; }- (void)addControllerContextDidSave:(NSNotification*)saveNotification { NSLog(@"%s", __FUNCTION__); NSManagedObjectContext *context = [[UIApplication sharedDelegate] managedObjectContext]; [context mergeChangesFromContextDidSaveNotification:saveNotification]; } A: If it takes long, you should do this the background and either use delegate callback or nsnotification to inform other functions that might be using it when the save is done. you can use GCD or nsoperationqueue...for gcd have a look at 'fiery robot's blog. I like it because he explains things not just give code for copy pasting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display post date on previous/next link I am about modifying the previous post (and next post) link in Wordpress. but I don't know how to show the date of the referred post. I don't want an external plugin for this answer, but the code in functions.php will be great. (Note: I have read this. if this is the answer how to use it in very practical code?) the final result should be like this: < Previous (12 June 2011) | Current Post | (14 June 2011) Next > A: The following code will output the link in the correct format from your single.php template: <?php $prev_post = get_previous_post(); ?> <a href="<?php echo get_page_link($prev_post->ID); ?>">&lt; (<?php echo mysql2date('d F Y', $prev_post->post_date, false) ?>) Previous</a> I'll leave the next link as an exercise for you. A: <?php echo get_the_date( 'd/m/Y' ); ?> this will also show the date even posts within a day
{ "language": "en", "url": "https://stackoverflow.com/questions/7563568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse CDT not recognizing some GL functions, but compiles fine I'm having a problem using Eclipse CDT, where it does not recognize some OpenGL functions. I have the header included from /Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/OpenGL.framework/Headers Some functions/enums are recognized by the indexer, some are not and provide no auto-completion. However if I command+click any of them (red or regular) I am taken to the proper file (GL.h) and the correct location of the function I've checked, and those enums are indeed defined in that header. Again compiles fine, but no code-completion provided, and areas are marked red as if wrong. A: I get the same error quite often as well. Sometimes cutting the faulty line & pasting it back helps, but if that doesn't solve the issue a restart of Eclipse worked for me in all cases until now. And the last resort solution to all Eclipse issue that cannot be resolved otherwise: Recreate the workspace and project, and copy only the source files into the new workspace. This has fixed most weird issues of Eclipse for many people, including myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery 1.5.0 to 1.5.1 breaks previous script I needed to update my jQuery library for some bugs that IE9 has with <= v1.5.0. Upgrading the library to 1.5.1+ (even at current 1.6.4) breaks some script that I have on the page, though... (so of course, fix one issue, cause another)... The script allows the user to add and subtract a group of input boxes (so, if they want to input a single line item, they do just that... but they can add unlimited amount of additional line items). //ADDS ANOTHER USER $(".add-user").click(function() { onemore = $("#userSelectBoxes").clone(); onemore.find(":input").each(function() { $(this).val(""); }); $("#user_block > #userSelectBoxes:last").after(onemore); set_add_del(); return false; }); $(".removeable").click(function() { $(this).parent().remove(); set_add_del(); return false; }); function set_add_del() { $('.remove_cat').show(); $('.add_cat').hide(); $('.add_cat:last').show(); $("#user_block > #userSelectBoxes:only-child > .remove_cat").hide(); } The add and remove buttons, in the HTML are as follows (and they just add another DIV of input fields basically): <a href="#" class="remove_cat removeable">-</a> <a href="#" class="add_cat add-user">+</a> So with 1.5.0 - this would work properly, and let me click + or - unlimited amount of times and always function. With 1.5.1+, I can click the + ONCE, then nothing else works (adding OR deleting). Any ideas? Hopefully I included all that would be needed here... UPDATE 9/27/11 @ 5:05 PM EST I followed the suggestions in the comments below. No luck. It actually performs exactly the same... I should note that when I click for the 2nd time, not only does it no work (as I stated earlier), but it will pop me back up to the top of the screen as well. Here is the latest code... $(".add-user").click(function(){ onemore = $(".userSelectBoxes").first().clone(); onemore.find(":input").each(function(){ $(this).val(""); }); $("#user_block > .userSelectBoxes:last").after(onemore); set_add_del(); return false; }); $(".removeable").click(function(){ $(this).parent().remove(); set_add_del(); return false; }); function set_add_del(){ $('.remove_cat').show(); $('.add_cat').hide(); $('.add_cat:last').show(); $("#user_block > .userSelectBoxes:only-child > .remove_cat").hide(); } A: You can use two different versions of jQuery on a page. You'll need to call .noConflict() after loading the second version of the library. This will reset the value of the $ object to the first version of the library. Documentation <script type="text/javascript" src="jquery.1.5.0.js"></script> <script type="text/javascript" src="jquery.1.5.1.js"></script> <script type="text/javascript"> $.noConflict(); //'$' now refers to 1.5.0 //'jquery' now refers to 1.5.1 </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Validation always returns true I have this html; <form action="" method="post" name="ApplyForm" id="ApplyForm" enctype="multipart/form-data"> <input type=text class="required"/> <input type="submit" onclick="return validateForm()" class="submit" value="Submit Application" title="Submit application" /> and my script; $(function () { $("#ApplyForm").validate(); }); function validateForm() { alert($(".email").valid()); return false; } So what's happening is if I alert out alert($("#ApplyForm").valid()); I always get true yet if I alert out the individual fields I get the expected results but the form still posts back; this code works but I am unsure why the validate is not working on the form; function validateForm() { if ($(".required").valid() == 0) return false; else return true; } I know this isn't much to go on but I'm hoping someone else has had this experiance and can tell me a solution. A: <form action="" method="post" name="ApplyForm" id="ApplyForm" onSubmit="return validateForm()" enctype="multipart/form-data"> <input type=text class="required"/> <input type="submit" class="submit" value="Submit Application" title="Submit application" /> A: Try adding a name attribute to your first validated element within the form: <input type=text required name='blah' /> I spent 2 hours tracking down this same issue, and I found that if the FIRST validated element in the form has a name attribute then everything works as you would expect (that is, .valid() will return false if the form is invalid). It seems to make no difference whether the other validated elements have name attributes or not. In normal forms, you definitely need name attributes because that's what's used when the data gets submitted to the server. But in more modern environments, such as those using Knockout, there's no reason to have a name attribute on input elements, because the data-binding works to keep your data model updated. A: You should add <input type="text" data-val="true" name="name" data-required="1"> For unobtrusive HTML 5-compatible attributes describe the validators to be attached to the input fields Additional info Click here
{ "language": "en", "url": "https://stackoverflow.com/questions/7563586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: field width while using delayed expansion I am using a for loop and constructing names of env variables ( like abc%%i , where i is the loop variable ) that are to be read , and use delayed expansion to print out their values (assuming these env variables have already been set ) .. echo is dos provides the facility to mention the field width of the variable to be printed out like echo %x:~-8% will right justify the value of x and the field width will be 8 .. But since i am using delayed expansion , !abc%%i:~-8! does not seem to be working . Any ideas as to how to set field width while using delayed expansion ,?? Happiness Deepak A: I don't know who told you that %x:~-8% would pad out your variable but they're wrong, at least in the version of cmd that I'm using (XP). That construct will simply give tou the last 8 characters if the variable is 8 or more. If it's less than 8, you'll get the variable itself, sans padding. If you want it padded, you can use something like: set y= %x% echo %y:~-8% And, as can be seen from this script, !abc%%i:~-8! works just fine once you realise that you're responsible for the padding: @setlocal enableextensions enabledelayedexpansion @echo off for /f %%i in ('echo 1 ^&^& echo 92') do ( set var%%i= %%i echo !var%%i:~-8! ) echo.===== set var endlocal This outputs: 1 92 ===== var1= 1 var92= 92 as you would expect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to logging data change with Entity Framework, otherwise how to do it with SQL Server 2008 Standard? I use SQL Server 2008 Standard, Asp.net MVC 2 and Entity Framework 4.0 I would like to know the best and simplest way to log data change. I read a little bit about change data capture and seem to be very interesting. I just wanted to know if I can log directly with Entity Framework. I have a total of 170 entities. If possible, is there a generic method to perform my needs ? Thanks a lot everyone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to persist data in a broadcast receiver I have a simple broadcast receiver which receives some data which I would like to store for the application to use on next launch. It is just a few strings so simplicity is the goal. Normally I'd just write to to a file or sharedPreferences but not being an activity that seems incorrect. Thoughts? -- Henry A: Saving into SharedPreferences is perfectly fine. You have a Context to access it from as it is passed into the BroadcastReceiver.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Actionscript broken? My Flash is a little strange, I doesn't recognize the UILoader I'm importing, actually when I type import fl.c it doesn't suggest the container library, was this deleted in AS3 or is flash just broken? package { import flash.display.MovieClip; import fl.containers.UILoader; public class Tarjetas extends MovieClip { public function Tarjetas() { var loader:UILoader = new UILoader(); } } } A: UILoader is a component (like FLVPlayback) which means the component itself needs to be added to your library for the above to work. This may help: http://livedocs.adobe.com/flash/9.0/main/flash_as3_components_help.pdf
{ "language": "en", "url": "https://stackoverflow.com/questions/7563595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check for existence of a row in mysql without using INSERT IGNORE? I currently use this query to update listings in my database from my php app: $query = "INSERT INTO listings (title, description) VALUES ('$title','$description')"; This listings table has a 'postid' column as it's primary key that auto increments. I don't want to do an INSERT IGNORE and have it check postid. Instead, I'd like to keep the table structure the same and check to see if $title exists.. and not insert if it does. Will php/mysql allow me to somehow run a: If ($title does not exist) { $query = "INSERT INTO listings (title, description) VALUES ('$title','$description')"; } If so, how would I write that? A: You can do the dollowing: Query your database to see if there is already any list with the given title and if the count query returns 0, execute your insert statement: $result = mysql_query('SELECT count(*) as total from listings where title="$title"'); $result = mysql_fetch_array($result); if($result['total'] == 0){ $query = mysql_query("INSERT INTO listings (title, description) VALUES ('$title','$description')"); } But I strongly suggest you to do not manipulate your database this way. Better to use an ORM or a database class instead of putting your SQL statements all over the place. Good luck. A: Try this: INSERT INTO listings (title, description) VALUES ('$title','$description') FROM dual WHERE not exists (SELECT title FROM listings WHERE title = '$title'); Or you can do like this: $result = mysql_query("UPDATE listings SET description = '$description' WHERE title ='$title';"); if (mysql_affected_rows() == 0) { $result = mysql_query("INSERT INTO listings (title, description) VALUES ('$title','$description');"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can Spring Security validate the relationship between user? I am new to Spring Security. Can Spring Security validate the relationship between users? for example: I have two users type. one is teacher, another one is student. I wanna validate whether this student have relationship with the special teacher. Then the student can do some operation with this special teacher. Can spring security achieve this goal? Please provide me some reference, keyword, or link then i can do more study Thx A: At its core, this doesn't sound like a Spring Security issue - its data related. If this is a relationship that is stored in your DB, and you are using an ORM, then there should be a OneToMany relationship between the Teacher and the Student (and ManyToOne conversely). If you want to track some additional information about a logged-in user (say, their primary Teacher) in the Spring Security context, then you need to implement the UserDetailsService and extend the Spring Security User object with your additional data. A: Security issues can be categorised as authentication or authorization issues. Your issue is an authorization issue. But it is not a static authorization problem, since it is not caused due to the configuration of rights and roles of the user, but it is a dynamic one since it has to do with the student being related to a teacher in order to be authorised to execute some specific action. What you need is to inject the spring security which business checks that provide a positive flag each time this relation is satisfied. If I undestood you problem well perhaps you might need to read and understand about AccessDecisionManager class from Spring Security.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do you put wordpress post images into list items I want to take the images in my wordpress single page post and put them in a list order. The purpose is to then create a custom slider off of that list. or if someone knows a good image slider for wordpress that has dynamic heights let me know. A: Actually, there are plenty of sliders either the wordpress plugin or jquery plugin. My recommendation is the jquery plugin named Coda slider where it can be modified to be used even on the div
{ "language": "en", "url": "https://stackoverflow.com/questions/7563603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cross PDO driver compatible GROUP_CONCAT? Is there an efficient alternative to GROUP_CONCAT that works in the major PDO drivers? A: Given this MySQL: select group_concat(c separator ',') from t you could do this in PostgreSQL: select array_to_string(array_agg(c), ',') from t or this in SQLite: select group_concat(c, ',') from t I don't know about SQL Server though. References: * *MySQL group_concat *PostgreSQL array_agg *PostgreSQL array_to_string *SQLite group_concat
{ "language": "en", "url": "https://stackoverflow.com/questions/7563604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse content assist auto-activation for CSS? I found there is content assist auto-activation option for Java, JavaScript and XML. But not for CSS. So I have to type Ctrl+Space like crazy. Any way to make the auto-completion box show up automatically? A: You'll have to open a feature request in Bugzilla for this. http://bugs.eclipse.org/
{ "language": "en", "url": "https://stackoverflow.com/questions/7563608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I parse magnetic strip card data input in Java Swing textbox? I'm trying to write an application which will search and retrieve a user's profile using data using an id key found using a scanned barcode or embedded in a magnetic strip card's data. The latter one is cause me grief. The magstripe data needs to be parsed prior to searching for the user profile. My question, is there a way to capture the text scanned into the textbox and parse it before it gets displayed in the textbox? My reader/scanner is the keyboard emulation type so its as if each character encoded on the stripe is typed out in the textbox. I guess a solution (but is it the best?) would be to intercept each keystroke (emulated by the magnetic stripe reader), store them in a buffer and display an empty character until the end of the read string. Once the end of card's data is read, I could parse and display the id part of id. Problem is... how do you know it's the end of the card's data string if they get inputted as individual char keystroke? A: You should be able to use a Document Filter to intercept the text as it is added to the Document of the JTextField. Then when you receive the end of string character you can parse the text and insert it into the text field. A: Answer to your first question is to set a DocumentFilter on the Document of the textfield. ..how do you know it's the end of the card's data string if they get inputted as individual char keystroke? Your MSR would surely emit a START_STRING and an END_OF_LINE_STRING as a combination of some predefined characters. Read the data specification of the MSR device. Once you have that, you could implement the insertString of the filter similar to this pseudo code if str == START_CHARACTER then clear buffer if str == EOL_CHARACTER then parse and do super.insertString else append string to buffer Again, the parse logic can be implemented using the data specification of the MSR. (MSR = Magnetic Stripe Reader)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't spawn "cmd.exe" I use a program called LF-Aligner that uses dictionaries to make parallel texts out of texts in different languages. I believe it's written in Perl. It's based on another program called Hunalign. When I used it a few months earlier, it worked perfectly. It got accidentally deleted, I recently reinstalled it, but now I just get the error message: Aligning... Dictionary used by Hunalign: es-en.dic Can't spawn "cmd.exe": No such file or directory at script/LF_aligner_2011_06_29_multi.pl line 1856. Use of uninitialized value $alignedfilesize in numeric eq (==) at script/LF_aligner_2011_06_29_multi.pl line 1864. ------------------------------------------------- Align failed (probably due to one file being empty or very short). ABORTING... I can't understand it. Could it be a conflict with something I've installed in the meantime? Or something I've deleted, maybe? (The problem is not due to "one file being empty or very short", as the program suggests. The files are just fine.) EDIT: Here is the log file: Program: LF aligner, version: 2.56, OS: Windows, launched: 2011/09/28, 04:13:01 Setup: filetype_def: t; filetype_prompt: y; l1_def: en; l2_def: hu; l1_prompt: y; l2_prompt: y; segmenttext_def: y; segmenttext_prompt: y=; cleanup_def: y; cleanup_prompt: y; review_def: x; review_prompt: y; create_tmx_def: y; create_tmx_prompt: y; l1_code_def: EN-GB; l2_code_def: HU; l1_code_prompt: y; l2_code_prompt: y; creationdate_prompt: y; creationid_def: ; creationid_prompt: y; ask_master_TM: n; chopmode: 0; tmxnote_def: ; tmxnote_prompt: y; pdfmode: y GUI on filetype: t Input file 1: kakeen.rtf (C:/Users/jippi/Desktop/qewr/kakeen.rtf) Input file 2: kaketo.rtf (C:/Users/jippi/Desktop/qewr/kaketo.rtf) Input file sizes: 1375014 bytes 1375014 bytes Converting rtf files to txt; AbiWord binary: C:\Program Files (x86)\LF_aligner_2.56\aligner\scripts\abiword\bin\AbiWord.exe Converting rtf files to txt; AbiWord binary: C:\Program Files (x86)\LF_aligner_2.56\aligner\scripts\abiword\bin\AbiWord.exe File sizes after conversion to txt: 1074504 bytes 1074504 bytes Initial stats: - en: 6091 segments, 196644 words, 1037434 chars - en: 6091 segments, 196644 words, 1037434 chars Segmentation: y (The problem occurs when I use txt-files aswell.) A: I downloaded the application in question. It is a Perl application packed using pp. To see the code in question, unzip the downloaded file and then extract the contents of the executable using E:\Home\Downloads\LF_aligner_2.56_win\aligner> unzip LF_aligner_2.56.exe -d some-temp-dir You'll find the file some-temp-dir\script\LF_aligner_2011_06_29_multi.pl Line 1856 is: system ("\"$hunalign_bin\" -text \"$scriptpath/scripts/hunalign/data/$hunalign_dic\" \"$folder/$file1\" \"$folder/$file2\" > \"$folder/aligned_${alignfilename}.txt\""); which is messy to say the least. The program does not check if the system succeeded. Because the system fails, the subsequent attempt to read the size of the output file also fails (note the warning) and subsequently, the program realizes something went wrong: # SEE IF ALIGNED FILE IS OK, ABORT IF NOT my $alignedfilesize = -s "$folder/aligned_${alignfilename}.txt"; if ($alignedfilesize == 0) { print "\n\n-------------------------------------------------"; print "\n\nAlign failed (probably due to one file being empty or very short). ABORTING...\n\n"; print LOG "\nAligned file empty, aborted."; None of this solves your problem, but gives you something to investigate if you feel like it. At the very least, you might want to notify the author of the program. The way the author handles paths is too messy for anyone else to feel really motivated to investigate. A: Are you launching it from the %WINDIR%\system32 folder? Did you check to see if the PATH environment variable was modified by the installation? A: I'm the author of LF Aligner. Frankly, I'm a bit baffled by the "can't spawn cmd.exe" error. Unless that's some incorrect error message, then the problem seems to be outside of LF Aligner itself. You could try and see if the error is indeed due to one file being much shorter than the other. This would cause Hunalign to abort as it's impossible to do a reasonable job of pairing up the sentences, and then LF Aligner stops with the error message you posted. Other than that, it could be some bug in Hunalign (unlikely) or LF Aligner (a bit less unlikely, but I'd still be surprised). As a test, try to align two files that are of the same size, e.g. the same file under two different names. I could try and do some troubleshooting, let me know which script you are using (and which version). Posting the log file wouldn't hurt, either. Re: the comments on code quality; I'm not a professional programmer and this is a hobby project. I know it's messy and inelegant, but it works. A: There are multiple reasons why you may get Can't spawn "cmd.exe": ... with Perl on Windows (that is, assuming that you can successfully invoke cmd.exe from a command prompt or from +R to begin with): * *As pointed out previously, PATH may not exist (or no longer exist) in Perl's environment at the time of system/`STRING` invocation, or it may be that PATH is malformed, or that none of the directories in PATH actually contain a cmd.exe at the time of system/`STRING` invocation *PATH may exist and one of the directories therein may contain cmd.exe (or some cmd.exe), but there may be other issues with that particular cmd.exe (e.g. permission issues, DLL issues, etc.) *The invocation of cmd.exe actually succeeded, but some other executable in the command line you passed to system/`STRING` (and spawned as a child by cmd.exe, e.g. hunalign.exe) died abnormally (without invoking DrWatson) and returned an exit code (such as the exception value for an unhandled exception that caused the process to terminate) that Perl then misinterpreted as a misfire of cmd.exe itself You can easily pinpoint which of the scenarios above using Process Monitor. Start by setting up a filter in Process Monitor to include events where Path contains cmd.exe and Event Class is File System as well as Event Class is Process. * *Has Windows looked for cmd.exe (looking at e.g. IRP_MJ_CREATE) in all directories normally present in PATH up to and including e.g. C:\windows\system32 (or C:\windows\SysWOW64 as the case may be)? *If Windows has located C:\windows\system32\cmd.exe (or C:\windows\SysWOW64\cmd.exe as the case may be), is there anything other than SUCCESS in the Result column? (e.g. indication of permission issues?) Is there a Create Process event for cmd.exe that succeeded? A Load Image event that succeeded? *Writing down the PID number from the Detail column corresponding to the successful Create Process event, and disabling the filters I mentioned above replacing them with a single PID is filter, what is the value for Exit Status in the Detail column corresponding to the Process Exit for the written down PID; is it e.g. e negative value such as -1073741819 (0xc0000005)? A: Sorry, I know this is super-old and maybe it has already been answered, but I've just found out on Windows if you use the built-in Perl function system() to spawn an executable, and that executable then returns a negative exit value, Perl spews out that erroneous Can't spawn ... message. I'm using Perl v5.14.2, so this may or may not have been fixed in a later Perl version. A: this means the Path c:\windows\system32 is missing in you system environment variable, in order to solve this problem,go to my computer\properity\advance\environment variable,go to the table system variable, edit path, add the path c:\windows\system32 A: Found this answer on another site, seems the %SystemRoot% variable doesn't always get expaneded in perl, so you need to set the exact path. The below explanation is from this 'greenstone' software wiki, but can be generalized for the problem you're having here. Windows Building error: can't spawn cmd.exe When building a collection in GLI on Windows, if you see an error message like the following in the build log output: Can't spawn "cmd.exe": No such file or directory … then try the steps below. This error has been reported by some users. It appears to occur because %SystemRoot%, an environment variable used in the %PATH% which evaluates to C:\windows, isn't being passed in to the perl code from GLI. As a result, the PATH does not contain c:\windows\system32 which contains cmd.exe used by perl to execute commands. However, this problem does not appear to manifest for all Windows users of Greenstone. The solution that has worked for the 2 members of the mailing list who reported this problem is as follows. * *In a text editor, open the file gli.bat which is located in your Greenstone installation's "gli" folder *Near the top, just after set GLILANG=en add the following line: set PATH=c:\windows\systems32;%PATH% The above manually prefixes c:\windows\systems32; to the PATH during GLI's execution. *Now try running GLI and building the collection again. A: I faced this issue when my folder had "-" or hyphen in its name, probably perl interpreted this as a command instead of folder name, replaced the hyphen with underscore and it started working fine. A: Make sure your perl 32/64bit version and your starting cmd version match. I had the same problem, and for me It was executing a 64-bit perl version inside a 32-bit cmd.exe. Then, the perl script tried to do a system call, and at that point, it failed with the Can't spawn "cmd.exe" message. When using a 32-bit perl, all worked. A: PATH was already checked, but I got the same error with our software and you can reproduce it with the following: c:\temp>set path=C:\Windows;C:\%SystemRoot%\system32;C:\Windows\System32\Wbem c:\temp>perl -w -e "system('dir', 'C:\\');" Can't spawn "cmd.exe": No such file or directory at -e line 1. The problem is, that "cmd.exe" could not be found in the PATH... I think unexpanded variables could be a general problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Performance of rendering a bitmap using an image transform matrix on an ImageView Basically, I want to render an image (bitmap) on an ImageView, but change its image transform matrix quite rapidly. I'm new to android development and I'm not sure if what I'm doing is the right thing or not. I'm currently doing this by: myImageView.setImageResource(resource_id); // only once myImageView.setImageMatrix(myMatrix); // many times The problem is that the rendering takes a lot of time - about 12 to 63 milliseconds depending on the visible area after the transform. Does this use hardware acceleration? Is there a way to make it faster? Do I have to move to OpenGL (which I know nothing about)? Where do I start if I do (OpenGL 1.0/2.0)? Thanks! A: Android supports Hardware Acceleration starting in Honeycomb which is for tablets only. It will carry over into Ice Cream Sandwich (not out yet). Before that you will always be running in a software renderer. Google has provided a nice breakdown of some of the device specs from what is being using in the Android Market. For the custom animation you might want to check out the View Animation framework that already exists. Careful there's a new much better Property Animation framework introduced in Honeycomb as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Core Data loading in background problem I have setup few methods to load core data in the background using NSOperationQueue, like the below: operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(selectToLoadDataOne) object:nil]; operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(selectToLoadDataTwo) object:nil]; The "selectToLoadDataOne" and "selectToLoadDataTwo" is just standard NSFetchRequest using the template NSManagedContext from app delegate. Problem is that after loading a few times, it just stop loading altogether and stuck at executeFetchRequest: and without any error. I know this is related to using of threads with core data, and so I tried to create a new nsmanagedobjectcontext for each call but the result returned are empty nsmanagedobject. Can someone point me to a good example or doc I can use to solve the loading of core data from background thread? A: Core Data has very specific rules about running on multiple threads. You must have one NSManagedObjectContext per thread and the thread that a NSManagedObjectContext will be used on must be the thread that creates it. You are running into issues because you are breaking that rule. Instead of using a NSInvocationOperation: * *create a subclass of NSOperation *pass in the NSPersistentStoreCoordinator *create the NSManagedObjectContext in the -main Of course that is only going to load them into the NSPersistentStoreCoordinator and you are still going to need to reload them in the main NSManagedObjectContext. Why do you need to load data on a background thread? Looking to speed up data loads is usually indicative of a deeper issue in the app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issues with Rails gem mysql2 on OS X 10.7 with Ruby 1.9.2 and Rails 3.1 OS Version: Mac OS X 10.7.1 Lion Ruby Version: ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.1.0] Ruby Location: /usr/local/rvm/bin/ruby Rails Version: Rails 3.1.0 Rails Location: /usr/local/rvm/gems/ruby-1.9.2-p290/bin/rails Now, I installed the mysql2 gem and when I run gem list it shows up in the list as: mysql2 (0.3.7) So far so good, right? OK, so here's where it gets tricky. No matter what I do, I can't start the server. In terminal I cd to the directory my rails app is and run rails s. However, instead of starting i get this: /usr/local/rvm/gems/ruby-1.9.2-p290/gems/mysql2-0.3.7/lib/mysql2.rb:9:in `require': dlopen(/usr/local/rvm/gems/ruby-1.9.2-p290/gems/mysql2-0.3.7/lib/mysql2/mysql2.bundle, 9): Library not loaded: libmysqlclient.18.dylib (LoadError) Referenced from: /usr/local/rvm/gems/ruby-1.9.2-p290/gems/mysql2-0.3.7/lib/mysql2/mysql2.bundle Reason: image not found - /usr/local/rvm/gems/ruby-1.9.2-p290/gems/mysql2-0.3.7/lib/mysql2/mysql2.bundle from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/mysql2-0.3.7/lib/mysql2.rb:9:in `<top (required)>' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `block (2 levels) in require' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `each' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `block in require' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `each' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `require' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler.rb:120:in `require' from /Users/doug/Sites/simple_cms/config/application.rb:7:in `<top (required)>' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:52:in `require' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:52:in `block in <top (required)>' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:49:in `tap' from /usr/local/rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.0/lib/rails/commands.rb:49:in `<top (required)>' from script/rails:6:in `require' from script/rails:6:in `<main>' Obviously, this is not what should be happening. The problem is I can't figure out why not. None of the solutions I've come across have worked. This is actually my first attempt at getting Ruby/RoR working on my computer. I'm following a tutorial from Lynda.com and, unsurprisingly, this doesn't happen to the guy doing the videos. I've tried searching and, as I said, nothing seems to help. Ideas? A: install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib ~/.rvm/gems/ruby-1.9.2-p290@[gemset name]/gems/mysql2-0.3.7/lib/mysql2/mysql2.bundle [gemset name] = the name of the gemset you are using -- if you didn't set one then you should set it as that is one of the main points of getting rvm hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7563632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lite/Pro version vs In-app-billing upgrade option I have free version with limited functionalities&ads and paid ver. with full features with no ads. I'm wondering, Should I make different ver. of app paid/free and upload it to market or Lite version and IN-APP-PURCHASE to upgrade to pro version? What should be the best choice in this case? if you can give insights of pros and cons of IAP and pro/lite method would be great. 1Q: if user installs free ver. > makes in-app-purchase > uninstall If he downloads it again then will he clicks in-app-purchase. Will Market ask him for money again (since he already paid? ref: IAP android. A: Not really a programming question, the best choice depends on many things. In short, IAB is a bit harder to integrate, but may provide a better user experience: no need to install a separate app, and uninstall the free one later, etc. Maybe you should read the IAB reference first to get an idea how it works. As for your question, if you use a managed item, the purchase is tied to the user's Google account, so they will get the upgrade after moving to a new device for free (you need to restore transactions on first run to ensure this happens). A: You could also use a license key like DocumentsToGo. The user has to download a 2nd app but you can even set it so it doesn't show up in the app drawer, basically the user wouldn't really notice that he DLs another app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Working with 2 html5 Localstorage apps problem So I've been working with 2 different Localstorage application for a task I've been given. The one is a todo list and the other one is notes which both work on the same html file. Now, the todo list have 3 localstrorage keys. One for the value of the todo. Second for the order of the todo's (which is first, sec, third etc) and Third how many todo's you have in general. So thats 3 different values. For the notes is 1 localstorage Key with all its values. (see image below) Now the problem is: If for example I have 3 notes and then I add a todo I get this on the localstorage: which this is working fine. But, if I add another two notes, I get this: which is logical although the last two notes doesn't show. Another example: This will not show any notes although there are 4. I'm not sure how to explain this but basically what happens is that what ever is written on the localstorage after a todo-ID, doesn't show but note that the todoList keeps working perfectly. I'm not pretty sure what the problem is but what I think it could be its the way the keys are being loaded. maybe ??? So here is how I load the notes: var initStickies = function initStickies() { $("<div />", { text : "+", "class" : "add-sticky", click : function () { createSticky(); } }).prependTo(document.body); initStickies = null; }, openStickies = function openStickies() { initStickies && initStickies(); for (var i = 0; i < localStorage.length; i++) { createSticky(JSON.parse(localStorage.getItem(localStorage.key(i)))); } } and this is how I load the todo-list: orderList = localStorage.getItem('todo-orders'); orderList = orderList ? orderList.split(',') : []; for( j = 0, k = orderList.length; j < k; j++) { $itemList.append( "<li id='" + orderList[j] + "'>" + "<span class='editable'>" + localStorage.getItem(orderList[j]) + "</span> <a href='#'>X</a></li>" ); } What the problem could be? Does anyone had this problem before? Thanks alot for reading and sorry for the big post. I'm trying to be as clear as possible. I've been thinking how to fix this for really long time and im coming to a dead line. Hope someone can help me. Thanks again A: In your notes app, you try to iterate through every item in localStorage and parse them as JSON. When it gets a JSON string, it successfully parses it and continues its work. When it gets your todo item, it breaks and stops working. If you want to have both todo and note in one localStorage, you'd better have some way to tell the difference. One simple way is to have todo- as prefix for todo item (as you've alreayd done) and note- as prefix for note item. One possible quick fix for your code is to use try ... catch ... to avoid non-JSON string breaking your iteration: for (var i = 0; i < localStorage.length; i++) { try { createSticky(JSON.parse(localStorage.getItem(localStorage.key(i)))); } catch (error) { /* do nothing and just skip */ } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript array - how to handle multiple array items with same key/name? I have a javascript array like this (end result): Array( [text_vars] => Array( [0] => 'xxxxxx', [1] => 'xxxxxx' ) ) Right now the loop I'm using to translate my JSON data into the array: var aws = json.data; var text_vars = new Array(); for(i=0; i < 4; i++){ var id = aws[i]['id']; var name = aws[i]['name']; text_vars[i] = id; } I then post the resulting array to my PHP processing page, I send them along with my jQuery post in this format: { text_vars: text_vars } I need the array formatted like this: Array( [text_vars][0] => 'xxxxx', [text_vars][1] => 'xxxxx' ) The end goal is to prepare the data so it's ready to be posted via jQuery, like this: { text_vars[0]: 'xxxxx', text_vars[1]: 'xxxxx' } So, if you can suggest a better method to transform the array into that format, I'm happy to hear it :) A: var result = {} for (var i = 0; i < text_vars.length; ++i) { result["text_vars[" + i + "]"] = text_vars[i] } Now result contains the structure you desire.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jade Inline Conditional I'm trying to make everything apart from the first element in an array have a CSS class using the Jade templating engine. I was hoping I could do it like this, but no luck. Any suggestions? - each sense, i in entry.senses div(class="span13 #{ if (i != 0) 'offset3' }") ... a tonne of subsequent stuff I know I could wrap the code as below, but as far as I understand Jade's nesting rules to work, I'd have to duplicate the code or extract it to a Mixin or something. - each sense, i in entry.senses - if (i == 0) .span13 ... a tonne of subsequent stuff - else .span13.offset3 ... identical subsequent stuff Is there a better way of doing this? A: You can do this instead: - each sense, i in entry.senses - var klass = (i === 0 ? 'span13' : 'span13 offset3') div(class=klass) ... a tonne of subsequent stuff A: This also works: div(class=(i===0 ? 'span13' : 'span13 offset3')) A: This works too: div(class="#{i===0 ? 'span13' : 'span13 offset3'}") A: This is my solution. I'm using a mixin to pass the current active path and in the mixin I define the complete menu and always pass an if to check if the path is the active path. mixin adminmenu(active) ul.nav.nav-list.well li.nav-header Hello li(class="#{active=='/admin' ? 'active' : ''}") a(href="/admin") Admin A: You can to use, not only class, but a bunch of attributes in a conditional way: - each sense, i in entry.senses - var attrs = i === 0 ? {'disabled': 'true'} : {'class': '100', 'ng-model': 'vm.model.name', 'ng-click': 'vm.click()'} div&attributes(attrs) A: I prefer to use simple functions to check any complex conditions. It's works perfect and fast, you shouldn't write long lines in template. Can replace this - each sense, i in entry.senses - var klass = (i === 0 ? 'span13' : 'span13 offset3') div(class=klass) ... a tonne of subsequent stuff to this -function resultClass(condition) -if (condition===0) -return 'span13' -else if (condition===1) -return 'span13 offset3' -else if (condition===2) //-any other cases can be implemented -return 'span13 offset3' -else -return 'span13 offset3' - each sense, i in entry.senses div(class=resultClass(i)) ... a tonne of subsequent stuff Hope it helps and the idea is clear to understand. Also it's good practice to move all functions in include file and share it between different templates, but it's another question A: With pug 2 you can use this syntax: a(href='/', class="link", class={"-active": page === 'home'}) Home page more here: https://pugjs.org/language/attributes.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7563647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: What are the basic language constructs in java? I've been asked to "Identify all language constructs in Java. Your list should start with classes: The body of class declarations" I was under the impression that a 'language construct' was any allowable command in a language, but this is clearly not what is meant by the question. If anyone could give me a clearer understanding of what a language construct is in this context, and what kind of thing this list should contain, I would appreciate it. Thanks in advance! A: Well, according to Wikipedia, a language construct is "a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of a programming language" The phrase "language construct(s)" appears in the JLS once, in the Preface (excluding a mention in the index): "We intend that the behavior of every language construct is specified here..." This implies that every Java "language construct" is cataloged in the JLS. Combined with the Wikipedia definition, that would seem to cover everything from keywords and literal values; types, names, and variables; to packages, classes, interfaces, and class members like methods, fields, and constructors; blocks, statements, expressions... Take your pick. Just take a look through the ToC. A: It seems to me that he means to ask "What is allowed within the body of a class declaration?" Which, in normal Java, would be something like this: * *A class may contain both "members" and static blocks. *A member may be public, protected, package private, or private. *A member may be either statically or non-statically accessible *A member may be one of: * *Variable *Method *Inner Class *A variable may be followed by an assignment. *A method may contain a series of calls to other methods, variable declarations, and variable assignments. *Finally, an inner class may contain all the things listed above, as it itself is a normal class. A: I hope you would be knowing what a construct is. Therefore let me tell you the types of constructs that are allowed in Java: * *Sequence construct-in this pragram starts at one place and it is executed line by line (each and every line is executed in this part of code). *Selection construct - in this construct we have two or more than two statements or part of code and only a limited or one is executed depending upon the condition (e.g. if else). *Looping construct - in this a set of statements is repeated again and again(part of code that is repeated again and again). This classification was on basis of the path followed by the the compiler or interpreter while the code is executed. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I use TA-Lib in Google App Engine? TA-Lib has a Java binary version. http://ta-lib.org/hdr_dw.html Can I use this in a Google App Engine project? A: The most likely reason that it wouldn't work would be the use of classes that are restricted in the production runtime. Or the use of a library that uses one of those restricted classes. You can get see list of classes that are allowed here: http://code.google.com/appengine/docs/java/jrewhitelist.html There is also a list of frameworks and APIs that people have tested here: http://code.google.com/p/googleappengine/wiki/WillItPlayInJava When you test this and find out, please update this question and the Will It Play wiki.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Static Final Variable in Java Possible Duplicate: private final static attribute vs private final attribute What's the difference between declaring a variable as static final int x = 5; or final int x = 5; If I only want to the variable to be local, and constant (cannot be changed later)? Thanks A: In first statement you define variable, which common for all of the objects (class static field). In the second statement you define variable, which belongs to each created object (a lot of copies). In your case you should use the first one. A: Just having final will have the intended effect. final int x = 5; ... x = 10; // this will cause a compilation error because x is final Declaring static is making it a class variable, making it accessible using the class name <ClassName>.x A: Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword. Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name. As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final'). Similar question is private final static attribute vs private final attribute Hope it helps A: For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4. See Pavel's response for the correct answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Java generics constraint require default constructor like C# In C#, I can put a type constraint on a generic parameter that requires the generic type to have a default parameterless constructor. Can I do the same in Java? In C#: public static T SomeMethodThatDoesSomeStuff<T>() where T : class, new() { // ... method body ... } The class and new() constraints mean that T must be a class that can be called with the new operator with zero parameters. What little I know of Java generics, I can use extends to name a required super class. Can I use that (or any other supported operation) to achieve the above functionality? A: No; in Java the typical solution is to pass a class, and doc the requirement of 0-arg constructor. This is certainly less static checking, but not too huge a problem /** clazz must have a public default constructor */ public static <T> T f(Class<T> clazz) return clazz.newInstance(); A: No. Because of type erasure, the type of <T> is not known at runtime, so it's inherently impossible to instantiate it. A: Java does not do structural typing, so you cannot constrain T to have a particular constructor or static method. Only subtyping and supertyping restrictions are permitted. So, pass an appropriate abstract factory. Use of reflection here, or in virtually any case, is highly inappropriate. There is now a now a suitable generic JDK type for this in the form of java.util.function.Supplier. public static T someMethodThatDoesSomeStuff<T>( Supplier<T> factory ) { Invoke as: Donkey donkey = someMethodThatDoesSomeStuff(BigDonkey::new); (The method reference needn't be a constructor.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Windows Phone - Change Grid Background Color On Button Click I'm trying to change the background color of the grid named LayoutRoot to black when you click the button bgButton in the application bar. I can't find anything on how to do this through Google or anything. Thanks. A: In the event handler for the button's Click event add the following: LayoutRoot.Background = new SolidColorBrush( Colors.Cyan ); It doesn't have to be a SolidColorBrush, it can be any class derived from Brush, such as LinearGradientBrush, RadialGradientBrush etc. You can also use a binding instead of explicitly setting the color for the Grid. In XAML <Grid Background="{Binding RootBackground}"> ... </Grid> In your ViewModel public Brush RootBackground { get { return _rootBackground; } set { if( value != _rootBackground ) { _rootBackground = value; NotifyPropertyChanged( "RootBackground" ); } } } private Brush _rootBackground = new SolidColorBrush( Colors.Transparent ); In the button event handler RootBackground = new SolidColorBrush( Colors.Cyan );
{ "language": "en", "url": "https://stackoverflow.com/questions/7563657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP check file extension I have an upload script that I need to check the file extension, then run separate functions based on that file extension. Does anybody know what code I should use? if (FILE EXTENSION == ???) { FUNCTION1 } else if { FUNCTION2 } A: For php 5.3+ you can use the SplFileInfo() class $spl = new SplFileInfo($filename); print_r($spl->getExtension()); //gives extension Also since you are checking extension for file uploads, I highly recommend using the mime type instead.. For php 5.3+ use the finfo class $finfo = new finfo(FILEINFO_MIME); print_r($finfo->buffer(file_get_contents($file name)); A: $file_parts = pathinfo($filename); $file_parts['extension']; $cool_extensions = Array('jpg','png'); if (in_array($file_parts['extension'], $cool_extensions)){ FUNCTION1 } else { FUNCTION2 } A: $info = pathinfo($pathtofile); if ($info["extension"] == "jpg") { .... } A: $path = 'image.jpg'; echo substr(strrchr($path, "."), 1); //jpg A: pathinfo is what you're looking for PHP.net $file_parts = pathinfo($filename); switch($file_parts['extension']) { case "jpg": break; case "exe": break; case "": // Handle file extension for files ending in '.' case NULL: // Handle no file extension break; } A: $original_str="this . is . to . find"; echo "<br/> Position: ". $pos=strrpos($original_str, "."); $len=strlen($original_str); if($pos >= 0) { echo "<br/> Extension: ". substr($original_str,$pos+1,$len-$pos) ; } A: $file = $_FILES["file"] ["tmp_name"]; $check_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION)); if ($check_ext == "fileext") { //code } else { //code }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Gitolite and Gitweb config acces via web I have a problem with gitolite and gitweb ... it almost done .. but gitweb display all repos.. doesn't filter permissions for users .. so it always show me all repos for all users.. I read that I must configure with this: https://github.com/sitaramc/gitolite/blob/pu/contrib/gitweb/gitweb.conf but when I insert that code in my gitweb.cgi it says: Global symbol "$REPO_BASE" requires explicit package name at gitweb.cgi line 7389. Global symbol "$REPO_BASE" requires explicit package name at gitweb.cgi line 7389. Global symbol "$REPO_BASE" requires explicit package name at gitweb.cgi line 7389. Execution of gitweb.cgi aborted due to compilation errors. here is my gitweb.cgi https://gist.github.com/1244184 does any one know how to make this work??? thanks.. A: I think you need to put the gitweb.conf in your /etc/ folder at least thats what I did with it. I can see all repos I am permitted to!My Gitolite works against an AD/LDAP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Scrollbar Accelerator? I'm writing an Android application that contains lots of long lists and I need to accelerate scrolling somehow. The Android Contacts application for example uses a list of letters to allow quick scrolling to a certain spot in the list ... it's not exactly what I'm looking for though. I've seen other applications use a handle (or paddle) that appears when you start scrolling and allows you to easily drag the scrollbars to a specific location, that might be a better solution for me. I'm wondering if anyone would have any info about either of the above methods or any other suggestions on how to accelerate scrolling through long lists (long meaning 500-750 items). Thanks, Harry A: <ListView ... android:fastScrollEnabled="true"/> and this to "jump" in listView: http://developer.android.com/reference/android/widget/SectionIndexer.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7563660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What does this piece of code do? I came across this key logger online and was wondering what the following piece of code actually does. There are 2 lodsd commands in succession and that confuses me. And also what is the purpose of the or command there? full code can be found at: http://www.rohitab.com/discuss/topic/21205-asm-keylogger-in-4k-d/ Here is the code excerpt(line 295 onwards): get_name_of_key: ; no need for large table of pointers to get asciiz mov esi, [lParam] lodsd ; skip virtual key code lodsd ; eax = scancode shl eax, 16 xchg eax, ecx lodsd ; extended key info shl eax, 24 or ecx, eax push 32 lea edi, [lpCharBuf] push edi push ecx call GetKeyNameTextA ; get the key text A: LODSD loads a dword from whatever ESI points to into EAX and then increments ESI by 4 (pointing to the next dword). You're viewing the low level keyboard hook callback, according to MSDN a call to the callback will put a pointer to a KBDLLHOOKSTRUCT in lParam, the MOV ESI,[lParam] puts that pointer in ESI for later use by LODSD. The structure contains Virtual Keycode, followed by scan code, some flags, a timestamp and pointer to extra info, each one DWORD long. So the first LODSD reads the vkcode into EAX, the next reads the scan code into (and overwriting) EAX. It then shifts the scancode from bits 0-7 to bits 16-23 for later use by GetKeyNameText. EAX and ECX are then swapped. The next LODSD reads the flags associated with the key press, the flag that indicates whether an extended key (Fxx or keys from the numpad, etc) was pressed is at bit 0, it and the other bits are shifted to bit 24 and beyond, filling the lower bits with 0. The OR then does a binary OR of the scancode at bits 16-23 in ECX and the extended key flag at bit 24 in EAX combining all bits into ECX. (Binary OR sets each bit to 1 when either or both source bits are set 1, otherwise 0), that information is then passed to GetKeyNameText to get an text representation of the key pressed, like CAPSLOCK or LEFT SHIFT, in the 32 byte character buffer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Copy and paste commands with WPF buttons I have created a toolbar that has buttons. Of the buttons 3 of them are cut copy and paste. I set the command of each of those buttons to cut copy and paste on the properties but when I go run the program none of the buttons are even clickable. Are they disabled I'm guessing? I'm trying to copy and paste from textbox to textbox in a tabcontrol. Any help is appreciated. <Style TargetType="{x:Type Button}" x:Key="textBoxCommands"> <Setter Property="Content" Value="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" /> <Setter Property="CommandTarget" Value="{Binding ElementName=textBox}" /> </Style> <Button x:Name="btnCut" Click="btnCut_Click"> <Image Source="Icons/Cut.png" ToolTip="Cut" /> </Button> <Button x:Name="btnCopy" Click="btnCopy_Click" Command="ApplicationCommands.Copy" Style="{StaticResource textBoxCommands}"> <Image Source="Icons/Copy.png" ToolTip="Copy" /> </Button> <Button x:Name="btnPaste" Click="btnPaste_Click" Command="ApplicationCommands.Paste" Style="{StaticResource textBoxCommands}" > <Image Source="Icons/Paste.png" ToolTip="Paste" /> </Button> A: You can’t use command this way! The Command (in the way you use it) should be inside a Menu or Toolbar. By the way, you don’t need those click event handler since you are going to use Commands! I recommend you to try add DelegateCommand to the ViewModel and let that delegate call ApplicationCommads. I highly recommend you to read this http://msdn.microsoft.com/en-us/magazine/dd419663.aspx But as a quick solution for you try the following (important: remember that you need to have some text selected in your TextBox then Copy and Cut will be enabled): <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top"> <ToolBar> <Button Content="Cut" Command="ApplicationCommands.Cut" Height="23" Width="75"/> <Button Content="Copy" Command="ApplicationCommands.Copy" Height="23" Width="75"/> <Button Content="Paste" Command="ApplicationCommands.Paste" Height="23" Width="75"/> </ToolBar> <TextBox Height="23" Name="textBox1" Width="120"/> </StackPanel> A: For the purpose you are trying to achieve I would suggest using a togglebutton. Also the button would be clickable as and when they are supposed to. For example * *Paste button gets clickable only when there is something to paste. *Cut/Copy Button gets clickable when there something selected in RTB. Have a look at all the ApplicationCommands at msdn. You can implement them as easily as: <ToggleButton x:Name="PasteBtn" Command="ApplicationCommands.Paste"/> <ToggleButton x:Name="CutBtn" Command="ApplicationCommands.Cut"/> <ToggleButton x:Name="CopyBtn" Command="ApplicationCommands.Copy"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Algorithm for finding the ratio of two floating-point numbers? I need to find the ratio of one floating-point number to another, and the ratio needs to be two integers. For example: * *input: 1.5, 3.25 *output: "6:13" Does anyone know of one? Searching the internet, I found no such algorithm, nor an algorithm for the least common multiple or denominator of two floating-point numbers (just integers). Java implementation: This is the final implementation that I will use: public class RatioTest { public static String getRatio(double d1, double d2)//1.5, 3.25 { while(Math.max(d1,d2) < Long.MAX_VALUE && d1 != (long)d1 && d2 != (long)d2) { d1 *= 10;//15 -> 150 d2 *= 10;//32.5 -> 325 } //d1 == 150.0 //d2 == 325.0 try { double gcd = getGCD(d1,d2);//gcd == 25 return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd));//"6:13" } catch (StackOverflowError er)//in case getGDC (a recursively looping method) repeats too many times { throw new ArithmeticException("Irrational ratio: " + d1 + " to " + d2); } } public static double getGCD(double i1, double i2)//(150,325) -> (150,175) -> (150,25) -> (125,25) -> (100,25) -> (75,25) -> (50,25) -> (25,25) { if (i1 == i2) return i1;//25 if (i1 > i2) return getGCD(i1 - i2, i2);//(125,25) -> (100,25) -> (75,25) -> (50,25) -> (25,25) return getGCD(i1, i2 - i1);//(150,175) -> (150,25) } } * *-> indicates the next stage in the loop or method call Mystical's implementation as Java: Though I did not end up using this, it more than deserves to be recognized, so I translated it to Java, so I could understand it: import java.util.Stack; public class RatioTest { class Fraction{ long num; long den; double val; }; Fraction build_fraction(Stack<long> cf){ long term = cf.size(); long num = cf[term - 1]; long den = 1; while (term-- > 0){ long tmp = cf[term]; long new_num = tmp * num + den; long new_den = num; num = new_num; den = new_den; } Fraction f; f.num = num; f.den = den; f.val = (double)num / (double)den; return f; } void get_fraction(double x){ System.out.println("x = " + x); // Generate Continued Fraction System.out.print("Continued Fraction: "); double t = Math.abs(x); double old_error = x; Stack<long> cf; Fraction f; do{ // Get next term. long tmp = (long)t; cf.push(tmp); // Build the current convergent f = build_fraction(cf); // Check error double new_error = Math.abs(f.val - x); if (tmp != 0 && new_error >= old_error){ // New error is bigger than old error. // This means that the precision limit has been reached. // Pop this (useless) term and break out. cf.pop(); f = build_fraction(cf); break; } old_error = new_error; System.out.print(tmp + ", "); // Error is zero. Break out. if (new_error == 0) break; t -= tmp; t = 1/t; }while (cf.size() < 39); // At most 39 terms are needed for double-precision. System.out.println();System.out.println(); // Print Results System.out.println("The fraction is: " + f.num + " / " + f.den); System.out.println("Target x = " + x); System.out.println("Fraction = " + f.val); System.out.println("Relative error is: " + (Math.abs(f.val - x) / x));System.out.println(); System.out.println(); } public static void main(String[] args){ get_fraction(15.38 / 12.3); get_fraction(0.3333333333333333333); // 1 / 3 get_fraction(0.4184397163120567376); // 59 / 141 get_fraction(0.8323518818409020299); // 1513686 / 1818565 get_fraction(3.1415926535897932385); // pi } } One MORE thing: The above mentioned implemented way of doing this works IN THEORY, however, due to floating-point rounding errors, this results in alot of unexpected exceptions, errors, and outputs. Below is a practical, robust, but a bit dirty implementation of a ratio-finding algorithm (Javadoc'd for your convenience): public class RatioTest { /** Represents the radix point */ public static final char RAD_POI = '.'; /** * Finds the ratio of the two inputs and returns that as a <tt>String</tt> * <h4>Examples:</h4> * <ul> * <li><tt>getRatio(0.5, 12)</tt><ul> * <li>returns "<tt>24:1</tt>"</li></ul></li> * <li><tt>getRatio(3, 82.0625)</tt><ul> * <li>returns "<tt>1313:48</tt>"</li></ul></li> * </ul> * @param d1 the first number of the ratio * @param d2 the second number of the ratio * @return the resulting ratio, in the format "<tt>X:Y</tt>" */ public static strictfp String getRatio(double d1, double d2) { while(Math.max(d1,d2) < Long.MAX_VALUE && (!Numbers.isCloseTo(d1,(long)d1) || !Numbers.isCloseTo(d2,(long)d2))) { d1 *= 10; d2 *= 10; } long l1=(long)d1,l2=(long)d2; try { l1 = (long)teaseUp(d1); l2 = (long)teaseUp(d2); double gcd = getGCDRec(l1,l2); return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd)); } catch(StackOverflowError er) { try { double gcd = getGCDItr(l1,l2); return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd)); } catch (Throwable t) { return "Irrational ratio: " + l1 + " to " + l2; } } } /** * <b>Recursively</b> finds the Greatest Common Denominator (GCD) * @param i1 the first number to be compared to find the GCD * @param i2 the second number to be compared to find the GCD * @return the greatest common denominator of these two numbers * @throws StackOverflowError if the method recurses to much */ public static long getGCDRec(long i1, long i2) { if (i1 == i2) return i1; if (i1 > i2) return getGCDRec(i1 - i2, i2); return getGCDRec(i1, i2 - i1); } /** * <b>Iteratively</b> finds the Greatest Common Denominator (GCD) * @param i1 the first number to be compared to find the GCD * @param i2 the second number to be compared to find the GCD * @return the greatest common denominator of these two numbers */ public static long getGCDItr(long i1, long i2) { for (short i=0; i < Short.MAX_VALUE && i1 != i2; i++) { while (i1 > i2) i1 = i1 - i2; while (i2 > i1) i2 = i2 - i1; } return i1; } /** * Calculates and returns whether <tt>d1</tt> is close to <tt>d2</tt> * <h4>Examples:</h4> * <ul> * <li><tt>d1 == 5</tt>, <tt>d2 == 5</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5.0001</tt>, <tt>d2 == 5</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5</tt>, <tt>d2 == 5.0001</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5.24999</tt>, <tt>d2 == 5.25</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5.25</tt>, <tt>d2 == 5.24999</tt> * <ul><li>returns <tt>true</tt></li></ul></li> * <li><tt>d1 == 5</tt>, <tt>d2 == 5.1</tt> * <ul><li>returns <tt>false</tt></li></ul></li> * </ul> * @param d1 the first number to compare for closeness * @param d2 the second number to compare for closeness * @return <tt>true</tt> if the two numbers are close, as judged by this method */ public static boolean isCloseTo(double d1, double d2) { if (d1 == d2) return true; double t; String ds = Double.toString(d1); if ((t = teaseUp(d1-1)) == d2 || (t = teaseUp(d2-1)) == d1) return true; return false; } /** * continually increases the value of the last digit in <tt>d1</tt> until the length of the double changes * @param d1 * @return */ public static double teaseUp(double d1) { String s = Double.toString(d1), o = s; byte b; for (byte c=0; Double.toString(extractDouble(s)).length() >= o.length() && c < 100; c++) s = s.substring(0, s.length() - 1) + ((b = Byte.parseByte(Character.toString(s.charAt(s.length() - 1)))) == 9 ? 0 : b+1); return extractDouble(s); } /** * Works like Double.parseDouble, but ignores any extraneous characters. The first radix point (<tt>.</tt>) is the only one treated as such.<br/> * <h4>Examples:</h4> * <li><tt>extractDouble("123456.789")</tt> returns the double value of <tt>123456.789</tt></li> * <li><tt>extractDouble("1qw2e3rty4uiop[5a'6.p7u8&9")</tt> returns the double value of <tt>123456.789</tt></li> * <li><tt>extractDouble("123,456.7.8.9")</tt> returns the double value of <tt>123456.789</tt></li> * <li><tt>extractDouble("I have $9,862.39 in the bank.")</tt> returns the double value of <tt>9862.39</tt></li> * @param str The <tt>String</tt> from which to extract a <tt>double</tt>. * @return the <tt>double</tt> that has been found within the string, if any. * @throws NumberFormatException if <tt>str</tt> does not contain a digit between 0 and 9, inclusive. */ public static double extractDouble(String str) throws NumberFormatException { try { return Double.parseDouble(str); } finally { boolean r = true; String d = ""; for (int i=0; i < str.length(); i++) if (Character.isDigit(str.charAt(i)) || (str.charAt(i) == RAD_POI && r)) { if (str.charAt(i) == RAD_POI && r) r = false; d += str.charAt(i); } try { return Double.parseDouble(d); } catch (NumberFormatException ex) { throw new NumberFormatException("The input string could not be parsed to a double: " + str); } } } } A: Assuming you have a data type that can handle arbitrarily large numeric values, you can do something like this: * *Multiply both values by 10 until the significand is entirely to the left of the decimal point. *Find the Greatest Common Denominator of the two values. *Divide by GCD So for you example you would have something like this: a = 1.5 b = 3.25 multiply by 10: 15, 32.5 multiply by 10: 150, 325 find GCD: 25 divide by GCD: 6, 13 A: This is a fairly non-trivial task. The best approach I know that gives reliable results for any two floating-point is to use continued fractions. First, divide the two numbers to get the ratio in floating-point. Then run the continued fraction algorithm until it terminates. If it doesn't terminate, then it's irrational and there is no solution. If it terminates, evaluate the resulting continued fraction back into a single fraction and that will be the answer. Of course, there is no reliable way to determine if there is a solution or not since this becomes the halting problem. But for the purposes of limited precision floating-point, if the sequence doesn't terminate with a reasonable number of steps, then assume there's no answer. EDIT 2: Here's an update to my original solution in C++. This version is much more robust and seems to work with any positive floating-point number except for INF, NAN, or extremely large or small values that would overflow an integer. typedef unsigned long long uint64; struct Fraction{ uint64 num; uint64 den; double val; }; Fraction build_fraction(vector<uint64> &cf){ uint64 term = cf.size(); uint64 num = cf[--term]; uint64 den = 1; while (term-- > 0){ uint64 tmp = cf[term]; uint64 new_num = tmp * num + den; uint64 new_den = num; num = new_num; den = new_den; } Fraction f; f.num = num; f.den = den; f.val = (double)num / den; return f; } void get_fraction(double x){ printf("x = %0.16f\n",x); // Generate Continued Fraction cout << "Continued Fraction: "; double t = abs(x); double old_error = x; vector<uint64> cf; Fraction f; do{ // Get next term. uint64 tmp = (uint64)t; cf.push_back(tmp); // Build the current convergent f = build_fraction(cf); // Check error double new_error = abs(f.val - x); if (tmp != 0 && new_error >= old_error){ // New error is bigger than old error. // This means that the precision limit has been reached. // Pop this (useless) term and break out. cf.pop_back(); f = build_fraction(cf); break; } old_error = new_error; cout << tmp << ", "; // Error is zero. Break out. if (new_error == 0) break; t -= tmp; t = 1/t; }while (cf.size() < 39); // At most 39 terms are needed for double-precision. cout << endl << endl; // Print Results cout << "The fraction is: " << f.num << " / " << f.den << endl; printf("Target x = %0.16f\n",x); printf("Fraction = %0.16f\n",f.val); cout << "Relative error is: " << abs(f.val - x) / x << endl << endl; cout << endl; } int main(){ get_fraction(15.38 / 12.3); get_fraction(0.3333333333333333333); // 1 / 3 get_fraction(0.4184397163120567376); // 59 / 141 get_fraction(0.8323518818409020299); // 1513686 / 1818565 get_fraction(3.1415926535897932385); // pi system("pause"); } Output: x = 1.2504065040650407 Continued Fraction: 1, 3, 1, 152, 1, The fraction is: 769 / 615 Target x = 1.2504065040650407 Fraction = 1.2504065040650407 Relative error is: 0 x = 0.3333333333333333 Continued Fraction: 0, 3, The fraction is: 1 / 3 Target x = 0.3333333333333333 Fraction = 0.3333333333333333 Relative error is: 0 x = 0.4184397163120567 Continued Fraction: 0, 2, 2, 1, 1, 3, 3, The fraction is: 59 / 141 Target x = 0.4184397163120567 Fraction = 0.4184397163120567 Relative error is: 0 x = 0.8323518818409020 Continued Fraction: 0, 1, 4, 1, 27, 2, 7, 1, 2, 13, 3, 5, The fraction is: 1513686 / 1818565 Target x = 0.8323518818409020 Fraction = 0.8323518818409020 Relative error is: 0 x = 3.1415926535897931 Continued Fraction: 3, 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 3, The fraction is: 245850922 / 78256779 Target x = 3.1415926535897931 Fraction = 3.1415926535897931 Relative error is: 0 Press any key to continue . . . The thing to notice here is that it gives 245850922 / 78256779 for pi. Obviously, pi is irrational. But as far as double-precision allows, 245850922 / 78256779 isn't any different from pi. Basically, any fraction with 8 - 9 digits in the numerator/denominator has enough entropy to cover nearly all DP floating-point values (barring corner cases like INF, NAN, or extremely large/small values). A: If the floating point numbers have a limit to decimal places - then just multiply both numbers by 10^n where n is limit - so for 2 decimal places, multiply by 100, then calculate for whole numbers - the ratio will be the same for the original decimals because it is a ratio. A: In Maxima CAS simply : (%i1) rationalize(1.5/3.5); (%o1) 7720456504063707/18014398509481984 Code from numeric.lisp : ;;; This routine taken from CMUCL, which, in turn is a routine from ;;; CLISP, which is GPL. ;;; ;;; I (rtoy) have modified it from CMUCL so that it only handles bigfloats. ;;; ;;; RATIONALIZE -- Public ;;; ;;; The algorithm here is the method described in CLISP. Bruno Haible has ;;; graciously given permission to use this algorithm. He says, "You can use ;;; it, if you present the following explanation of the algorithm." ;;; ;;; Algorithm (recursively presented): ;;; If x is a rational number, return x. ;;; If x = 0.0, return 0. ;;; If x < 0.0, return (- (rationalize (- x))). ;;; If x > 0.0: ;;; Call (integer-decode-float x). It returns a m,e,s=1 (mantissa, ;;; exponent, sign). ;;; If m = 0 or e >= 0: return x = m*2^e. ;;; Search a rational number between a = (m-1/2)*2^e and b = (m+1/2)*2^e ;;; with smallest possible numerator and denominator. ;;; Note 1: If m is a power of 2, we ought to take a = (m-1/4)*2^e. ;;; But in this case the result will be x itself anyway, regardless of ;;; the choice of a. Therefore we can simply ignore this case. ;;; Note 2: At first, we need to consider the closed interval [a,b]. ;;; but since a and b have the denominator 2^(|e|+1) whereas x itself ;;; has a denominator <= 2^|e|, we can restrict the seach to the open ;;; interval (a,b). ;;; So, for given a and b (0 < a < b) we are searching a rational number ;;; y with a <= y <= b. ;;; Recursive algorithm fraction_between(a,b): ;;; c := (ceiling a) ;;; if c < b ;;; then return c ; because a <= c < b, c integer ;;; else ;;; ; a is not integer (otherwise we would have had c = a < b) ;;; k := c-1 ; k = floor(a), k < a < b <= k+1 ;;; return y = k + 1/fraction_between(1/(b-k), 1/(a-k)) ;;; ; note 1 <= 1/(b-k) < 1/(a-k) ;;; ;;; You can see that we are actually computing a continued fraction expansion. ;;; ;;; Algorithm (iterative): ;;; If x is rational, return x. ;;; Call (integer-decode-float x). It returns a m,e,s (mantissa, ;;; exponent, sign). ;;; If m = 0 or e >= 0, return m*2^e*s. (This includes the case x = 0.0.) ;;; Create rational numbers a := (2*m-1)*2^(e-1) and b := (2*m+1)*2^(e-1) ;;; (positive and already in lowest terms because the denominator is a ;;; power of two and the numerator is odd). ;;; Start a continued fraction expansion ;;; p[-1] := 0, p[0] := 1, q[-1] := 1, q[0] := 0, i := 0. ;;; Loop ;;; c := (ceiling a) ;;; if c >= b ;;; then k := c-1, partial_quotient(k), (a,b) := (1/(b-k),1/(a-k)), ;;; goto Loop ;;; finally partial_quotient(c). ;;; Here partial_quotient(c) denotes the iteration ;;; i := i+1, p[i] := c*p[i-1]+p[i-2], q[i] := c*q[i-1]+q[i-2]. ;;; At the end, return s * (p[i]/q[i]). ;;; This rational number is already in lowest terms because ;;; p[i]*q[i-1]-p[i-1]*q[i] = (-1)^i. ;;; (defmethod rationalize ((x bigfloat)) (multiple-value-bind (frac expo sign) (integer-decode-float x) (cond ((or (zerop frac) (>= expo 0)) (if (minusp sign) (- (ash frac expo)) (ash frac expo))) (t ;; expo < 0 and (2*m-1) and (2*m+1) are coprime to 2^(1-e), ;; so build the fraction up immediately, without having to do ;; a gcd. (let ((a (/ (- (* 2 frac) 1) (ash 1 (- 1 expo)))) (b (/ (+ (* 2 frac) 1) (ash 1 (- 1 expo)))) (p0 0) (q0 1) (p1 1) (q1 0)) (do ((c (ceiling a) (ceiling a))) ((< c b) (let ((top (+ (* c p1) p0)) (bot (+ (* c q1) q0))) (/ (if (minusp sign) (- top) top) bot))) (let* ((k (- c 1)) (p2 (+ (* k p1) p0)) (q2 (+ (* k q1) q0))) (psetf a (/ (- b k)) b (/ (- a k))) (setf p0 p1 q0 q1 p1 p2 q1 q2)))))))) A: I'm using the folowing algorithm. It's fast and simple. It uses the fact that 10^N = 2^N * 5^N and it also handles recurring patterns of digits ! I hope it will help you. Fraction-to-ratio-converter Some demos are also provided at that side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Only fetch a subset of remote git branches or only display a subset of them in gitk If other developers push their local branches to a shared remote repository before committing to trunk (to share, backup, or centrally store them for access from multiple machines), is there a way for me to easily only fetch my own branches or selectively delete local references to others' remote branches? If not, is there a way to only show a subset of remote branches in gitk, so I can see where my branches are relative to my remote branches, but not have the graph cluttered by everyone else's remote branches? A: Here's one way of only fetching particular branches from a remote: The refs (including branches) that are fetched from a remote are controlled with the config option remote.<remote-name>.fetch. For example, your remote.origin.fetch is probably the refspec: +refs/heads/*:refs/remotes/origin/* ... which means to make fetch the names of all the refs under refs/heads/ in the remote repository, and make them available under refs/remotes/origin/ in your local repository. (The + means to do forced updates, so your remote-tracking branches can be updated even if the update wouldn't be a fast-forward.) You can instead list multiple refspecs that specify particular branches to fetch, e.g. changing this with: git config remote.origin.fetch +refs/heads/master:refs/remotes/origin/master git config --add remote.origin.fetch +refs/heads/blah:refs/remotes/origin/blah ... and then the next time only master and blah will be fetched. Of course, you already locally have lots of remote-tracking branches, and gitk will still show those. You can remove each of the ones you're not interested in with: git branch -r -d origin/uninteresting
{ "language": "en", "url": "https://stackoverflow.com/questions/7563671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery .next selector ignores the generated div and targets the next div - how can I target the sibling div I am trying to target a div that is generated by a jQuery plugin. I have been trying to do this using .next but with no luck. Update: Please note this generated div is triggered by a click *Update:Here is a fiddle of the code http://jsfiddle.net/clintongreen/PAbAH/1/ The problem is, the next selector ignores the generated div and targets the next div. I understand that this is not working because the generated div is technically not a sibling. Does anyone have an idea how I can target this elusive generated div. I can't use css because I only want to hide it when it is generated from certain links. Code example //Script $("div.region_marker").next("div.bubble").hide(); //HTML <div class="region_marker">Region Marker text</div> //this is how I am targeting the generated div <div class="bubble">Bubble text</div> //div generated by jQuery, not hard coded, this is ignored by .next <div class="map_marker">Map Marker text</div> //random div, this is the one that .next targets <div class="map_marker">Map Marker text</div> //random div I am open to any suggestions you have, thanks guys A: If it's a child, use .find(). If it's a sibling and the very next sibling, use .next(). If it's a next sibling, but not the very next sibling, then use .nextAll(). In your code, this will get the "Bubble text" div generated by jQuery: $("div.region_marker").next(); This will get the first Map Marker text div: $("div.region_marker").nextAll(".map_marker").first(); If you really want to hide the first .bubble sibling, then you can use this: $("div.region_marker").nextAll(".bubble").first().hide(); The only reason that last one would work and your code would not is if the order of the tags isn't quite what you think it is. P.S. Using selectors like div.bubble and div.region_marker is not necessary unless you're trying to eliminate other types of tags that might have that class. In your situation, you can just use .region_marker and .bubble and save the selector engine a little work. A: Thanks I got it working using: $("div.region_marker").click(function() { $(this).next(".bubble").hide(); }); It works now using the click function to trigger this at the same time, the traditional methods were not working because I ran those functions before the div.bubble was loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Differentiate Guid and string Parameters in MVC 3 Using the out-of-the-box method locators in ASP.NET MVC (3 or 4DP), is there a way to have the MVC framework differentiate between a string and Guid without needing to parse the parameter in the controller action? Usage examples would be for the URL http://[domain]/customer/details/F325A917-04F4-4562-B104-AF193C41FA78 to execute the public ActionResult Details(Guid guid) method, and http://[domain]/customer/details/bill-gates to execute the public ActionResult Details(string id) method. With no changes, obviously the methods are ambiguous, as follows: public ActionResult Details(Guid id) { var model = Context.GetData(id); return View(model); } public ActionResult Details(string id) { var model = Context.GetData(id); return View(model); } resulting in the error: The current request for action 'Details' on controller type 'DataController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Details(System.Guid) on type Example.Web.Controllers.DataController System.Web.Mvc.ActionResult Details(System.String) on type Example.Web.Controllers.DataController I attempted to use a custom constraint (based on How can I create a route constraint of type System.Guid?) to try and push it through via routing: routes.MapRoute( "Guid", "{controller}/{action}/{guid}", new { controller = "Home", action = "Index" }, new { guid = new GuidConstraint() } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); And switched the action signatures to: public ActionResult Details(Guid guid) { var model = Context.GetData(guid); return View(model); } public ActionResult Details(string id) { var model = Context.GetData(id); return View(model); } The constraint executes and passes, thus the argument is sent to an action, but seemingly still as a string, and thus ambiguous to the two method signatures. I expect that there's something in how the action methods are located that causes the ambiguity, and thus could be overridden by plugging in a custom module to locate methods. The same result could be achieved by parsing out the string parameter, but would be really nice for brevity to avoid that logic in the action (not to mention to hopefully reuse someday later). A: My opinion is that using action method selector is more usable and less coding. public class GuidMethodSelectorAttribute : ActionMethodSelectorAttribute { public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo) { var idStr = controllerContext.RouteData.Values["id"]; if (idStr == null) return false; Guid a; var result = Guid.TryParse(idStr.ToString(), out a); return result; } } This selector inspects request for ID parameter. If it's guid, it returns true. So, to use it: public class HomeController : Controller { [GuidMethodSelector] public ActionResult Index(Guid id) { return View(); } public ActionResult Index(string id) { return View(); } } A: If you're still registering routes in this way then the GuidRouteConstraint() class was added in a newer version of MVC and should be used instead of a custom implementation: public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Guid", "{controller}/{action}/{guid}", new { controller = "Home", action = "Index" }, new { guid = new GuidRouteConstraint() } ); } Then you can simply create your action result as: public class HomeController : Controller { public ActionResult Index(Guid guid) { } } A: First, you must disambigute your methods by giving them two different names: public ActionResult DetailsGuid(Guid guid) { var model = Context.GetData(guid); return View(model); } public ActionResult DetailsString(string id) { var model = Context.GetData(id); return View(model); } Next, you need a custom route handler to inspect the request, and change the method name accordingly: using System.Web.Mvc; using System.Web.Routing; public class MyRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { var routeData = requestContext.RouteData; var stringValue = routeData.Values["id"].ToString(); Guid guidValue; var action = routeData.Values["action"]; if (Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty); routeData.Values["action"] = action + "Guid"; else routeData.Values["action"] = action + "String"; var handler = new MvcHandler(requestContext); return handler; } } Finally, add a Details route at the top of your routes, as follows: routes.Add("Details", new Route("{controller}/Details/{id}", new RouteValueDictionary( new { controller = "Home", action = "Details" }), new MyRouteHandler() ) ); ); When a request comes in for details, the Details route will use your custom route handler to inspect the id token. The route handler adds to the action name based on the form of the id token, so that the request will be directed to the appropriate action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how to triger testng by testng.xml, after determing by other test which testng.xml need to be run I need to run a programe before knowing which suit of test(define in testng.xml) need to be trigger. How to solve this problem? how to trigger testNG in run time? A: Have you looked at TestNG's programmatic API? A: Below code you have to put it in main method. You can run the class as regular java file. XmlSuite suite = new XmlSuite(); suite.setName("TmpSuite"); XmlTest test = new XmlTest(suite); test.setName("TmpTest"); List<XmlSuite> suites = new ArrayList<XmlSuite>(); suites.add(suite); TestNG tng = new TestNG(); //MyTestListener is custom listner if any TestListenerAdapter listener = new MyTestListener(); tng.addListener(listener); tng.setXmlSuites(suites); //if any suits tng.run(); A: Hi You can add listeners ie- suitelistner , testlistner and report listener for better control over your test.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Looping through a list and using elements within that list In the code below, instead of starting with p=0.01 and then incrementing it, I'd like to be able to do something like p=(1:99)/100 and then just loop through p. For example, instead of p=0.01, let's let p=(1:99)/100. Now, I try to replace 1:99 in my for loop with p. When I run the code, however, I start having problems with coverage[i] (it returns numeric(0)). It seems like this should be fairly trivial so I'm hoping I'm just overlooking something in my code. Also, if you see any easy boosts in efficiency please feel free to chime in! Thanks =) w=seq(.01,.99,by=.01) coverage=seq(1:99) p=0.01 for (i in 1:99){ count = 0 for (j in 1:1000){ x = rbinom(30,1,p) se=sqrt(sum(x)/30*(1-sum(x)/30)/30) if( sum(x)/30-1.644854*se < p && p < sum(x)/30+1.644854*se ) count = count + 1 } coverage[i]=count/1000 print(coverage[i]) p=p+0.01 } A: I would work on the middle part rather than that outer loop. coverage <- p <- 1:99/100 z <- qnorm(0.95) for (i in seq(along=p) ){ # simulate all of the binomials/30 at once x <- rbinom(1000, 30, p[i])/30 # ses se <- sqrt(x * (1-x)/30) # lower and upper limits lo <- x - z*se hi <- x + z*se # coverage coverage[i] <- mean(p[i] > lo & p[i] < hi) } This is almost instantaneous for me. The trick is to vectorize those simulations and calculations. Increasing to 100,000 simulation replicates took just 4 seconds on my 6-year-old Mac Pro. (You'll want to increase the replicates to see the structure in the results; plot(p, coverage, las=1) with 100k reps gives the following; it wouldn't be clear with just 1000 reps.) A: To answer the original question, setting i in p where p is 0.01, 0.02, etc, means that coverage[i] is trying to do coverage[0.01]; since [] requires an integer it truncates it to zero, resulting in a numeric of length zero, numeric(0). One of the other solutions is better, but for reference, to do it using your original loop, you'd probably want something like p <- seq(.01, .99, by=.01) coverage <- numeric(length(p)) N <- 1000 n <- 30 k <- qnorm(1-0.1/2) for (i in seq_along(p)) { count <- 0 for (j in 1:N) { x <- rbinom(n, 1, p[i]) phat <- mean(x) se <- sqrt(phat * (1 - phat) / n) if( phat-k*se < p[i] && p[i] < phat+k*se ) { count <- count + 1 } } coverage[i] <- count/N } coverage A: @Karl Broman has a great solution that really shows how vectorization makes all the difference. It can still be improved slightly though (around 30%): I prefer using vapply - although the speed improvement of it isn't noticeable here since the loop is only 99 times. f <- function(n=1000) { z <- qnorm(0.95)/sqrt(30) vapply(1:99/100, function(p) { # simulate all of the binomials/30 at once x <- rbinom(n, 30, p)/30 zse <- z*sqrt(x * (1-x)) # coverage mean(x - zse < p & p < x + zse) }, numeric(1)) } system.time( x <- f(50000) ) # 1.17 seconds Here's a version of the OP's original code using vapply and it's about 20% faster than the original -but of course still magnitudes slower than the fully vectorized solutions... g <- function(n=1000) { vapply(seq(.01,.99,by=.01), function(p) { count = 0L for (j in seq_len(n)) { x <- sum(rbinom(30,1,p))/30 # the constant is qnorm(0.95)/sqrt(30) zse <- 0.30030781175850279*sqrt(x*(1-x)) if( x-zse < p && p < x+zse ) count = count + 1L } count/n }, numeric(1)) } system.time( x <- g(1000) ) # 1.04 seconds
{ "language": "en", "url": "https://stackoverflow.com/questions/7563680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Camera doesn't work on phonegap when files in server? I wrote a client for my server based on jquery mobile. I just cannot figure out how to transfer photos to my server because when I use GET method to post base64 strings, the server says the URI is too long. So I tried to move the webpages and scripts to server and left a local file to redirect to server page. But right now, I can take photos but there seems have no callback when I finished. Here is what I did var imgTakePhotoStatusBase64="Wyk+HjAxHTAyNzg3MDUdODQwHTAxOR0wMDAwMDAwMDAwMDAwMDAdRkRFQh0wMDAwMDAwHTA0MB0dMS8xHTUwLjVMQh1OHVcgMzR0aCBTdHJlZXQdQXVzdGluHVRYHSAeMDYdMTBaR0QwMDQdMTFaUmVjaXBpZW50IENvbXBhbnkgTmFtZR0xMlo5MDEyNjM3OTA2HTE0WioqVEVTVCBMQUJFTCAtIERPIE5PVCBTSElQKiodMjNaTh0yMlocWR0yMFogHDAdMjZaNjEzMxwdHgQ="; function TextStatus(){ var s=window.prompt("","请输入广播的内容"); if(s!=null&&s!=""){ SetStaus(s); } } $("#pageTakePhotoStatus").live("pageshow", function() { TakePhotoStatus() }); function TakePhotoStatus(){ imageData=""; navigator.camera.getPicture(onTakePhotoStatusSuccess, onTakePhotoStatusFail, { quality: 75 }); } function onTakePhotoStatusSuccess(imageData) { var image = document.getElementById('imgTakePhotoStatus'); image.src = "data:image/jpeg;base64," + imageData; imgTakePhotoStatusBase64=imageData; } function onTakePhotoStatusFail(message) { alert('获取照片失败,因为: ' + message); } function TakePhotoStatusOk(){ try { var myDate = new Date(); var r=myDate.getTime(); var path="uploads.share/"+r+"/"+r+".jpg"; doMethod("ImageUploadByBase64String","{'str':'"+e(imgTakePhotoStatusBase64)+"','path':'"+e(path)+"'}",null, function(result){ doMethod("PublishPhotoes","{'located':'false','path':'"+e(path)+"','text':'"+e("描述:"+$("#txaTakePhotoStatusDes").val())+"'}",null, function(r){ alert("您的照片已经发布"); history.back(); }); }); }catch(err) { alert(err.description); } } But onTakePhotoStatusSuccess doesn't work when I take a photo. When I run it in local, it is just fine. A: Flimzy is right. You should use a POST request to send back those huge images. POST requests are not limited by length like GET requests are. Also, I can't imagine the camera working properly when used from a remotely loaded page. That kind of stuff is typically sandboxed by the platform. I can't say for certain that it wouldn't work, but I would be very surprised if it did. A: Camera works with phonegap, so if the user has your code running as an app it's ok. It won't work as a webapp, because there's no phonegap then. Now the main issue: POST might refuse to work cross-domain (not sure if phonegap can be set to allow it). If you can - use POST. If not, read: GET can hold as much data as the browser is willing to send and the server is willing to catch. There is no standard. IE sends 2048 characters (2kb), FF sends over 100kb etc. You have to test your server and maybe configure it to accept large GET queries. Now the fun part - if you know the length of GET that is avaliable to you, you can transfer data in chunks. * *get length of data and divide by chunk length *send the result as the first query so that the server knows how many chunks to expect *send N more queries with chunks of data Why not send and then confirm that it's all done? Well, it's asynchronous, so you never know. This works. I did some different implementations of sending lots of data cross-domain with JSONP
{ "language": "en", "url": "https://stackoverflow.com/questions/7563682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shutdown iOS programmatically Is it possible to shutdown an iOS device (iPhone, iPad, iPod) with objective c? I have searched the internet through and through, and nothing at all has come up. I was just thinking about it, how much control over the device you really have. Does anyone know if this is possible? If so, how? A: No, it's not possible in a non-"jailbroken" state. Your app cannot escape it's own "sandbox" and consequently has no access to system calls that could be used to control the power state of the device. Not only that, but App Store approval chances for this feature would be slim to none. A: No, this is not possible on a non-jailbroken device. The operating system maintains control over most of the system-wide functions and access to many things, like power, are prohibited.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: .htaccess duplicate static content loading I've made a sub-domain for static content (static.site.com) and I have the following .htaccess: RewriteCond %{HTTP_HOST} www.site.com [NC] RewriteCond %{REQUEST_FILENAME} \.(jpg|gif|png|css|js|txt|ico|pdf)$ [NC] RewriteRule ^(.*) http://www.static.site.com/$1 [L,R=301] Everything is loading fine, but in firebug i have two lines for every file with rewrited path: http://www.site.com/images/image.png (301 Moved Permanently) and http://www.static.site.com/images/image.png (304 Not Modified) How can I prevent loading my content from main domain. Thanks. A: How can I prevent loading my content from main domain. Thanks. Contents don't load from your main domain. when you request http://www.site.com/images/image.png server will send you http://www.static.site.com/images/image.png. Note: as I understand your files are in subdirectory in main domain. so you can change document root of your subdomain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to merge a branch into trunk? I'm facing a peculiar problem with SVN merge. I want to merge from a dev branch to trunk. We have multiple dev branches cut off the trunk at the same time. I'm merging one of those branches to trunk with this command: svn merge trunk branch_1 I see changes that are not part of this branch, getting merged into trunk. What am I doing wrong ? SVN Version : Subversion command-line client, version 1.6.16-SlikSvn-tag-1.6.16@1076804-WIN32. A: If your working directory points to the trunk, then you should be able to merge your branch with: svn merge https://HOST/repository/branches/branch_1 be sure to be to issue this command in the root directory of your trunk A: Your svn merge syntax is wrong. You want to checkout a working copy of trunk and then use the svn merge --reintegrate option: $ pwd /home/user/project-trunk $ svn update # (make sure the working copy is up to date) At revision <N>. $ svn merge --reintegrate ^/project/branches/branch_1 --- Merging differences between repository URLs into '.': U foo.c U bar.c U . $ # build, test, verify, ... $ svn commit -m "Merge branch_1 back into trunk!" Sending . Sending foo.c Sending bar.c Transmitting file data .. Committed revision <N+1>. See the SVN book chapter on merging for more details. Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate A: Do an svn update in the trunk, note the revision number. From the trunk: svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName You can check where the branch was cut from the trunk by doing an svn log svn log --stop-on-copy A: The syntax is wrong, it should instead be svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "135" }
Q: checkbox checking verification HTML: <div> <input> <label> </div> JS: $('div input').live('click',function(){ alert($(this).is(':checked')); }); $('div').live('click,'function(e){ if(!$(e.target).is('input')) $(this).find('input').click(); }); Whenever I click on the input it accurately displays what the input turns into (if I turn on the input it alerts true) But whenever I click on the div/label it does the opposite (when the input turns on it alerts false) Is there a way to test whether the input is being turned on and off in both circumstances instead of 1? [I assume that the reason this is happening because one is triggered by the browser which happens before jquery (even though I assumed jquery should happen first, but whatever) and in the other case the jquery is running before the trigger of the 'checked', but can't seem to figure out how to either delay the trigger until after the script, or force it to run before the script.] Thanks in advance! A: You can monitor change() on the checkbox itself, then on DIV click you can change the value in the checkbox directly and then trigger change() instead of click(). $('input[type="checkbox"]').live('change',function(){ alert($(this).is(':checked')); }); $('div').live('click',function(e){ if(!$(e.target).is('input')) { var $input = $(this).find('input'); $input.prop("checked", !$input.is(':checked')).change(); } }); Also, if your purpose is to avoid the whole <label for="" /> annoyance, check this out. <label><input type="checkbox" value="awesome" /> Check it</label> A: try this: $('div input').live('click',function(){ alert($(this).is(':checked')); }); $('div').live('click,'function(e){ if(!$(e.target).is('input')) $(this).find('input').triggerHandler("click"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7563709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using php to end a loop until match is found This is my first attempt at a php script after a few weeks of learning. So basically I am parsing an XML blog feed. First if gets the blog post date and if it matches today's date based on Los Angeles time zome it will go further and get the current blog post urls for the day. Else it will return "no match". Upon finding blog posts for today if will gather the url of each post. Now here is my issue no matter what i do it always returns no match on the code i am looking for. I assume its not checking each url but since my knowledge is limited I can be certian. I am trying to search each post for a numerical string with regex and if its found I want to echo that string and end the script or if there is no code found echo a message stating that and also end the script. Also if you found a better way or a more efficient way of rewriting my code to clean it up a bit i welcome that too /*------------------------------------------------ //XML File and Parsing ------------------------------------------------*/ //XML document $rss = simplexml_load_file($xmlfeed); //Blog Dates $blogdate = $rss->channel->item; //Blog URLS $blogurl = $rss->channel->item; /*------------------------------------------------ //Date Variables ------------------------------------------------*/ //Original date format: Mon, 26 Sep 2011 22:00:08 +0000 $post_date = $date->pubDate; //Original date format: September 26 2011 $todays_date = date("F j Y"); $timezone = new DateTimeZone('America/Los_Angeles'); //Format blog post dates into PDT $date1 = new DateTime($post_date); $date1->setTimeZone($timezone); //Output date: September 26 2011 $post_date_final = $date1->format("F j Y"); //Format server date into PDT $date2 = new DateTime($todays_date); $date2->setTimeZone($timezone); //Output date: September 26 2011 $todays_date_final = $date2->format("F j Y"); echo $post_date; /*------------------------------------------------ //Checking and Looping ------------------------------------------------*/ //Looping through blog dates for a mtach foreach ($blogdate as $date) { //If dates match continue to gather URLs if ( $post_date_final == $todays_date_final ) { foreach ($blogurl as $url) { $postone = $url->guid[0]; $posttwo = $url->guid[1]; $postthree = $url->guid[2]; $postfour = $url->guid[3]; $postfive = $url->guid[4]; $postsix = $url->guid[5]; $go = array($postone, $posttwo, $postthree, $postfour, $postfive, $postsix); foreach ($go as $stop){ $html = file_get_contents($stop); preg_match('/cd=\b[0-9]{8,15}\b/', $html, $match); $regex_match = $match[0]; if (isset($regex_match)) { echo $regex_match; }else{ echo "no match"; exit; } } } }else{ echo "no match"; exit; } } A: I've only quickly skimmed over your code but I saw this line which you might want to change: if(!isset($regex_match)) It is saying, if $regex_match is not set then echo $regex_match. Meaning if you are trying to echo it when it has not found something. Try taking out that ! and see if that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Warning: preg_match() [function.preg-match]: Unknown modifier Anyone have an idea of why this is popping up? Trying to use this to redirect users based on user agent. This warning comes up when user agent is search bot. Also Windows XP MSIE 8 user agent is being incorrectly redirected. "Warning: preg_match() [function.preg-match]: Unknown modifier 'c' in /.../getos.php on line 36" function getOS($userAgent) { $oses = array ( 'iPhone' => '(iPhone)', 'iPad' => 'iPad', 'Android' => 'Android', 'Windows 3.11' => 'Win16', 'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)', // Use regular expressions as value to identify operating system 'Windows 98' => '(Windows 98)|(Win98)', 'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)', 'Windows XP' => '(Windows NT 5.1)|(Windows XP)', 'Windows 2003' => '(Windows NT 5.2)', 'Windows Vista' => '(Windows NT 6.0)|(Windows Vista)', 'Windows 7' => '(Windows NT 6.1)|(Windows 7)', 'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)', 'Windows ME' => 'Windows ME', 'Blackberry' => 'Blackberry', 'Open BSD'=>'OpenBSD', 'Sun OS'=>'SunOS', 'Linux'=>'(Linux)|(X11)', 'Macintosh'=>'(Mac_PowerPC)|(Macintosh)', 'QNX'=>'QNX', 'BeOS'=>'BeOS', 'OS2'=>'OS2', 'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp/cat)|(msnbot)|(ia_archiver)' ); //'Safari' => '(Safari)', foreach($oses as $os=>$pattern){ // Loop through $oses array // Use regular expressions to check operating system type if(preg_match("/".$pattern."/i", $userAgent)) { // Check if a value in $oses array matches current user agent.<---------Line 36 return $os; // Operating system was matched so return $oses key } } return 'Unknown'; // Cannot find operating system so return Unknown } $operatingsystem = getOS($_SERVER['HTTP_USER_AGENT']); A: Your Search Bot entry has (Slurp/cat) in it. The / is being counted as the end of the regex, and the subsequent c causes the error. (Slurp\/cat) will solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When is a while(True) loop appropriate? Possible Duplicate: is while(true) bad programming practice? What's the point of using “while (true) {…}”? I've always considered it bad practice to use while(true). Many people think it's okay. Why would you want to purposefully create an infinite loop? The only two reasons I can think of are: * *You're being devious *You're being lazy When, if ever, is it appropriate to use this? And why would you use this over an algorithm? A: Sometimes, while(true) is more readable than the alternatives. Case in point: BufferedReader in = ...; while (true) { String line = in.readLine(); if (line == null) break; process(line); } Consider the alternative: BufferedReader in = ...; String line; while ((line = in.readLine) != null) process(line); A: * *In threaded code (concurrent programming).. *In games and for menus *While using C or Fortran(I mean moreso here) Actually you see it a lot...
{ "language": "en", "url": "https://stackoverflow.com/questions/7563719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: How can I detect if the Back button will exit the app (i.e. this is the last activity left on the stack)? I'd like to warn the user if the back press is going to finish the last activity on the stack, thereby exiting the app. I'd like to pop up a little toast and detect a 2nd back press within the next few seconds and only then call finish(). I already coded the back press detection using onBackPressed(), but I can't find an obvious way to see how many activities are left on the back stack. Thanks. A: The droid-fu library does this by checking the stack of running tasks and seeing if the next task is the android home screen. See handleApplicationClosing at https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/activities/BetterActivityHelper.java. However, I would only use this approach as a last resort since it's quite hacky, won't work in all situations, and requires extra permissions to get the list of running tasks. A: The reddit is fun app does this by overriding the onKeyDown method: public boolean onKeyDown(int keyCode, KeyEvent event) { //Handle the back button if(keyCode == KeyEvent.KEYCODE_BACK && isTaskRoot()) { //Ask the user if they want to quit new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.quit) .setMessage(R.string.really_quit) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Stop the activity finish(); } }) .setNegativeButton(R.string.no, null) .show(); return true; } else { return super.onKeyDown(keyCode, event); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Android query using extras in the where statement I having trouble with my database i was wondering how would i be able to connect two variables in a sql query. Example i have a bus schedule that has two tables and im trying to use two put extras to query the results i want but im not sure if im able to use two extras in the where statement to replace the '?' with. I get no errors when i do it but nothing displays but when i take away one of the extras it works but doesnt display the right information that i want. Could someone explain why this wont work if i cant use two '?' at once or if im doing something wrong. enter code here idDay = getIntent().getStringExtra("Day_ID"); idNum = getIntent().getIntExtra("BUS_ID", 0); Cursor cursor = db.rawQuery ( "SELECT A2._id, A2.dayOfWeek, A2.direction " + "FROM TimeTable A2 " + // "WHERE A2._id = ? " + // "WHERE A2.dayOfWeek = ? " + "WHERE (A2._id = ?) AND (A2.dayOfWeek = ?) " + "GROUP BY A2.direction", // new String[]{""+idNum}); new String[]{""+idNum+idDay}); // new String[]{""+idNum}); A: If you use 2 selection args in your query then you need 2 values in the array: new String[] { Integer.toString(idNum), Integer.toString(idDay) } It doesn't matter where you get the values from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: how can an invoking function not handle an exception from sub-function? I learnt an invoking function must either declare or handle all the exceptions the invoked function declares to throw. But following code can compile. public a() throws SipException, NullPointerException { try { } catch (SipException e) { throw e; } catch (Exception e) { throw new SipException("...", e); } } public b() throws SipException { a(); } since a declares to throw NullPointerException, though it does not really do, how can b ignore this please? A: Java differentiates betwixt exceptions that have to be declared or caught, or those that don't. The latter are called unchecked exceptions. NullPointerException is an unchecked exception, which does not need to be declared or caught (so you should remove it from your throws line. Think about it, null pointers can happen almost anywhere in your code; if you had to declare or catch them, every single method would have to do this. Or as this says Those unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be cluttered, pointlessly. A: an invoking function must either declare or handle all the exceptions the invoked function declares to throw. The exception here are RuntimeExceptions, which you do not need to declare. NullPointerException is a RuntimeException. Non-RuntimeExceptions are called "checked exceptions" (because the compiler checks that you think about them). A: Look at Checked vs Unchecked Exceptions. http://www.javapractices.com/topic/TopicAction.do?Id=129 NPE is an unchecked exception, imagine the verbosity of programs if everything had to either catch or declare all possible exceptions! RuntimeExceptions (Unchecked Exceptions) are a key concept to understand. Check out the javadoc. A: There are two main kinds of exceptions: RuntimeException and regular plain-old Exception. You only need to explicitly handle Exceptions. RuntimeExceptions may be ignored and will propagate up the stack exactly as though you wrote "throws NullPointerException" in every signature. There are various philosophies about when to use each type. I subscribe to the idea that RuntimeExceptions should represent coding errors, while checked exceptions represent problems that are "expected" to occur in the somewhat normal flow of the running program. A: In Java, there are two types of exceptions which do not need to be explicitly caught: * *Any exception which extends java.lang.Error *Any exception which extends java.lang.RuntimeException These two exceptions exist to denote exceptions which are indicative of fatal errors. Errors which cannot be recovered from should not be caught in the first place, rather the programmer should let the program fail. So the language allows you to omit the annoying try {} catch {} boilerplate in these situations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best way to encode string by public-key in python Is there any way to encode string by public-key? I found two packages, pycrypto and m2crypto. But I can not find how to use them. A: To encode a string using public key: #!/usr/bin/env python from M2Crypto import RSA, X509 x509 = X509.load_cert("recipient_cert.pem") rsa = x509.get_pubkey().get_rsa() print rsa.public_encrypt("your string to encrypt", RSA.pkcs1_oaep_padding)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I stop auto increment on ignored inserts that make no changes in MySQL? I am inserting say 500 rows using INSERT IGNORE, if the row already exists (based on a unique field) then it simply does nothing, if not it inserts the row. My problem is that say only 10 do NOT exist the auto increment still increases for every insert so it goes up by 500 so I end up with gaps in my id's. How do I stop this? I have tried: SET global innodb_autoinc_lock_mode = 0; But I get the error: 1238 - Variable 'innodb_autoinc_lock_mode' is a read only variable How do I change this? A: According to MySQL's documentation, the innodb_autoinc_lock_mode is not a dynamic variable and, thus cannot be changed while MySQL is running. You'll either have to set it in the command line --innodb_autoinc_lock_mode=0 or in the configuration file (mysql.ini) innodb_autoinc_lock_mode=0 It should be noted that you should not (read: never) rely on a continuous id sequence. Rollbacked or failed transactions may result in gaps. A: I had the same issue and I set the InnoDB auto_inc_lock_mode to 0 and it worked just once but I encountered the same problem again. Luckily I found a way to solve it. ALTER TABLE `nameOfTable` AUTO_INCREMENT=1; You can enter this query to reset the jumping indices or better still the GUI of phpMyAdmin has an Operation tab. Go to Operations > Table Options and change the AUTO_INCREMENT value manually. You can also do this: SET @num := 0; UPDATE your_table SET id = @num := (@num+1); ALTER TABLE your_table AUTO_INCREMENT =1; From this source .
{ "language": "en", "url": "https://stackoverflow.com/questions/7563733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Programming Library for Matrices over GF I am looking for a Library in Java or C for doing matrix operations (mainly RANK) over certain Finite Field (GF). I used Jama, but it has no Finite Field Functionality. any help appreciated. A: C The best thing I would recommend to you is to use NTL library. You will be probably interested in classes: * *mat_GF2: matrices over GF(2); includes basic matrix arithmetic operations, including determinant calculation, matrix inversion, solving nonsingular systems of linear equations, and Gaussian elimination *mat_GF2E: matrices over GF2E; includes basic matrix arithmetic operations, including determinant calculation, matrix inversion, solving nonsingular systems of linear equations, and Gaussian elimination It also supports rank operation you mentioned. For more modules/classes please refer to the documentation. JAVA currently I am using BouncyCastle library that has some basic support for GF2, GF2^n matrices. Personally I am using source code of BouncyCastle library extending it on my own for desired features. A few useful methods are private/protected. Please refer to JavaDoc for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: c++ generic pointer? void pointer? I am writing a program that can take in either 3 ints, or 3 floats in the constructor(I suppose I will need 2 constructors for this). I want to declare an array and store the values in the array "numbers". If I don't know which constructor will be called I am not sure how to declare "numbers"(as an int array or as a float array). Is there a good technique to get around this? or can I create an int array and a float array and somehow have a generic pointer to the array being used(is using a void pointer the best way to do this)? A: Looks like you want a templated class. template <class T> class Foo { public: Foo(T a, T b, T c) { numbers[0] = a; numbers[1] = b; numbers[2] = c; } private: T numbers[3]; }; A: Can't you use templates for that? example: template <class T> class Foo { public Foo(T a, T b, T c); }; // Foo<float> aaa(1.0f, 1.0f, 0.5f); Foo<int> bbb(1, 2, 3); A: Why not to make class Foo { public: Foo(double a, double b, double c) :_a(a), _b(b), _c(c) {} virtual double get_a() {return _a;} virtual double get_b() {return _b;} virtual double get_c() {return _c;} // more methods protected: double _a, _b, _c; }; works well for both ints and floats: Foo ifoo(1, 3, 5); Foo ffoo(2.0, 4.0, 6.0); and for mixing them: Foo mfoo(1, 4.0, 5); douable storage space is more than enouh for both int and float
{ "language": "en", "url": "https://stackoverflow.com/questions/7563741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MSDTC transaction timeout issue I'm facing a MSDTC transaction timeout issue now. For historical reason, we still have lots of legacy code running DB operations by C++ ODBC, and the connection is escalated into MSDTC by default. The issue is when I try to perform a lengthy operation which takes longer than 1 minute, the transaction will be disposed by MSDTC automatically, I found that it's possible to change this value by Component Services administrative tool, However can I set this timeout value programmatically? Any reference will be appreciated, thanks in advance. A: My name is Tony and I work with the Distributed Transaction Team here at Microsoft Support. I have read your post and believe I understand what you're asking for. Here's a code sample I wrote to make the change at the component level. I hope this helps you: //Connect to the machine COMAdmin.COMAdminCatalog m_objAdmin1 = new COMAdmin.COMAdminCatalog(); m_objAdmin1.Connect(System.Environment.MachineName.ToString()); //Get a list of COM+ Applications COMAdmin.COMAdminCatalogCollection objApplications = (COMAdmin.COMAdminCatalogCollection)m_objAdmin1.GetCollection("Applications"); objApplications.Populate(); COMAdmin.COMAdminCatalogObject appToFind = null; //Find the application you want to change for (int i = 0; i < objApplications.Count; i++) { appToFind = (COMAdmin.COMAdminCatalogObject)objApplications.get_Item(i); if (appToFind.Name.ToString() == "MSTEST") { break; } } //Now find the component in the application you wish to change COMAdmin.COMAdminCatalogCollection objComponents = (COMAdmin.COMAdminCatalogCollection)objApplications.GetCollection("Components", appToFind.Key); objComponents.Populate(); COMAdmin.COMAdminCatalogObject ComponentsToFind = null; for (int i = 0; i < objComponents.Count; i++) { ComponentsToFind = (COMAdmin.COMAdminCatalogObject)objComponents.get_Item(i); if (ComponentsToFind.Name.ToString() == "tdevere_vb6_com.Tdevere") { break; } } //Set the Transaction support option //Enable the overide option //Set the new value for the time out option COMAdmin.COMAdminTransactionOptions temp = (COMAdmin.COMAdminTransactionOptions )ComponentsToFind.get_Value("Transaction"); ComponentsToFind.set_Value("Transaction", COMAdmin.COMAdminTransactionOptions.COMAdminTransactionRequiresNew); ComponentsToFind.set_Value("ComponentTransactionTimeout", 120); ComponentsToFind.set_Value("ComponentTransactionTimeoutEnabled", true); //Make sure to save the changes objComponents.SaveChanges(); objApplications.SaveChanges();
{ "language": "en", "url": "https://stackoverflow.com/questions/7563743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Aligning JW Player and jQuery UI Datepicker side-by-side I'm trying to get JW Player and a jQuery UI Datepicker to sit side-by-side on a page (example at here). From what I've read, I'm supposed to apply float: left; to both elements in order to do this but that doesn't seem to work. Here are screenshots to illustrate what I'm trying to do: Actual Intent
{ "language": "en", "url": "https://stackoverflow.com/questions/7563751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stack returning Objects instead of Integers I'm trying to implement a program that involves an array of stacks. Each stack takes in Integer objects, but the problem is when I try to get an Integer object from the stack: import java.util.*; public class Blocks { public static void main(String[] args) { System.out.println(); Scanner input = new Scanner(System.in); Stack[] blocks = new Stack[input.nextInt()]; for (int i = 0; i < blocks.length; i++) {blocks[i] = new Stack<Integer>();} //initializing main array of stacks of blocks for (int i = 0; i < blocks.length; i++) {blocks[i].push(i);} //add first block to each stack Stack retainer = new Stack<Integer>(); //used for when moving stacks of blocks instead of one block. boolean m; //move or pile boolean on; //onto or over int fromBlock; //block being moved int toBlock; //block where the fromBlock is being moved String command = input.next(); while (!command.equals("quit")) { m = command.equals("move"); fromBlock = input.nextInt(); on = input.next().equals("onto"); toBlock = input.nextInt(); if (m) //put back blocks on fromBlock { if (on) //put back blocks on toBlock { int holder = blocks[fromBlock].pop().intValue(); //I get a compiler error here moveOnto(blocks, holder, toBlock); } else //fromBlock goes on top of stack on toBlock { } } else //bring blocks on fromBlock { if (on) //put back blocks on toBlock { } else //fromBlock goes on top of stack on toBlock { } } command = input.next(); } } void moveOnto(Stack[] array, int sBlock, int rBlock) { } } The error says that is doesn't recognize .intValue(). Obviously that is a method of Integer, and I found out from that point that it's returning Object objects instead of Integer types. How can I make it return Integer types? A: To define an array of generic you need to do this. @SuppressWarnings("unchecked") // to avoid warnings. Stack<Integer>[] blocks = new Stack[n]; Then you can write int holder = blocks[fromBlock].pop(); And yes, it does compile and works just fine. EDIT: Why the compiler can't let you do Stack<Integer>[] blocks = new Stack<Integer>[n]; or Stack<Integer>[] blocks = new Stack<>[n]; to mean the same thing is beyond me. A: int holder = blocks[fromBlock].pop().intValue(); //I get a compiler error here Change that to: int holder = ((Stack<Integer>blocks[fromBlock]).pop().intValue(); You will get a compiler warning. Contrary to all the wrong answers here, you can't have an array of a generic type in Java. A: Use the Stack Generic version of Stack i.e. Stack<Integer>[] blocks = new Stack<Integer>[input.nextInt()]; you have to include the generic parameter on the declared type i.e. Stack<Integer[] blocks; A: (oops - Java doesn't allow arrays of generics) Change your Stack variable declaration to use the generic version of Stack: Stack<Integer>[] blocks = new Stack<Integer>[input.nextInt()]; Otherwise when you access the non-generic stack's .pop() method it just returns an Object which you would need to cast back to an Integer In order to access Integer methods like intValue(): int holder = ((Integer)blocks[fromBlock].pop()).intValue(); (But you won't need to cast if you fix the declarations.) A: You need to change the type of blocks to Stack<Integer>[]. edit: Code compiles fine. You get a warning, which is there to remind you that a bad array assignment can still occur at runtime, so the compiler cannot guarantee you won't get a ClassCastException at runtime if you write buggy code. However, the posted solution does exactly what the OP wants: public static void main(String[] args) throws Exception { Stack<Integer>[] array = new Stack[] { new Stack(7) }; Integer result = array[0].pop(); } class Stack<T> { private final T foo; public Stack(T foo) { this.foo = foo; } T pop() { return foo; } } ps. to clarify, that warning is there to point out that even though you aren't casting explicitly, you can still get a ClassCastException at runtime, as in the following code: public static void main(String[] args) throws Exception { Stack<Integer>[] array = new Stack[] { new Stack(7) }; Stack notAnIntegerStack = new Stack<Object>(new Object()); array[0] = notAnIntegerStack; Integer result = array[0].pop(); // class cast exception at runtime } There are warnings all over this code pointing out the danger, but it will compile. Hope that clears things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php explode help I have this data set from a textarea P234324, 2011-03-23 12:34:37 \nP234434, 2011-03-23 13:34:36 \nP438794, 2011-03-23 14:34:36 \nP238924, 2011-03-23 15:34:36 \n I would like to explode it to this, but the multiple foreach is throwing me. $data['P234324'] = "2011-03-23 12:34:37" $data['P234434'] = "2011-03-23 13:34:36" $data['P438794'] = "2011-03-23 14:34:36" $data['P238924'] = "2011-03-23 15:34:36" A: This will work: $old_data = ...; //your string $data = array(); $pairs = explode("\n", rtrim($old_data, "\n")); foreach($pairs as $pair) { $components = explode(',', $pair); $data[$components[0]] = trim($components[1]); } codepad example
{ "language": "en", "url": "https://stackoverflow.com/questions/7563754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I filter to only null/empty dates in jqGrid? I'm building an ASP.NET MVC 3 application and using the jqGrid to display tabular data. In one of my grid displays I show recipe data and there are a couple of date columns where I don't always have a date for the data. Using the date picker I can filter to things that have a particular date or happen before/after a particular date. But how can I filter to things that are missing a date? The workaround I'm using right now is to sort the date column and that'll get me easily enough to the missing dates but I'd like to be able to easily answer the question "How many recipes are missing the last prepared date?" Any ideas for this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7563760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: is group chat for facebook implemented in the API? I know that the feature for user to user chat is implemented in the API, but I was wondering if they implemented the ability to access the group chat (the chat you can have with your facebook group) has been implemented. I don't see anything about it in the doc, so I was wondering if any one here would know. If it is possible to create apps that utilizes group chat, can some one point me in the right direction (doc for it, etc.)? A: This was answered by one of the Facebook staff on January 18th in the Facebook XMPP Developer Relations group: "[Multi user chat] is not currently on the XMPP roadmap, but definitely belongs on the wishlist." This goes for both arbitrary friend chats and chats defined by members of a Facebook group.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: why Session attributes are officially not thread safe in Servlet? I am reading some servlet text regarding scope of attributes in Java servlet. In the text, the author wrote: "Session attributes are officially not thread safe." This confused me because I thought that one user only has a specific session, no one can access of the others. If so, session attributes are thread safe. Or am I misunderstanding something?? A: This confused me because I thought that one user only has a specific session, no one can access of the others. If so, session attributes are thread safe. Well, if that was the case, session attributes need not be thread-safe. That is different from saying they are thread-safe. The lack of thread safety might be a problem if you have more than one thread handling the same user's session at the same time. Maybe some parallel executions that you spawned from the main request worker thread. Or the same user accessing the server more than once (such as loading five frames at the same time). A: Session attribute is not thread safe. From this document (Java theory and practice: Are all stateful Web applications broken?) When a Web application stores mutable session data such as a shopping cart in an HttpSession, it becomes possible that two requests may try to access the shopping cart at the same time. Several failure modes are possible, including: 1. An atomicity failure, where one thread is updating multiple data items and another thread reads the data while they are in an inconsistent state 2. A visibility failure between a reading thread and a writing thread, where one thread modifies the cart but the other sees a stale or inconsistent state for the cart's contents Have a look at thread from coderanch; * *How HttpSession is not thread safe *Are Session thread safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to flatten a WPF TreeView I need a control that behaves like a treeview (binds to a tree structure, expands child nodes based on IsExpanded property of bound object), yet displays data like the grid (no indenting, or toggle images). The expand collapse will be happening automatically based on bound object. TreeView is perfect, i just need to remove the indentation and the triangle image to make it vertically flat, like a grid column. I suppose i could try overriding the TreeViewItem template, but that just doesn't display anything.. A: Based on the TreeView style on MSDN, something like this should work: <Style TargetType="TreeViewItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="TreeViewItem"> <StackPanel> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="ExpansionStates"> <VisualState x:Name="Expanded"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="ItemsHost"> <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}" /> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Collapsed" /> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <ContentPresenter ContentSource="Header" /> <ItemsPresenter Name="ItemsHost" Visibility="Collapsed" /> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> A: You need a TreeListView (it combines the TreeView and ListView at TreeViewItem template level beautifully) http://msdn.microsoft.com/en-us/library/ms771523.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7563771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to calculate work hours per project per employee I have a PHP form that inputs empID, projectNumber, and clock-in/clock-out time-stamp into a MySQL table like this: Having no reputation, I can't post image, so take a look here: screenshot http://mailed.in/timecard/ss1.jpg I need help in generating a report that looks like this: screenshot http://mailed.in/timecard/ss2.jpg Can I do this entirely in MySQL? How? A: This may help you : SELECT empID AS EmpID, projectNumber AS ProjectNumber, DATE(clocktime) AS StartDate, TIMEDIFF( (SELECT max(clocktime) from tableName where DATE( `clocktime` ) = CURDATE( )), (SELECT min(clocktime) from tableName where DATE( `clocktime` ) = CURDATE( )) ) AS WorkHours FROM `tableName` WHERE DATE( `clocktime` ) = CURDATE( ) GROUP BY empID A: Try this query - CREATE TABLE table_proj ( empid INT(11) DEFAULT NULL, projectnumber INT(11) DEFAULT NULL, clocktime DATETIME DEFAULT NULL ); INSERT INTO table_proj VALUES (1, 1, '2011-09-27 10:02:22'), (1, 1, '2011-09-27 11:17:32'), (2, 2, '2011-09-27 11:34:13'), (3, 3, '2011-09-27 11:01:21'), (3, 3, '2011-09-27 13:36:28'), (2, 2, '2011-09-27 13:55:39'), (4, 4, '2011-09-27 14:25:07'); SELECT empid, projectnumber, MIN(clocktime) startdate, TIMEDIFF(MAX(clocktime), MIN(clocktime)) workhours FROM table_proj GROUP BY empid, projectnumber HAVING COUNT(*) = 2; +-------+---------------+---------------------+-----------+ | empid | projectnumber | startdate | workhours | +-------+---------------+---------------------+-----------+ | 1 | 1 | 2011-09-27 10:02:22 | 01:15:10 | | 2 | 2 | 2011-09-27 11:34:13 | 02:21:26 | | 3 | 3 | 2011-09-27 11:01:21 | 02:35:07 | +-------+---------------+---------------------+-----------+
{ "language": "en", "url": "https://stackoverflow.com/questions/7563772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: @ symbol valid in Unix username? A client has given me SSH access to their web server with the username firstname.lastname@email.com (my email address). I've tried: ssh firstname.lastname@email.com@555.555.555.555 ssh firstname.lastname+email.com@555.555.555.555 and several other combinations, but no luck. I don't know anything about the server environment, other than that it's some flavour of Linux. Before I come back to them saying it doesn't work, perhaps I'm missing something? A: Ubuntu Linux is happy to create a user with an at symbol in the name. I created user bob@home and was able to log in using the syntax ssh bob@home@myserver as well as with the syntax ssh -l bob@home myserver Try using the -l switch to specify the username and see if that works. A: If it's password authentication, you could always do: ssh 555.555.555.555 then enter your username.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting canvas to pdf I've been looking into this for a while, but the closest thing I've come up with is .toDataUrl(), which seems to only be used for bitmap image formats. What I really need is to be able to save the canvas contents to a pdf, and be able to specify page breaks where appropriate. Is there a function in javascript to do so, or will I have to do this with an apache command line tool? A: It is possible to generate PDF documents using Javascript, but I'm yet to come across a framework that is mature enough to use. What you could do is use some PHP PDF library, such as FPDF, and post your image data to a PHP script that generates the PDF document. Better yet you could use the AJAX method to generate the PDF without a page refresh. When attaching images just specify the data URL as the image URL (although I haven't tested, it should work). A: try pdf.js....idk if it'll work with canvas off the bat, but worth a looksie http://badassjs.com/post/708922912/pdf-js-create-pdfs-in-javascript GitHub Link
{ "language": "en", "url": "https://stackoverflow.com/questions/7563782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What are common methods of sending initial configuration variables to an Ajax client on the page load? A complex web-app can have a large amount of user and/or context specific meta and configuration information. eg, user's preferred result-set size, timezone, beginning of the week (Sun/Mon), etc. What are the possible ways to transport the variables to the client application as it is loading (hidden variables? JSON embedded somewhere?), and what are the pros/cons of each method? I know of a few ways to hack things together, but I'm curious if anyone has identified good design patterns to use, or best practices they can share. Although I'd prefer general info on this, my primary stack is jLAMP (jQuery, Apache, MySQL, PHP) EDIT: I already have applications that do this, so I'm not looking for a quick fix, or suggestions for an entirely different paradigm (as in, not loading config). I'm looking for a discussion with the options and pros/cons of each, so that I might tune what I have, or a new user would be presented with plenty of options to make a good design decision from the start. Thanks! A: As others have pointed out, if there is a lot of information to transport during the loading of your application I would not recommend using AJAX, since you're putting an overhead on your connection. My chosen method would be to render all the configuration information on the head tag of your application, using PHP, that way, once your events get triggered (after the DOM has finished loading I would assume), you have all the information at your disposal. Code example: <head> <script type="text/javascript"> //Some js code here.... var myConfigurationName = "<?=$myConfigurationNameFromDatabase;?>"; //Some more js code here... </script> </head> The way you format your configuration data is completely up to you, it all depends on how related all of it is, or in how many different places / objects / functions you might need to use it. You could create some different configuration objects depending on your data, or only one that concentrates all of them. It really depends on the application design you have so far. If you have a strong OO design on your JS code, you could check out this site and see if any of the basic patterns match your needs. Feel free to elaborate a bit more on your design (if you can) to help us understand where you stand and how we can help you. Happy coding! A: For me it's passing in a JSON array. It's so flexible on the client side I'm not sure why you wouldn't use it. On the backend I build it up using a regular PHP array and then just convert it to JSON using json_encode before echoing to the webpage. <script>var myObject = <?=$mySettings?></script> and you're good to go. As a bonus I just convert the json object to a string before I pass it back to PHP using a single variable in a post and convert it back to a PHP array for manipulation and inclusion into a database. A: So far I use a php file to store custom setting for my application. Then include them in a page as I need them. Don't forget to set content type to "text/javascript" As illustration, my configuration file will look like: <?php header('Content-type: text/javascript'); ?> var myApp = { // setTimeOut id timeoutID : null, // Cards clearance delay cardsClearanceDelay : 1500, // Add other attribute as needed } And include them in the page <html> <head> <script type="text/javascript" src="web/get_configuration"></script> </head> I build my application using CI, web/get_configuration just calling controller action to render my javascript configuration file. A: Have you ever tried jQuery taconite . http://jquery.malsup.com/taconite/ JSON is a great data exchange format. But it's not the best solution for every problem. In comparison, the Taconite model only requires that the server return valid XHTML. There is no coding required on the client at all! A: First you need to figure out what is more important for you - fine tuning server preference, user side performance, modularity, or something else. So you could load configuration for each module in some separate way with a separate class or even hardcode some stuff in JS. You would gain agility but it would be an overall mess, but it might be a mostly working mess. Probably depends on how isolated the coding teams or developers of modules are. Instead of spreading configuration across modules you could separate different kinds of configuration: * *Some temporary configuration can be stored in localStorage (or similar, even cookies) and you will gain from adding events that can push the configuration to all open tabs. Of course this would be great only when one user has only one computer, but you could still allow to save this configuration to your server. *User preferences might be put in one serialized object (JSON is pretty light) and sent with AJAX calls. You could cache this settings on PHP side after user would change them and simply serialize key-value pairs. *Site-wide configuration should probably be made separate as it would rarely changed and could be stored in a JS file. You want to load it after page load? Fine - you can do that to with AJAX and then run eval. What would you gain? You could also load the same JS file statically and it would be cached by the browser and not loaded every time and wouldn't be touched by PHP interpreter at all. And you could mix all this as it mostly happens in most cases of big websites I've seen. As for the format I would prefer JSON. It's pretty light (especially when comparing to XML) and you can GZIP it nicely to make it even lighter. JSON is also easily extend-able over time (you can add and remove options without fatal failures) and is almost JS native. As to how generate JSON... Well CACHE IT. Beside some specific things preferences most of the configuration options won't change too often (not as often as being read). Also note that configuration may be understood in many ways - in MediaWiki/Wikipedia you can add your own JavaScript. Also you may want to express more options then it is needed if you want your users to create some extra scripts. A: Simple persistent user selected options are probably best set by cookies. Everything more complex is better handled by json values. Obviously you could put custom javascript code into your header to set js variables, but this requires you to render code dynamically, which is (IMHO) ugly and error prone. On the other hand you can render custom meta tags holding all your custom data, and read it out by javascript later. My simple and elegant solution in the past was to just render json in a script tag in the header <script id="initparams" type="application/json"> [ output of json.dumps({a: "AAA", ....}) ] </script> And later in a jQuery document ready handler (which may be loaded from an external file): var initparams = $.parseJSON($('#initparams').html()); Since I use json dump and parse on both sides no chance for wrong escaping or an injection attack. I've done the same embedding json params in <div class="options"> for options belonging to a jstree or data table, when I needed just a few local parameters not warranting an AJAX call. You can either hide the div.options by CSS, or remove it from the dom when parsing it: var tableoptions = $.parseJSON($('table.mydata > div.options').remove().html());
{ "language": "en", "url": "https://stackoverflow.com/questions/7563788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to change the visibility when the click is outside of the control I have a User control in WPF that is built on MVVM format. The usercontrol is a collection of viewmodels arranged in a panel. The number of pannels (or related views/ view models) will be decided at run time. Each panel is a user control and refers a view model (case as workspaces). Each pannel consists of a button and a listbox. Initially when loaded only the buttons of all the pannels will be shown. On click of button the corresponding List box would be shown. Till this it is working fine. What i need is if the user clicks on any other area the curent open listbox should collapse. If user selects another button, that listbox should be shown and this current open list box should be collapsed. Currently it shows on button click but never closes For showing the list box i am using the below code in the button trigger : <Button.Triggers> <EventTrigger RoutedEvent="Button.Click"> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.Target="{x:Reference ListBoxDrop}" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </Button.Triggers> Any suggestion ? * *Girija A: just add another trigger! <Button Content="Button" Height="23" Name="button" Width="75" > <Button.Triggers> <EventTrigger RoutedEvent="Button.Click"> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.Target="{x:Reference ListBoxDrop}" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Visible}"></DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> <EventTrigger RoutedEvent="Button.LostFocus"> <BeginStoryboard> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.Target="{x:Reference ListBoxDrop}" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Visibility.Collapsed}"></DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </EventTrigger> </Button.Triggers> </Button> A: Fred's answer might just be it. However the expected behavior for the user is for the listbox to get focus on button click. So the the button will lose focus even when the corresponding listbox (or its item) is selected by the user. Thus hiding the listbox again. I would suggest to modify it like this: <ListBox.Triggers> <EventTrigger RoutedEvent="GotFocus"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="myListBox" Storyboard.TargetProperty="Opacity" Duration="0:0:0.1" To="1"/> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> <EventTrigger RoutedEvent="LostFocus"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimation Storyboard.TargetName="myListBox" Storyboard.TargetProperty="Opacity" Duration="0:0:0.1" To="0"/> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </ListBox.Triggers> And for the corresponding button, set an event handler in codebehind... private void Btn_Click(object sender, RoutedEventArgs e) { myListBox.Focus(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to download a file with HTTP POST? Is it possible to download a file with HTTP POST? I know the "Get" way(windows.location), but in my case, there are a lot of param that should be passed to server A: In some sense, every HTTP GET or POST is "downloading a file", but it's better to think of it as the message payload rather than a file. In most cases, the payload is an HTML document that the browser should render as a web page. But what if it's not an HTML document? What if it's a zip file for which the browser should offer the user a "Save as" dialog? Obviously, the browser must make a determination about the content type of the response and handle it correctly. One of the most common ways that a browser determines the content type is through a HTTP header called, accordingly, "Content-Type". This header takes the value of a mime-type. This is the key to browsers doing content specific things like firing up an acrobat plugin when the response contains a pdf file, etc. Note, not all browsers 1) determine the content type in the same way, and 2) react to the content type in the same way. Sometimes you have to toy with setting the headers to get the behaviors you want from all the browsers. All server side technologies allow you to set HTTP headers. A: I managed to solve it using this: service.js downloadExcel : function() { var mapForm = document.createElement("form"); mapForm.target ="_self"||"_blank"; mapForm.id="stmtForm"; mapForm.method = "POST"; mapForm.action = "your_Controller_URL"; var mapInput = document.createElement("input"); mapInput.type = "hidden"; mapInput.name = "Data"; mapForm.appendChild(mapInput); document.body.appendChild(mapForm); mapForm.submit(); } Spring Controller Code : @Controller @PostMapping(value = "/your_Controller_URL") public void doDownloadEmsTemplate( final HttpServletRequest request, final HttpServletResponse response) throws IOException, URISyntaxException { String filePath = "/location/zzzz.xls"; logger.info("Excel Template File Location Path :" + filePath); final int BUFFER_SIZE = 4096; ServletContext context = request.getServletContext(); String appPath = context.getRealPath(""); String fullPath = appPath + filePath; File downloadFile = new File(fullPath); FileInputStream inputStream = new FileInputStream(downloadFile); String mimeType = context.getMimeType(fullPath); if (mimeType == null) { //mimeType = "application/octet-stream"; mimeType = "application/vnd.ms-excel"; } logger.info("MIME type: " + mimeType); response.setContentType(mimeType); response.setContentLength((int) downloadFile.length()); String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName()); logger.info("File Download Successfully : "); response.setHeader(headerKey, headerValue); OutputStream outStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); } inputStream.close(); outStream.close(); } A: You mean like this ? function IssuePostRequest(objData) { var strPageURL = "about:blank"; var strAction = "@Url.Action("GetPDF", "Home")/"; //var strAction = "/popups/delete.aspx"; var strWindowName = "MyEvilHttpPostInAnewWindow"; // ifrmDownload var iWindowWidth = 805; var iWindowHeight = 625; var form = document.createElement("form"); form.setAttribute("id", "bla"); form.setAttribute("method", "post"); form.setAttribute("action", strAction); form.setAttribute("target", strWindowName); form.setAttribute("style", "display: none;"); // setting form target to a window named 'formresult' // Repeat for all data fields var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", "data"); hiddenField.setAttribute("value", objData); form.appendChild(hiddenField); // End Repeat for all data fields document.body.appendChild(form); // creating the 'formresult' window with custom features prior to submitting the form //window.open(test.html, 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no'); //JS_PopupCenterScreen(strPageURL, strWindowName, iWindowWidth, iWindowHeight); window.open(strPageURL, strWindowName); // document.forms[0].submit(); //document.getElementById("xxx").click(); form.submit(); } // End Function IssuePostRequest With this Server code: public FileResult GetPDF(string data) { //data = @"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAAA8CAYAAACZ1L+0AAAABHNCSVQICAgIfAhkiAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAuhSURBVHic7Zx5kBT1Fcc/r2f2EhZQDq9IvBADiRoGROWaBXcWTCokhaIVb4scRaQUhlJMorCgUiizSoyliWKZMjGR9UghCswSaQVEgQZEJAoiQiJqonJ44B7TL3/0zO7M7Bw7uz0Dhv1WTc30r1+/95vf6/f7vd97r1tUlaMRaklfoB+wRnz69eHqhxytCgBQS7oBU4DuwCPi0x2F7sNRrYAY1JLBwNPRzyzx6ReFkm0UStCRDPHpBmAYMBp4Wy25rFCyC6uANVLONikuqMw2Qnz6ATAC2AAsUkuWqiU98y23cArYJsV2KTMZQFPBZOYI8emXwATgBWAs8LpacnY+ZRZIASIcYpEBD4HahZHZPohPI8BE4HXgDOA1taQyX/IKo4CNLMRgOT7dWRB5HYT49Cvgh8AOHA/pRbXk+rzIyrcXZFtyuyEMZJBekVdBeYBa8h1gI1AKRIDx4tMX3JSRXwvYJDeIMB7lhrzKyRPEp/8EZkUPPcBTaonPTRn5U8Aq6a02t4tNCMekv6mYD6yP/u4CLFFLvu0W8/xNQRtlocJZMkhH5EdA4aCWDAQ2AUXRps3AEPFphz26/FjAOrlQlQmiPNkm+k0ymPVyUV764gLEp28Bj8c1nQcE3eCdFwWoh1nATt7jj1mJN0s/O8Ikhuir+eiLi5gLCXuYmWrJ6R1l6r4CLJkEjFGo5TKNZKRdJz2x+ZMhTHO9Hy5DfLoL+HNcUxnwcEf5uquAd6VE4SaEd4zPuT8j7TYpVg9/B279Bi3SdwPxG8lKteQnHWHoqgIiB7ga+K7AKvxZYuyHmK3KOwzSVW72IZ+IhqvNpOapHeHpqgJEGQ0QsZvdttTYIqcpTDRs7nFTfoFQm3Q8Qi05t73M3FPAu1IiwlCUjz3C0xlpm5grwmrO1+1Z+R550dPnSJyGAG5sLzP3FLCficDpwFZ8eiAt3Wa5RG0qGyM8kJWnJUUcYgaIuNbPDkJ8+jHwSlLzlWrJce3h554ChDEAYrAlE5na3IjB2qIhmnmaQgThiUMNLIQjLm33fNJxGTCuPYzcUcA2KVa4AFBgZVq69XICygWibMzK0+JelDVlF+oHrvTRXaS6efztYeTtWD+i+IqxCP1R/gUsS0dmCzcIlKMsychvq5yiwkgZxFBX+uc+NuGsA/E38Kj2MHLHApTTor8+xaeN6cjEYDiwncG6LiO/Bu4R4YkjcOoBIJq0T3Yg+qklJ+XKyx0FGPSKfu9LS7NF+qAMFcm8RrBWTlZlCCX8wZW+5Q9WiracrcCtRdhJXivpvZ9GJgDHAW9n5FTEdcAWBmiDS33LF95N0dYvVyauKECjFqCawQKgN4CtfJaRl3CROOHeIx37U7T1zpWJOxZgOwowJKMCekZp3k9LUSse4PvAa670K79IpYA+uTJxxwtSeiNkXANs6CkQQUlf/ncWJ9BENyIZaFJhs/QgwrXAbnwsLlDlhSsKcMECRDA4FgCbgxmoeuF0+sN0NE0NnAk08lV6mlScNcJ6hfsVnrOtgsWXjhQFqKI4C6bQNT0ZPRC+yBSmEDgN4UDWSGo8NuEDzozjUajqi1RWVpSiLSPc8oI+j34fm5ZCiKB4o/N8SngM9qMU5xT7KWEL8J/YoUJdm6/tGFLdbDkX9bqzBsQUoOkVILBTlSZOpwRInYBpYjsedrGWUi7kUJskD9AG2SQVts0UA3ZLccH2D+XR7y+BPThjkHmDmQKuVEXoBlmKMBblWRmsEzrM8BsAtWQccDawUHyadu3LhmYLCITMcuB4nFK8LqSfnhqA3cDecNCvAAr7BEASLaBy3oq+eLytEtdNX7J65Ux/E0BV6KWRthrtmgpF2e8tPfReY33ZoJZGmuqC/tXV1dXG6i6jRiZfYxh2w/JpozMWAIy9f9WJkaZI/1TnPJ76LcumVn0mPl0KLA2ETA+m2Q/HIrqSftyacKao/eGg//1YozcQMj3AQ8C1QC7JjzcDIfPScNC/3fCwI+r49YgnEG9RLej5yRcWd2ESsBBAMcIilOQgNx4vNzaWzRBJiMAeAHqYjCouktaRWVWDqpqXhmVSgm1HHhQhZa63iZJxwLJAyPQCVwO3keMOOBAyXwPuDgf9zxtRBj8jt8EH+B6wIRAyuzUpsT/TPXaycv7KH6QafAA15I5LHlja3kHvMGw17kx3bux95pmojG8DmyDwGO0IP+CE7hcHQmalAbQy0xxQDgz1lrIS2KvxmSLDmJ32KtW+jQ3H/LwDcjsEgYqxNS9XpDqnEZ0GmnFKDITMEuAmF7oyyQuck9T4DPAgtPJCPFHa35M4z53CAG3AkncMm9sAqkLmjwVa5mXEVrRW4PLmFvQ3P6pestDodszISNIaYNgMVOHRFlo+slNMCUrkoODp1vb/K3ZscG10DjA8/uzFc//R0yj2XJd0UROtvcWLgBOT2l7HKeQ9gJOYiocXZ8GeT9wsAYz20nrRWBAO+tOViqwJhMyTidv44CzICFzJEP1IQAJIdWIfdFFJo3dyQ1FkHGhswI7/ukvXKeGp/nnJQiprTCTucoX6umn+lPGhyhrzgjR9TQFdRGyjpgy7+D5z7Iqp/uYEklHinYxqWQu9vKpoT4HkBTlZ6QeB4eGgP1Ot6OpAyNwHCQULXb3ANhLj2H8LhMwncXz1ehyvJ/apx4lUmsDOcNC/q/kqn34IEAiZEzTRqtQw9M4lM4bvC8xfuQCR21v+n9xSOW/Fw3W3Xpw+jO0mbOZhcCnRO9qIMIdoBq+i2iwt6ioJ1Q2KPRtkQQpOpUnHH2UZ/BiSkzilBq0jjycB04E7gLuAe4EFOJ7SYzh1MXXAe4GQuTwQMpt3hNXV1Ya21NPH8MyyqRVvATR6pQbicwZ6nHg8rhS5tgWNRbxPfHmhMLhy/srxAN4ucjVoXCxH1tUFK5anYZW8U2/bprElYtAMA2fAniJ1bCMbAjhKAmBNV//lwMC482qINnscK2/27xdNLFlUkZsrQmavdshuF2yJzHXWAgeGGLMn1tZ6RDShPlXVTu9EuAhvOOj/GrgiEDJ/BfTF2Yx1xXFLi6LfxThmVw5cSeIaMAhgYm2tR+k9M+nW+MxWuT4QMltaJGERQqC8CGbgWF3esWLamO2VIbPZIVD0nAO7+zyGaPzTkFbd9IpMjyLVJx13T0nVGskJG9sbCJlPQcJGaGY46H8jHYdAyNyMUx0WQ3+A/Xv6/FTQ5MWqJ21z1yYH7qmrCd9SubcNtB2HYdyFbU8kOpWo6DXxp1V1ThYOyVm9EwIh81vhoP/fWa4blnRc78UpKCqPazw1EDJfAFJVN3SBVu7gropq01vUlTuyCM+EMjG8vwUmd4BHm1E3deSbVTXmYlVSbbjeWDG9YnEWFrtw3LyYwZcCWwMh83HSu6FnAclP4H8S84Li62/OjX7aijXF5XqNqsRPSxHQX6tK2sS6iJ4DLY9+qsikqvmv3Lt8+shd6a5xExGVuwy0lQJUdI62HsAEhIP+PYGQGQaq4pq7k/vm7K9e4Hc4j9/knEwA9kZEHvEoLyY266JwsCJjZuqSB5aWNDUeMwbVvtGmIhV7JnBdO/qRM1YER60P1LwcRjUQ17x1xbSKZ9vIogYnilCWjTANPgUeNcJB/5M4sQkT+CTLRQdxyjHWANXAUK/aI4BT42hUDc/cbNJfnDKuXmxN9jSuqgqZeX01QDyMCAkxIRHuzHb3xxAO+sM4Tsss4C2cpFCmvUA98AGwFif2dko46N/R+bqaw4zO19UcZriVkvy/hFoyCLglemgDM91+q1anAtJALemPEyfqjTO3X5WPV5p1KiAF1JJvAWGcwa8HJopPs+0N2oXONSAJakkvnGBjX5xqh9H5GnzoVEAC1JJyYClO8uQ54Dzx5fcJ/s4pKIroG1D+gvOg4S/FpwWpL+q0AEAt+QXOc1+vAmcUavDhKLeA6Ntza4D/AoPFp3sK3YejdieslgzAmeuXyWF8V8X/AGryz36xXfJpAAAAAElFTkSuQmCC"; string base64Data = System.Text.RegularExpressions.Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value; byte[] binData = Convert.FromBase64String(base64Data); byte[] ba = PdfHandler.ImageToPdf(binData); //System.IO.File.WriteAllBytes(@"d:\temp\myba.pdf", ba); //return System.Convert.ToBase64String(ba); return File(ba, "application/pdf", "Chart.pdf"); } A: There's no difference, other than the request method and how you send data to the server. The way you process the response is the same regardless of whether you use GET or POST. A: Yes, the rest of a POST request can direct a browser to download a file. The file contents would be sent as the HTTP response, same as in the GET case. A: Looks like you'd like to generate the POST request from Javascript. I believe there is no way to get the browser to treat the result of an AJAX request as a download. Even if the Content-Type is set to something that browsers would normally offer as a download (e.g. to "application/octet-stream"), the browser will only deposit the data in the XMLHttpRequest object. Furthermore, as you probably already know, there is no way to make window.open() issue a POST request. I think the best way is to make an AJAX request which generates a file on the server. On the browser, when that request completes, use window.open() to download the generated file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How to do Pivoting in PostgreSQL I am new to PostgreSQL. Suppose I have a table as under colorname Hexa rgb rgbvalue Violet #8B00FF r 139 Violet #8B00FF g 0 Violet #8B00FF b 255 Indigo #4B0082 r 75 Indigo #4B0082 g 0 Indigo #4B0082 b 130 Blue #0000FF r 0 Blue #0000FF g 0 Blue #0000FF b 255 If I do a Pivot in SQL Server as SELECT colorname,hexa,[r], [g], [b] FROM (SELECT colorname,hexa,rgb,rgbvalue FROM tblPivot) AS TableToBePivoted PIVOT ( sum(rgbvalue) FOR rgb IN ([r], [g], [b]) ) AS PivotedTable; I get the output as colorname hexa r g b Blue #0000FF 0 0 255 Indigo #4B0082 75 0 130 Violet #8B00FF 139 0 255 How to do the same using PostgreSQL? My attempt is SELECT * FROM crosstab ( 'SELECT colorname ,hexa ,rgb ,rgbvalue FROM tblPivot' )AS ct(colorname text, hexa text, rgb text, rgbvalue int); But geting error: ERROR: function crosstab(unknown) does not exist LINE 2: FROM crosstab ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. ********** Error ********** ERROR: function crosstab(unknown) does not exist** Is there any elegant way of doing so in PostgreSQL (any built in function...) What is the standard practice of doing so ? A: This can be expressed as a JOIN: SELECT c.colorname, c.hexa, r.rgbvalue, g.rgbvalue, b.rgbvalue FROM (SELECT colorname, hexa FROM sometable GROUP BY colorname) c JOIN sometable r ON c.colorname = r.colorname AND r.rgb = 'r' JOIN sometable g ON c.colorname = g.colorname AND g.rgb = 'g' JOIN sometable b ON c.colorname = b.colorname AND b.rgb = 'b' ; A: Run this CREATE EXTENSION tablefunc; and try to execute your query
{ "language": "en", "url": "https://stackoverflow.com/questions/7563796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to implement the outline effect on text with WindowsAPICodePack? I'm still struggling on this issue after our other requirements are finished. I found we can use GeometrySink alike classes to implement the outline effect; but I'm not familiar with c++; see this article: http://msdn.microsoft.com/en-us/library/dd317121.aspx More complex shapes can be created by using the ID2D1GeometrySink interface to specify a series of figures composed of lines, curves, and arcs. The ID2D1GeometrySink is passed to the Open method of an ID2D1PathGeometry to generate a complex geometry. ID2D1SimplifiedGeometrySink can also be used with the DirectWrite API to extract path outlines of formatted text for artistic rendering. If you have any suggestions or ideas, please let me know. Best regards, Howard A: I use SharpDX. Here a snippit of code (this is work in progress and I JUST got it rendering, but it probably is what you are looking for somewhat). public class OutlineTextRender : SharpDX.DirectWrite.TextRenderer { readonly Factory _factory; readonly RenderTarget _surface; readonly Brush _brush; public OutlineTextRender(RenderTarget surface, Brush brush) { _factory = surface.Factory; _surface = surface; _brush = brush; } public Result DrawGlyphRun(object clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, SharpDX.DirectWrite.GlyphRun glyphRun, SharpDX.DirectWrite.GlyphRunDescription glyphRunDescription, ComObject clientDrawingEffect) { using (PathGeometry path = new PathGeometry(_factory)) { using (GeometrySink sink = path.Open()) { glyphRun.FontFace.GetGlyphRunOutline(glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.IsSideways, (glyphRun.BidiLevel % 2) > 0, sink); sink.Close(); } Matrix matrix = Matrix.Identity; matrix = matrix * Matrix.Translation(baselineOriginX, baselineOriginY, 0); TransformedGeometry transformedGeometry = new TransformedGeometry(_factory, path, matrix); _surface.DrawGeometry(transformedGeometry, _brush); } return new Result(); } public Result DrawInlineObject(object clientDrawingContext, float originX, float originY, SharpDX.DirectWrite.InlineObject inlineObject, bool isSideways, bool isRightToLeft, ComObject clientDrawingEffect) { return new Result(); } public Result DrawStrikethrough(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref SharpDX.DirectWrite.Strikethrough strikethrough, ComObject clientDrawingEffect) { return new Result(); } public Result DrawUnderline(object clientDrawingContext, float baselineOriginX, float baselineOriginY, ref SharpDX.DirectWrite.Underline underline, ComObject clientDrawingEffect) { return new Result(); } public SharpDX.DirectWrite.Matrix GetCurrentTransform(object clientDrawingContext) { return new SharpDX.DirectWrite.Matrix(); } public float GetPixelsPerDip(object clientDrawingContext) { return 0; } public bool IsPixelSnappingDisabled(object clientDrawingContext) { return true; ; } public IDisposable Shadow { get { return null; } set { // throw new NotImplementedException(); } } public void Dispose() { } } public void strokeText(string text, float x, float y, float maxWidth) { // http://msdn.microsoft.com/en-us/library/windows/desktop/dd756692(v=vs.85).aspx // FIXME make field SharpDX.DirectWrite.Factory factory = new SharpDX.DirectWrite.Factory(SharpDX.DirectWrite.FactoryType.Shared); TextFormat format = new TextFormat(factory, "Verdana", 50); SharpDX.DirectWrite.TextLayout layout = new SharpDX.DirectWrite.TextLayout(factory, text, format, 50, 1000); using (var brush = new SolidColorBrush(_surface, CurrentColor)) { var render = new OutlineTextRender(_surface, brush); layout.Draw(render, x, y); //_surface.DrawTextLayout(new DrawingPointF(x, y), layout, brush); // _surface.DrawGlyphRun(new DrawingPointF(x, y), run, brush, MeasuringMode.Natural); } } A: I turned this into a generic XAML outline text renderer. Thanks for posting. https://blogs.msdn.microsoft.com/theuxblog/2016/07/09/outline-text-from-a-windows-10-store-xaml-app-using-sharpdx/ Cheers, Paul
{ "language": "en", "url": "https://stackoverflow.com/questions/7563798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I execute a javascript function that is on a web page using VB.NET? What I am trying to do is go to a website using a webbrowser, and then simulate a click. I can do this easy enough when the click is on a regular button, not handling javascript. But it seems that the website has a javascript function handling the click that I want to simulate: <script language='JavaScript' type='text/javascript'><!-- function setgotopageNR() { if (document.gotopageform.gotopage_reverse.value=='1') { document.gotopageform.page.value=8+1-document.gotopageform.gotopage.value; } else { document.gotopageform.page.value=document.gotopageform.gotopage.value; } } //--></script> I have tried various solutions found through googling, such as WebBrowser1.Document.InvokeScript, also opening the website in internet explorer and then converting its document to IHTMLDocument2 and getting its parent window as IHTMLWindow2 and then using execScript. Any ideas? A: Normally one would do document.getElementById(id).click(). It should be easy to convert to whatever language you are using to host web browser. If click does not work please post more details on solutions you've already tried and what problems you got.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my jQuery AJAX function always return false? function check_username(){ $.ajax({ type: "POST", dataType: 'json', url: "/ajax/check/username.html", data: "via=ajax&username="+$('input[name=register_username]').val(), success: function(msg){ if(msg.response==false){ register_username.parent().css('background-color','#db2e24'); register_username.parent().parent().find('td:last-child').text(msg.message); register_username.focus(); return false; } else { register_username.parent().css('background-color','#fff'); register_username.parent().parent().find('td:last-child').text(""); return true; } } }); } I'm sorry if my English isn't good -- English is not my native language. Back to the topic, why does the function above always return false? FYI : the JSON is OK A: check_username calls an ajax function which starts a networking operation and then returns immediately. check_username returns long before the ajax call finishes and the success handler gets called. Thus, the success handler has NOTHING to do with the value that check_username returns. Since there is no return value in the check_username function itself (only in the embedded success handler function), check_username returns undefined which is a falsey value, thus you think it's always returning false. If you want to do something with the return value from the success handler, then you have to either operate in the success handler itself or you have to call another function from the success handler. This is how asynchronous operations work. Returning true or false from the success handler function does nothing. The success handler is called by the internals of the ajax handling code and returning from the success handler just goes into the bowels of the ajax internals. The return value from the success handler is not used in any way. A: The problem is the logical condition msg.response==false.. this always evaluates to false, the response is not a boolean. You need to check the response status instead. A: If I had to guess, you post, and the response returned is a JSON object. But it looks like your just checking to see if you got a valid response. Why not try it this way: Try this: function check_username() { $.ajax({ type: "POST", dataType: 'json', url: "/ajax/check/username.html", data: "via=ajax&username="+$('input[name=register_username]').val(), success: function( msg, textStatus ) { if ( textStatus == "success" ) { register_username.parent().css('background-color','#db2e24'); register_username.parent().parent().find('td:last-child').text(msg.message); register_username.focus(); return false; } else { register_username.parent().css('background-color','#fff'); register_username.parent().parent().find('td:last-child').text(""); return true; } }, error: function( jqXHR, textStatus, errorThrown ) { if ( textStatus == "parsererror" ) { alert( "There is an error in your JSON object" ); } } }); } The other problem you could have is that your not returning valid json, which jQuery will check. Adding an error will help reveal if this is indeed the case. Live demo http://jsfiddle.net/khalifah/4q3EJ/
{ "language": "en", "url": "https://stackoverflow.com/questions/7563804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: calling another mxml function in other mxml file in flex i have defined some functions in a component mxml file let us say addbutton() now i want to call this function in main mxml file. How can i do that. best regards A: var anyname:addGroup = new addGroup(); anyname.addGroupe(); This will work. A: Simple. yourComponentId.addButton()
{ "language": "en", "url": "https://stackoverflow.com/questions/7563807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the gr count 0 in my program output? I'm new to R and DM/ML, and I wrote a small program to try out the optim function. I used optim with SANN method. I defined my own gr function and made some config with the control parameter. The problem is that when I print the output, the count of gr, which stands for the number of calls to the gr function, is 0, while the number of calls to fn is correct. Here's my runnable code(I think the cost function is irrevelant so I posted a simple one): people = list('Seymour'='BOS', 'Franny'='DAL', 'Zooey'='CAK', 'Walt'='MIA', 'Buddy'='ORD', 'Les'='OMA') schedulecost <- function(schedule){ return(sum(schedule)) } annealingOptimize <- function(domains, step=1, T=10000,costf=schedulecost){ solution <- sample(1:9, 2 * length(people), replace=T) grFunction <- function(sol){ index <- sample(c(1:length(domains$Up)), 1, replace=T) delta <- as.integer(runif(1,min=-step-1,max=step+1)) newValue <- sol[index] + delta if (newValue > domains$Up[index]){ newValue <- domains$Up[index] } if (newValue < domains$Down[index]){ newValue <- domains$Down[index] } sol[index] <- newValue return(sol) } values <- optim(solution,costf,gr=grFunction, method='SANN', control=list(temp=T, REPORT=1, maxit=200, tmax=10)) print(values) return(values$par) } domains <- list(Down=rep(1,length(people) * 2), Up=rep(9, length(people) * 2)) schedule <-annealingOptimize(domains) And the output is: $par [1] 2 2 6 2 3 5 5 1 9 1 1 7 $value [1] 44 $counts function gradient 200 NA $convergence [1] 0 $message NULL In my understanding, the count of gr should equal to the count of fn, since you need to call the fn iff you have a new candidate from a call to gr. Is my understanding incorrect(if yes, what's their relationship) or there's something wrong with my code. Any one can help ? Thanks so much ! Update: As @Dwin pointed out, in the help documentation it says: "Method "SANN" ... uses only function values but is relatively slow. " But in the description of the parameter gr it says: "For the "SANN" method it specifies a function to generate a new candidate point. " If you add some print statement in my grFunction, you can see that it actually got called very intensively. Besides, if the SANN method just use fn and doesn't use gr, then what the sentence for gr really mean ? A: Investigating the code in src/main/optim.c shows that the SANN method really does call the gradient function (which you have of course confirmed via your print statements), but that it doesn't bother to update the gradient count. Here's the call to the internal SANN function samin: samin (npar, dpar, &val, fminfn, maxit, tmax, temp, trace, (void *)OS); for (i = 0; i < npar; i++) REAL(par)[i] = dpar[i] * (OS->parscale[i]); fncount = npar > 0 ? maxit : 1; grcount = NA_INTEGER; and I can confirm that samin calls genptry, which calls the gradient function. This strikes me as a bug (which could be reported to the R development list, or on the R bugs tracker), but a harmless one. As you point out, presumably the gradient (= candidate point generator) function always gets called exactly the same number of times (OK, give or take one or two during the set-up stage) as the objective function ... (but I understand the confusion when the function doesn't do what it says in the documentation!)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Install Type 1 Font in VS 2010 Setup Project I'm trying use a Visual Studio 2010 setup project to package a set of Type 1 fonts into a MSI file for easy installation. I've configured my setup project to place all the PFM and PFB files in the Fonts folder, set all the PFM files to vsdrfFont and fixed the naming issue mentioned here: http://cjwdev.wordpress.com/2011/03/14/installing-non-truetype-fonts-with-visual-studio-installer/ However, this isn't working for Type 1 fonts. The Type 1 font files are installed but the font is still not recognized and doesn't appear in the Fonts window. If installed manually, Type 1 fonts are registered under HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Type 1 Installer\Type 1 Fonts and work fine. How can the same result be achieved with a setup project? A: To install Type 1 fonts you need to do the following: * *Register the font title under 'Type 1 Fonts' *Copy both the PFM and the PFB to the windows fonts directory *Call the AddFontResource method Register the font title under 'Type 1 Fonts' SOFTWARE\Microsoft\Windows NT\CurrentVersion\Type 1 Installer\Type 1 Fonts The Font Title is required, rather than providing this to the installer, the following code snippet will allow you to read the font title from the PFM. It is based on information gathered from the following source: http://partners.adobe.com/public/developer/en/font/5178.PFM.pdf private static string GetType1FontName(string filename) { StringBuilder postscriptName = new StringBuilder(); FileInfo fontFile = new FileInfo(filename); using (FileStream fs = fontFile.OpenRead()) { using (StreamReader sr = new StreamReader(fs)) { using (BinaryReader inStream = new BinaryReader(fs)) { // PFM Header is 117 bytes inStream.ReadBytes(117); // skip 117 short size = inStream.ReadInt16(); int extMetricsOffset = inStream.ReadInt32(); int extentTableOffset = inStream.ReadInt32(); inStream.ReadBytes(4); // skip 4 int kernPairOffset = inStream.ReadInt32(); int kernTrackOffset = inStream.ReadInt32(); int driverInfoOffset = inStream.ReadInt32(); fs.Position = driverInfoOffset; while (inStream.PeekChar() != 0) { postscriptName.Append(inStream.ReadChar()); } } } } return postscriptName.ToString(); } Copy both the PFM and the PFB to the windows fonts directory According to this blog http://www.atalasoft.com/cs/blogs/stevehawley/archive/2008/08/25/getting-the-fonts-folder.aspx the right way to get the windows fonts folder is as follows: [DllImport("shell32.dll")] private static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, [Out] StringBuilder pszPath); public static string GetFontFolderPath() { StringBuilder sb = new StringBuilder(); SHGetFolderPath(IntPtr.Zero, 0x0014, IntPtr.Zero, 0x0000, sb); return sb.ToString(); } Call the AddFontResource method Finally, the method AddFontResource should be called, the parameter lpFilename should be made up of the pfm and pfb files separated by the pipe character '|'. In my case I put the full path to the windows fonts folder which seemed to work. After calling AddFontResource you need to call PostMessage with a parameter of WM.FONTCHANGE (0x001D) to inform other windows of the change. [DllImport("gdi32.dll")] static extern int AddFontResource(string lpFilename); // build the name for the api "<pfm>|<pfb>" string apiValue = string.Format("{0}|{1}", PfmFileDestination, PfbFileDestination); // Call the api to register the font int retVal = AddFontResource(apiValue); // Inform other windows of change PostMessage(HWND_BROADCAST, WM.FONTCHANGE, IntPtr.Zero, IntPtr.Zero); A: Here is a solution that involves an MSI custom action. I have written in using C#, but any other language capable of calling a DLL can be user. Here is a tutorial link for C#: Walkthrough: Creating a Custom Action using System; using System.Collections; using System.ComponentModel; using System.Configuration.Install; using System.IO; using System.Runtime.InteropServices; namespace InstallType1Font { [RunInstaller(true)] public partial class Installer1 : Installer { public Installer1() { InitializeComponent(); } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Install(IDictionary stateSaver) { base.Install(stateSaver); } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Commit(IDictionary savedState) { base.Commit(savedState); // here, you'll have to determine the proper path string path = @"c:\Windows\Fonts\MyFont.pfm"; if (File.Exists(path)) { InstallFontFile(IntPtr.Zero, path, 0); } } [DllImport("fontext.dll", CharSet = CharSet.Auto)] private static extern void InstallFontFile(IntPtr hwnd, string filePath, int flags); [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Rollback(IDictionary savedState) { base.Rollback(savedState); } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); } } } As far as I know, InstallFontFile is undocumented, but allows to install the font permanently. Use this at your own risk. Note: you still need to modify the .MSI to ensure the Fonts file have a FontTitle as described in the link you gave.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does this make an infinite loop #include <iostream> #include <math.h> using namespace std; int main() { double radius = 0.00; double height = 0.00; double width = 0.00; double side = 0.00; double Area = 0.00; const double PI = atan(1.0)*4; string input = "none"; while (input != "0") { cout << "Shape Menu: \n (r) rectangle \n (s) square \n (c) circle \n (0) exit" << endl; cin >> input; if (input == "r"){ cout << "Please enter a floating point value for the height of the rectangle." << endl; cin >> height; cout << height; while (height <= 0) { cin.clear(); cin.ignore(1000, '\n'); cout << "Your input was invalid. Please input a floating point value greater than 0."; cin >> height; } cout << "Please enter a floating point value greater than 0 for the width of the rectangle." << endl; cin >> width; while (width <= 0) { cin.clear(); cin.ignore(1000, '\n'); cout << "Your input was invalid"; cin >> width; } Area = height*width; cout << "The area of a rectangle with those dimensions is " << Area << "units squared." << endl; } else if(input == "s"){ cout << "Please enter a floating point value for the length of the side." << endl; cin >> side; if (cin.fail()) cout << "Please enter a floating point value."; Area = side*side; cout << "The area of a square with those dimensions is " << Area << "units squared" << endl; } else if(input == "c"){ cout << "Please enter a floating point value for the length of the radius." << endl; cin >> radius; if (cin.fail()) cout << "Please enter a floating point value."; Area = radius*radius*PI; cout << "The area of a circle with those dimensions is " << Area << "units squared." << endl; } else if(input == "0"){ break; } else{ cout << "Your input does not match one of the options suggested. Please type r, s, c to get the area of a shape, or type 0 to exit." << endl; } } return 0; } I am trying to write a program that asks the user to pick from a menu of shapes, then ask for certain inputs for each type to determine the area. The problem I am having now, is trying to figure out how to raise errors when people input answers for the radius or height and width that are not numeric. The error I was trying to write for the rectangle worked for the initial incorrect input, however once the user is prompted pick another shape, if an input error occurs again, then it begins an infinite loop. A: You are using cin.clear() and cin.ignore(1000,'\n') to skip over the invalid input in the rectangle case, which is good, but you aren't doing that in the other cases. A: For me, your code would go into a loop if I typed s (for square) and s again. This code doesn't; it checks inputs as it goes: #include <iostream> #include <math.h> using namespace std; int main() { double radius = 0.00; double height = 0.00; double width = 0.00; double side = 0.00; double Area = 0.00; const double PI = atan(1.0)*4; string input = "none"; while (input != "0") { cout << "Shape Menu: \n (r) rectangle \n (s) square \n (c) circle \n (0) exit" << endl; if (!(cin >> input)) { cout << "Break after reading input\n"; break; } cout << "Input: <<" << input << ">>" << endl; if (input == "r") { cout << "Please enter a floating point value for the height of the rectangle." << endl; if (!(cin >> height)) { cout << "Break after reading height (1)\n"; break; } cout << height; while (height <= 0) { cin.clear(); cin.ignore(1000, '\n'); cout << "Your input was invalid. Please input a floating point value greater than 0."; if (!(cin >> height)) { cout << "Break after reading height (2)\n"; break; } } cout << "Please enter a floating point value greater than 0 for the width of the rectangle." << endl; if (!(cin >> width)) break; while (width <= 0) { cin.clear(); cin.ignore(1000, '\n'); cout << "Your input was invalid"; if (!(cin >> width)) break; } Area = height*width; cout << "The area of a rectangle with those dimensions is " << Area << " units squared." << endl; } else if (input == "s") { cout << "Please enter a floating point value for the length of the side." << endl; if (!(cin >> side)) { cout << "Break after reading length\n"; break; } if (cin.fail()) cout << "Please enter a floating point value."; Area = side*side; cout << "The area of a square with those dimensions is " << Area << " units squared" << endl; } else if (input == "c") { cout << "Please enter a floating point value for the length of the radius." << endl; if (!(cin >> radius)) { cout << "Break after reading radius\n"; break; } if (cin.fail()) cout << "Please enter a floating point value."; Area = radius*radius*PI; cout << "The area of a circle with those dimensions is " << Area << " units squared." << endl; } else if (input == "0") { cout << "Break after reading zero\n"; break; } else { cout << "Your input does not match one of the options suggested.\n" << "Please type r, s, c to get the area of a shape, or type 0 to exit." << endl; } } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Global variable in ASP.NET I wish to stop a thread from entering code while another thread is still executing that bit of code: I'm currently going the following: global.asax.cs private static bool _isProcessingNewIllustrationRequest; public static bool IsProcessingNewIllustrationRequest { get { return _isProcessingNewIllustrationRequest; } set { _isProcessingNewIllustrationRequest = value; } } Then in MVC: public ActionResult CreateNewApplication() { if (!Global.IsProcessingNewIllustrationRequest) { Global.IsProcessingNewIllustrationRequest = true; // DO WORK... RUN CODE Global.IsProcessingNewIllustrationRequest = false; return View("Index", model); } else { // DISPLAY A MESSAGE THAT ANOTHER REQUEST IS IN PROCESS } } But if seems as if the code isn't working, because both threads(Chrome & Firefox) still executes the code at the same time. UPDATED private Object thisLock = new Object(); public ActionResult CreateApplication() { ILog log = LogManager.GetLogger(typeof(Global)); string aa = this.ControllerContext.HttpContext.Session.SessionID; log.Info("MY THREAD: " + aa); lock (thisLock) { Thread.Sleep(8000); DO SOME STUFF } } Even with the log, thread 2 (Firefox session) still goes into the code while session1 (Chrome) is executing it with the lock. What am I missing? A: I can see two obvious reasons why this code won't do what you want. Problem #1: It's not threadsafe. Every time someone connects to your server, that request is going to run in a thread, and if multiple requests come in, then multiple threads are all going to be running at the same time. Several threads could very well read the flag at the same time, all see that it's false, and so all enter their if block and all do their work, which is exactly what you're trying to prevent. This is a "race condition" (the results depend on who wins the race). Boolean variables aren't enough to solve a race condition. There are a bunch of ways to actually fix this problem. The best would be to remove the shared state, so each thread can run completely independently of the others and there's no need to lock the others out; but I'll assume you've already considered that and it's not practical. The next things to look at are mutexes and monitors. Monitors are a little simpler to use, but they only work if both threads are actually in the same appdomain and the same process. That brings me to... Problem #2: The two threads might not be in the same process. Recent versions of IIS will launch multiple separate worker processes to handle Web requests. Each process has its own address space, meaning each process (technically each appdomain within each process) has its own copy of your "global" variable! In fact, if you're building a really high-traffic Web site, the different worker processes may not even run on the same computer. Worker processes are your most likely culprit. If you were facing a race condition, the problem would be incredibly rare (and even more incredibly hard to debug when it did come up). If you're seeing it every time, my money is on multiple worker processes. Let's assume that all the worker processes will be on the same server (after all, if you had the kind of budget that required apps that can scale out to multiple Web servers, you would already know way more about multithreaded programming than I do). If everything's on the same server, you can use a named Mutex to coordinate across different appdomains and processes. Something like this: public static Mutex _myMutex = new Mutex(false, @"Global\SomeUniqueName"); public ActionResult CreateNewApplication() { if (_myMutex.WaitOne(TimeSpan.Zero)) { // DO WORK... RUN CODE _myMutex.ReleaseMutex(); return View("Index", model); } else { // DISPLAY A MESSAGE THAT ANOTHER REQUEST IS IN PROCESS } } The WaitOne(TimeSpan.Zero) will return immediately if another thread owns the mutex. You could choose to pass a nonzero timespan if you expect that the other thread will usually finish quickly; then it will wait that long before giving up, which would give the user a better experience than failing instantly into a "please try again later" error message. A: ASP.NET spools up worker processes as needed, don't fight it. Use a database queue and let ASP.NET work optimally. You will be choking the sever trying to control the threading, if you even can, on top of creating highly un-maintainable code. If you do find a way to control it, I can't imagine the type of bugs you are going to run into. A: In your Edit case above, you are creating that new object with every controller instance so its only going to lock code that would be on that same thread - and theres only one request so that does nothing. Try to log your global class variables upon application startup so the static initializers run and you know things are 'setup'. Then use an object that exists in this global class (it could be anything - a string) and use that as your lock variable. A: The only way to accomplish this is by using a mutex. The "lock" statement is syntactic sugar for a mutex. You should abstract your code into a static class that has a static member variable so all threads in your app-domain will have access to this class. Now, you can encapsulate all the code in your two static member functions in a lock statement. Please ensure that you are locking the same lock variable in the two member functions. Also, if you do not want these member functions to be static then your class doesn't have to be static. You will be fine as long as your lock variable is static. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone: Xcode 4.1 doesn't show up Distribution build configuration I developed an iPhone application and want to use Distribution scheme to build and upload to App store. I recently updated Xcode 4.1. When i search for Distribution setting build configuration, it doesn't show up. It shows only Release and Debug. Could someone help me to get this? Thank you! A: Check it out Build configuration for Distribution
{ "language": "en", "url": "https://stackoverflow.com/questions/7563828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drop Down menu using jquery I am using Phonegap and i am new to both phonegap as well as jquery. I needed to know if i can have a drop down button using jquery. Appreciate your help. $(document).ready(function(){       $('.down-list').width($('.dropdown-menu').width()-2);       $('.dropdown-menu').hover(       function () {         $('.menu-first', this).addClass('slide-down');         $('.down-list', this).slideDown(100);       },       function () {         obj = this;         $('.down-list', this).slideUp(100, function(){ $('.menu-first', obj).removeClass('slide-down'); });       }     );   }); this code doesn seem to work. It just gives me the text on android emulator. Any suggestions? Thanks a lot in advance. A: Have you solved the problem? If not, you should look into using jquery mobile and why did you want to use jquery to create a drop-down? I am guessing you want to "beautify" the drop-down? Another option is to look at html5 and css3 based drop-downs as those will be hardware accelerated; depending on jquery too much will only make your app run slower because it is being run inside a browser (phonegap) Update: From personal experience I have realized that you should look into micro frameworks like Zepto or XUI or jqMobi. I have personally used Zepto and have noticed significant improvements in performance compared with jQM and jQ. All of the frameworks I just mentioned use jQ style syntax so porting to them will not be a problem. I have blogged about PhoneGap(now Cordova) at http://codejournal.wordpress.com/2012/02/19/what-i-can-use-htmljavascriptcss-for-native-mobile-apps/. I have blogged about other useful stuff for mobile that you can use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: swipe to delete causing weird error in my UITable I have implemented this swipe to delete but as a clear button that resets the uitableviewcells textlabel to empty... when this method is executed it works perfectly.. however when the user touches the same cell after the swipe to clear nothing happens... then if you touch it again it works perfectly... here is my code.. // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //reset uitableviewcell textlabel with default input "empty" vehicleSearchObjectString = @"empty"; [self.tableView reloadData]; //reloads the tabels so you can see the value. } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } A: You need to delete your object from the data source. I see you have that line commented out where you delete the row at the given index path, but you also actually need to delete your object from whatever list or structure is holding your objects that are displayed in the table to begin with. I don't know if that's what's causing your problem, but I've had a bunch of problems with this in the past because I forgot to delete my object properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring persistence layer for dynamic queries I have legacy app having its own persistent layer. I cannot call it a framework but it does its job although very complicated and not componentised so gets very difficult to extend or add features. I am looking to use some latest technology to be introduced in the system where the new code is written in the new framework and slowly deprecate the legacy layer. I am inclined to use Spring framework JDBC layer and AOP based transaction management. My requirement is complicated as most of the queries are dynamic. The columns to be selected/updated are dynamic as depends on permission of the attribute to the user. Also since most of the entities have similar logic most of the time only table or view name needs to be changed in a query. What do you suggest in terms of what part of Spring I should use to write the SQL queries? A: Have you taken a look at Spring's SimpleJDBCTemplate? It would seem to fit the bill for your project. http://www.vaannila.com/spring/spring-simple-jdbc-template.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7563851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Complexity Difference Between Where Clause Inside Query and Where Clause Inside Conditional Split In SSIS I've been wondering, what's the complexity difference between these two cases: Case 1: An OLE DB Source query, written like this: select * from A where A.value > 1 Case 2: An OLE DB Source query, and the where clause is put in Conditional Split select * from A with the Conditional Split after the OLE DB Source query, containing: value > 1. Performance-wise, does it have any difference? And for more complex query, does it have any significant impact also? A: Yes there is a performance difference. Case 2 will return all data records from table A and store them in the SSIS memory buffer before passing them on to the Conditional Split Component for filtering. Case 1 immediately returns a smaller data set to the SSIS memory buffer. For further reading take a look at: * *Understanding SSIS Data Flow Buffers video *Improving Performance of the Data Flow *Monitoring Performance of the Data Flow Engine A: Main purpose of SSIS is Import/Export with/from heterogeneous source (such as text files, Excel spreadsheets etc). You can make some kind of validation before you loading data to server and it is possible to log "wrong" records somewhere. But if you plan to use SSIS with SQL query only and without any validation or error logging in text files, you should look for another solution (Linked server,OPENROWSET and some more). But if you are still look at SSIS, you should include all possible logic inside SQL query or data source. There is article about how to prepare fast extraction using SSIS: http://www.sqllion.com/2009/04/faster-extraction-loading-by-ssis/ Try to avoid type casting or manipulating data types inside the SSIS package as it is an additional overhead for SSIS. Do it prior to the package or do typecasting in the source query of OLE DB Source component.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Emacs error with MobileOrg push I am trying to set Emacs org-mode to do the initial push of my files into the Dropbox folder, by running org-mobile-push, nonetheless I keep getting an error which reads Invalid function: org-eval-in-environment I have searched the web for an answer, but have not been able to locate one. In terms of this I have done the following: * *Reinstalled org-mode through Git, using the following commands: mkdir $HOME/elisp && cd $HOME/elisp git clone git://orgmode.org/org-mode.git cd org-mode && make && make doc && make install *This installed correctly. The org-mobile-push used to work fine with the version of org-mode that came with my install of Emacs 23.3 from http://emacsformacosx.com/, which I believe was on the version 6 branch of org-mode. I later stopped using/testing the sync with MobileOrg, and moved along to update to version 7.7. through ELPA. Following that, I started playing with creating a Git repo for my files. Something along the line has apparently damaged an important configuration. I am new to org-mode, Emacs and Git as well. Any guiding will be appreciated. Lastly, if this seems all messed up, please provide some info on how to reset Emacs and org-mode to its "default version (as it came with 23.3) Thanks, A: Not exactly a solution, but if you've got a valid index.org file, you don't need org-mobile-push. mobileorg is perfectly happy to pull everything linked from a manually generated file. If you'd prefer not to download every single org file there, every time, try: cd /your/org/dir/ md5sum *.org >checksums.dat It'll only pull the files that have changed checksums. I have it in a cron job. A: First make sure you don't have other versions of org visible to emacs (one version comes with emacs distribution, I always delete it). The version/architecture of emacs used to compile the sources matters as well. I had this exact error with org-mobile-push when I copied compiled org tree from Linux to Windows, so try recompiling org. One simple way to do that from within emacs is to open the org/lisp directory in dired, mark all the source files via "*. el" (sans the quotes), then byte-compile the files by pressing "B". Now reload org via its menu or via "C-c C-x !".
{ "language": "en", "url": "https://stackoverflow.com/questions/7563863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Simple assembly algorithm to find the largest number - Why is it returning the wrong number? I am working on a simple routine that will loop through a list of numbers and return the max. It is always returning 11 and I cannot see what's wrong with my logic. To test the routine I have a list of numbers (data_items) that I am looping through. What am I doing wrong here? .section .data data_items: #these are the data items .long 3,67,34,222,45,75,857,858,983,11,55,43,23,123,785,4356,0 .section .text .globl _start _start: movl $0, %edi #move 0 into the index register movl data_items(,%edi,4), %eax #load the first byte of data movl %eax, %ebx #since this is the first item, %eax is the biggest start_loop: cmpl $0, %eax #check to see if we've hit the end je loop_exit incl %edi #load the next value movl data_items(,%edi,4), %eax cmpl %ebx, %eax #compare values jle start_loop #jump to the start of the loop if the value is not larger movl %eax, %ebx #move the value as the largest jmp start_loop #jump to the loop beginning loop_exit: movl $1, %eax #1 is the exit() syscall int $0x80 A: Unix based operating systems only support 8-bit return value (so 0-255). So your program does find the maximum value, and store it in %ebx, but you cannot return it as the program's exit code. I ran your program without the numbers that are bigger than 255 and it worked correctly. A: There's nothing wrong with your logic at all. When I enter that code into qq.s and execute the following: pax$ as -o qq.o qq.s pax$ ld -o qq qq.o pax$ gdb qq GNU gdb (Ubuntu/Linaro 7.2-1ubuntu11) 7.2 Copyright (C) 2010 Free Software Foundation, Inc. ... blah blah blah ... Reading symbols from /home/pax/qq...(no debugging symbols found)...done. (gdb) break loop_exit Breakpoint 1 at 0x8048097 (gdb) run Starting program: /home/pax/qq Breakpoint 1, 0x08048097 in loop_exit () (gdb) info reg ebx ebx 0x1104 4356 (gdb) _ In other words, the correct value is being loaded into ebx. A: two points (1) when debugging and getting an unreasonable answer, remove that value from your test data, so in this case remove the 11 from your data and see what happens (2) I just checked the value 4356(10) and displayed it in hex and got 1104(16), so I am thinking your return code is only getting the left byte of a 16 bit value (4356).
{ "language": "en", "url": "https://stackoverflow.com/questions/7563874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to put all elements of a String array into Queue(Of String)? I want to put all elements of a String array into a Queue(Of String). I have following code which using For...Each to put string into Queue(Of String): Dim Files() As String = OpenFileDialog1.FileNames 'OpenFileDialog1 is an instance of OpenFileDialog control Dim PendingFiles As New Queue(Of String) For Each x1 As String In Files PendingFiles.Enqueue(x1) Next My question: Is that possible to do it (i.e. put string array into Queue(Of String)) without using For...Each? A: Use the constructor of Queue<T> that takes an IEnumerable<T>. Dim PendingFiles As New Queue(Of String)(Files)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript program help Update this program is supposed to keep track of the number of times each side is rolled not each roll itself. I am working on a javascript exercise that needs to take two dice, roll them 1000 times and keep track of each roll. I thought the best way to do it was to use an array but I am not exactly sure if I am going in the right direction with what I am doing. I just need a little help in pointing me in the right direction to get this to work because right now it doesnt output anything. Thanks here is my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Exercise Five</title> <script type="text/javascript"> function Die(){ this.roll = function(){ this.sides = 0; return parseInt((Math.random( ) * 1000) % this.sides) + 1; } } </script> </head> <body> <script type="text/javascript"> var dieOne = new Die(); var dieTwo = new Die(); var rollOne = 0; var rollTwo = 0; var roll_value = new Array(); var arrayPlace = 0; for(var i = 0; i < 1000 ; i++){ rollOne = dieOne.roll(); dieOne.sides = 10; rollTwo = dieTwo.roll(); dieTwo.sides = 10; arrayPlace = (rollOne + rollTwo) - 2; roll_value[arrayPlace]++; } for( var i = 0; i < roll_value.length; i++){ document.writeln(roll_value[i]); } </script> </body> </html> A: Sorry, see updated code below: var dieOne = new Die(); var dieTwo = new Die(); var rollOne = 0; var rollTwo = 0; var roll_values = new Array(); for(var i = 0; i < 1000 ; i++){ rollOne = dieOne.roll(); rollTwo = dieTwo.roll(); roll_values[i] = { 'first': rollOne, 'second': rollTwo, 'value': 0 }; // 1. iterate through past roll_values[i].first, roll_values[i].second // in order to determine what you need to increment and by how much // 2. finally set roll_values[i].value = var_containing_value; } for( var i = 0; i < roll_value.length; i++){ console.log(roll_value[i]); } And, another note, for debugging, console.log(whatever) is excellent and supported on most modern browsers (IE > 8, thanks Kolink). The console log will show up in the javascript/error console. There were two problems: how you were storing the roll values and how you were incrementing your array. Both should now be fixed. A: Try this: function Dice(sides) { this.sides = sides; } Dice.prototype.roll = function() { return (Math.random() * (this.sides + 1)) | 0 ; } var counts = []; var d1 = new Dice(6); var d2 = new Dice(6); var s; for (var i=1000; i; i--) { s = d1.roll() + d2.roll(); counts[s] = typeof counts[s] == 'undefined'? 1 : ++counts[s]; } // Show results for (var i=0, iLen=counts.length; i<iLen; i++) { console.log(i + ' : ' + counts[i]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data contract serialization for IList I have the following code in which I'm trying to serialize a list to a file public static void Serialize<T>(this IList<T> list, string fileName) { try { var ds = new DataContractSerializer(typeof(T)); using (Stream s = File.Create(fileName)) ds.WriteObject(s, list); } catch (Exception e) { _logger.Error(e); throw; } } and I'm getting the exception: Type 'System.Collections.Generic.List`1[[MyClass, MyNameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOf*MyClass*:http://schemas.datacontract.org/2004/07/MyNameSpace' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer. [KnownType(typeof(MyClass))] [DataContract] public class MyClass { #region Properties [DataMember] public string Foo{ set; get; } [DataMember] public string Bar{ set; get; } } Any ideas? There is no inheritance. A: What has happened is that the serializer is expecting an instance of T, not a list of T, so you want your method to be like so: public static void Serialize<T>(this IList<T> list, string fileName) { try { var ds = new DataContractSerializer(list.GetType()); using (Stream s = File.Create(fileName)) ds.WriteObject(s, list); } catch (Exception e) { _logger.Error(e); throw; } } A: As suggested, the serializer should be for the list, not the type of items. Additionally, [KnownType(typeof(MyClass))] should take a class inheriting from MyClass in parameter, not MyClass itself. A: try this instead: var ds = new DataContractSerializer(typeof(T[]));
{ "language": "en", "url": "https://stackoverflow.com/questions/7563878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to calculate active total using javascript for html form I have an html form that I want to have generate a running total at the bottom of the form. I also want to do some other simple calculations but I am unable to find anything about doing simple calculations using javascript.i dont want someone to do this for me I just want someone to point me in the right direction aka what how to create a function to multiple a quantity times a price and add more then one to create a total. Rough example: <input type="text" name="qty1" onchange=""> <input type="text" name="price1" onchange="something"> <input type="text" name="qty2" onchange=""> <input type="text" name="price2" onchange="something"> and the total would be like this =(qty1*price1)+(qty2*price2) and so on and i want place this number in my sql db when submited I hope this isn't to difficult to explain. I also want to skip fields with no entry. A: Here's how do it if you want to use jQuery: HTML: <div> <input type="input" class="qty" /> <input type="input" class="price" /> </div> <div> <input type="input" class="qty" /> <input type="input" class="price" /> </div> <div> <input type="input" class="qty" /> <input type="input" class="price" /> </div> Total: <span id="total"></span> JavaScript: jQuery(function($) { $(".qty, .price").change(function() { var total = 0; $(".qty").each(function() { var self = $(this), price = self.next(".price"), subtotal = parseInt(self.val(), 10) * parseFloat(price.val(), 10); total += (subtotal || 0); }); $("#total").text(total); }); }); Basically, any time a price or quantity is changed, you enumerate each quantity input. You get the price value by finding the next sibling with the price class (assumes your price field is after the quantity field and is at the same level in the document). Then parse their values -- parseInt() for the quantity, and parseFloat for the price. The 10 argument is to force the radix to base 10 since js is known to 'guess' and will accept hex values, for example. If the calculation couldn't be done because the value wasn't a number, subtotal will be NaN. I "or" that with 0 so I don't try to add NaN to the total. Finally, I put the result into the total field. You said you want to save the total somewhere. You need to do that on the server with PHP, don't post the value from the client. Any value posted by the client, whether it's a hidden field or not, can be spoofed by the client. You can't trust it. So calculate it on the server from the posted fields. jsfiddle: http://jsfiddle.net/nCub9/ A: This is what i used to calculate on the fly. The answer is correct as well but for me it was too complicated for my simple mind. Thank you InfinitiesLoop and everyone else for your input <html> <head> <script> function calculate(){ if(isNaN(document.formname.qty.value) || document.formname.qty.value==""){ var text1 = 0; }else{ var text1 = parseInt(document.formname.qty.value); } if(isNaN(document.formname.Cost.value) || document.formname.Cost.value==""){ var text2 = 0; }else{ var text2 = parseFloat(document.formname.Cost.value); } document.formname.textbox5.value = (text1*text2); } </script> </head> <body> <form name="formname"> <input type="text" name="qty" onblur="calculate()"<br/> <input type="text" name="Cost" onblur="calculate()"<br/> <input type="text" name="textbox5"> </form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: different colors for each row Is it possible to give a different color to each row that has distinct data, using xslt ? For example, in case there is a table of the form country code india 1 spain 2 germany 3 india 1 sri lanka 4 spain 2 There are 2 rows in which india and spain occur. so, can I color those 2 rows with a particular color and the remaining with different colors? Suppose sri lanka occurs twice, I wish sri lanka rows to have a different color. dis can b done using xslt? The xml file gets updated dynamically. The xsl reads from the xml file and displays the data in the form of a table. 2 tables will be outputed. I want that, in the 2nd table, each row with distinct 'Conference name' should have a different color. my xsl file <?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head> <title>VPGate Media Mixer</title> <meta http-equiv="expires" content="0"/> <meta http-equiv="pragma" content="no-cache"/> <meta http-equiv="cache-control" content="no-cache, must-revalidate"/> <meta http-equiv="refresh" content="15"></meta> <script src="/Common/common.js\" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style001.css" /> <link rel="stylesheet" type="text/css" href="Grid.Default.css" /> </head> <body class="WorkArea"> <div class="divSummaryHeader" id="SummaryHeader"> <h1>Media Mixer - VPGate</h1> <xsl:for-each select="MMDiagnostics/Conference"> <h1> Media Mixer - <xsl:value-of select="name"/> </h1> </xsl:for-each> </div> &#160; <div class="RadGrid RadGrid_Default" id="SummaryData" style="position:absolute;width:810px;height:510px;overflow:auto"> <table border="0" class="rgMasterTable rgClipCells" cellspacing="0" cellpadding="0" > <tr> <input type="button" class="formEditBtn" id="SubBtn" value="Refresh" onclick="window.location=window.location;"/> </tr> <tr> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;" colspan="2">Conference Summary</td> </tr> <tr> <td> <table border="0" class="rgMasterTable rgClipCells" cellspacing="0" cellpadding="0" > <tr> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference Name</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference ID</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Composite Address</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Composite Port</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Composite Ssrc</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">No Of Participants</td> </tr> <xsl:if test="MediaMixer!= ''"> <xsl:for-each select="MediaMixer/Conference"> <!--<xsl:sort select="Name"/>--> <xsl:if test="Name !=''"> <xsl:if test="(position() mod 2 = 0)"> <tr class="rgAltRow SummaryTableDataRow"> <td valign = "top"> <xsl:value-of select="Name"/> </td> <td valign = "top"> <xsl:value-of select="ConfId"/> </td> <td valign = "top"> <xsl:value-of select="CompositeAddress"/> </td> <td valign = "top"> <xsl:value-of select="CompositePort"/> </td> <td valign = "top"> <xsl:value-of select="CompositeSsrc"/> </td> <td valign = "top"> <xsl:value-of select="NoOfParticipants"/> </td> </tr> </xsl:if> <xsl:if test="(position() mod 2 = 1)"> <td> <tr class="rgRow SummaryTableDataRow"> <td valign = "top"> <xsl:value-of select="Name"/> </td> <td valign = "top"> <xsl:value-of select="ConfId"/> </td> <td valign = "top"> <xsl:value-of select="CompositeAddress"/> </td> <td valign = "top"> <xsl:value-of select="CompositePort"/> </td> <td valign = "top"> <xsl:value-of select="CompositeSsrc"/> </td> <td valign = "top"> <xsl:value-of select="NoOfParticipants"/> </td> </tr> </td> </xsl:if> </xsl:if> </xsl:for-each> </xsl:if> <xsl:if test="MediaMixer = ''"> <td valign = "top"> <xsl:text>No Data </xsl:text> </td> </xsl:if> </table> </td> </tr> </table> &#160; <table border="0" class="rgMasterTable rgClipCells" cellspacing="1" cellpadding="1" > <tr> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;" colspan="2">Conference Details</td> </tr> <tr> <td> <table border="0" class="rgMasterTable rgClipCells" cellspacing="0" cellpadding="0" > <tr> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference Name</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Conference ID</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant ID 1</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant ID 2</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant Address</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">Participant Listening Port</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">MM Listening Port</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">SSRC From Participant</td> <td class="rgHeader SummaryTableHdrRow" style="font-weight:bold;">SSRC From MM</td> </tr> <xsl:if test="MediaMixer!= ''"> <xsl:for-each select="MediaMixer/Conference"> <xsl:for-each select="Participant"> <xsl:if test="(position() mod 2 = 0)"> <tr class="rgAltRow SummaryTableDataRow"> <td valign = "top"> <xsl:value-of select="../Name"/> </td> <td valign = "top"> <xsl:value-of select="../ConfId"/> </td> <td valign = "top"> <xsl:value-of select="ID1"/> </td> <td valign = "top"> <xsl:value-of select="ID2"/> </td> <td valign = "top"> <xsl:value-of select="ParticipantAddress"/> </td> <td valign = "top"> <xsl:value-of select="ParticipantListeningPort"/> </td> <td valign = "top"> <xsl:value-of select="MMListeningPort"/> </td> <td valign = "top"> <xsl:value-of select="SSRCFromParticipant"/> </td> <td valign = "top"> <xsl:value-of select="SSRCFromMM"/> </td> </tr> </xsl:if> <xsl:if test="(position() mod 2 = 1)"> <td> <tr class="rgRow SummaryTableDataRow"> <td valign = "top"> <xsl:value-of select="../Name"/> </td> <td valign = "top"> <xsl:value-of select="../ConfId"/> </td> <td valign = "top"> <xsl:value-of select="ID1"/> </td> <td valign = "top"> <xsl:value-of select="ID2"/> </td> <td valign = "top"> <xsl:value-of select="ParticipantAddress"/> </td> <td valign = "top"> <xsl:value-of select="ParticipantListeningPort"/> </td> <td valign = "top"> <xsl:value-of select="MMListeningPort"/> </td> <td valign = "top"> <xsl:value-of select="SSRCFromParticipant"/> </td> <td valign = "top"> <xsl:value-of select="SSRCFromMM"/> </td> </tr> </td> </xsl:if> </xsl:for-each> </xsl:for-each> </xsl:if> <xsl:if test="MediaMixer= ''"> <td valign = "top"> <xsl:text>No Data </xsl:text> </td> </xsl:if> </table> </td> </tr> </table> &#160; <div style="display:none"> <iframe id="frameUpdate" name="frameUpdate" width="100%"></iframe> </div> </div> </body> </html> </xsl:template> </xsl:stylesheet> XML file that gets updated dynamically <?xml-stylesheet type="text/xsl" href="MMDiagnostics.xslt"?> <MediaMixer> <Conference> <Name>Test</Name> <ConfId>1002</ConfId> <CompositeAddress>238.57.0.1</CompositeAddress> <CompositePort>48000</CompositePort> <CompositeSsrc>243324353</CompositeSsrc> <NoOfParticipants>2</NoOfParticipants> <Participant> <ID1>abc88C</ID1> <ID2>0</ID2> <ParticipantAddress>192.168.177.45</ParticipantAddress> <ParticipantListeningPort>22004</ParticipantListeningPort> <MMListeningPort>45004</MMListeningPort> <SSRCFromParticipant>316541</SSRCFromParticipant> <SSRCFromMM>26481</SSRCFromMM> </Participant> <Participant> <ID1>piy65R</ID1> <ID2>0</ID2> <ParticipantAddress>192.168.177.45</ParticipantAddress> <ParticipantListeningPort>22004</ParticipantListeningPort> <MMListeningPort>45004</MMListeningPort> <SSRCFromParticipant>316541</SSRCFromParticipant> <SSRCFromMM>26481</SSRCFromMM> </Participant> </Conference> <Conference> <Name>Test3</Name> <ConfId>1007</ConfId> <CompositeAddress>238.57.0.1</CompositeAddress> <CompositePort>48000</CompositePort> <CompositeSsrc>243324353</CompositeSsrc> <NoOfParticipants>2</NoOfParticipants> <Participant> <ID1>abxxC</ID1> <ID2>0</ID2> <ParticipantAddress>192.168.177.45</ParticipantAddress> <ParticipantListeningPort>22004</ParticipantListeningPort> <MMListeningPort>45004</MMListeningPort> <SSRCFromParticipant>316541</SSRCFromParticipant> <SSRCFromMM>26481</SSRCFromMM> </Participant> <Participant> <ID1>yyy65R</ID1> <ID2>0</ID2> <ParticipantAddress>192.168.177.45</ParticipantAddress> <ParticipantListeningPort>22004</ParticipantListeningPort> <MMListeningPort>45004</MMListeningPort> <SSRCFromParticipant>316541</SSRCFromParticipant> <SSRCFromMM>26481</SSRCFromMM> </Participant> </Conference> <Conference> <Name>Test002</Name> <ConfId>1002</ConfId> <CompositeAddress>238.57.0.1</CompositeAddress> <CompositePort>48005</CompositePort> <CompositeSsrc>353324353</CompositeSsrc> <NoOfParticipants>2</NoOfParticipants> <Participant> <ID1>70542151</ID1> <ID2>0</ID2> <ParticipantAddress>192.168.177.45</ParticipantAddress> <ParticipantListeningPort>22004</ParticipantListeningPort> <MMListeningPort>45004</MMListeningPort> <SSRCFromParticipant>316541</SSRCFromParticipant> <SSRCFromMM>26481</SSRCFromMM> </Participant> <Participant> <ID1>70542151</ID1> <ID2>0</ID2> <ParticipantAddress>192.168.177.45</ParticipantAddress> <ParticipantListeningPort>22004</ParticipantListeningPort> <MMListeningPort>45004</MMListeningPort> <SSRCFromParticipant>316541</SSRCFromParticipant> <SSRCFromMM>26481</SSRCFromMM> </Participant> </Conference> </MediaMixer> output looks like this as of now A: This transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my" exclude-result-prefixes="my"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="kCountryByName" match="country" use="@name"/> <my:colors> <color bgcolor="aqua"/> <color bgcolor="blue"/> <color bgcolor="fuchsia"/> <color bgcolor="gray"/> <color bgcolor="green"/> <color bgcolor="lime"/> <color bgcolor="maroon"/> <color bgcolor="navy"/> <color bgcolor="purple"/> <color bgcolor="yellow"/> </my:colors> <xsl:variable name="vColors" select="document('')/*/my:colors/*"/> <xsl:variable name="vDistinctCountries" select= "/*/country [generate-id() = generate-id(key('kCountryByName', @name)[1]) ]"/> <xsl:template match="/*"> <html> <table> <xsl:apply-templates/> </table> </html> </xsl:template> <xsl:template match="country"> <xsl:variable name="vthisName" select="@name"/> <xsl:variable name="vNum"> <xsl:for-each select="$vDistinctCountries"> <xsl:if test="@name = $vthisName"> <xsl:value-of select="position()"/> </xsl:if> </xsl:for-each> </xsl:variable> <tr bgcolor="{$vColors[position()=$vNum]/@bgcolor}"> <td><xsl:value-of select="@name"/></td> <td><xsl:value-of select="@continent"/></td> </tr> </xsl:template> </xsl:stylesheet> when applied on this XML document (as no XML document was provided!!!): <data> <country name="india" continent="Asia"/> <country name="spain" continent="Europe"/> <country name="germany" continent="Europe"/> <country name="india" continent="Asia"/> <country name="sri lanka" continent="Asia"/> <country name="spain" continent="Europe"/> </data> produces the wanted, correct result: <html> <table> <tr bgcolor="aqua"> <td>india</td> <td>Asia</td> </tr> <tr bgcolor="blue"> <td>spain</td> <td>Europe</td> </tr> <tr bgcolor="fuchsia"> <td>germany</td> <td>Europe</td> </tr> <tr bgcolor="aqua"> <td>india</td> <td>Asia</td> </tr> <tr bgcolor="gray"> <td>sri lanka</td> <td>Asia</td> </tr> <tr bgcolor="blue"> <td>spain</td> <td>Europe</td> </tr> </table> </html> Explanation: Muenchian grouping. UPDATE: If there isn't a known upper limit for the number of distinct countries, use something like this: <tr bgcolor="#{$vNum*123456 mod 16777216}"> The complete transformation becomes: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my" exclude-result-prefixes="my"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:key name="kCountryByName" match="country" use="@name"/> <my:colors> <color bgcolor="aqua"/> <color bgcolor="blue"/> <color bgcolor="fuchsia"/> <color bgcolor="gray"/> <color bgcolor="green"/> <color bgcolor="lime"/> <color bgcolor="maroon"/> <color bgcolor="navy"/> <color bgcolor="purple"/> <color bgcolor="yellow"/> </my:colors> <xsl:variable name="vColors" select="document('')/*/my:colors/*"/> <xsl:variable name="vDistinctCountries" select= "/*/country [generate-id() = generate-id(key('kCountryByName', @name)[1]) ]"/> <xsl:template match="/*"> <html> <table> <xsl:apply-templates/> </table> </html> </xsl:template> <xsl:template match="country"> <xsl:variable name="vthisName" select="@name"/> <xsl:variable name="vNum"> <xsl:for-each select="$vDistinctCountries"> <xsl:if test="@name = $vthisName"> <xsl:value-of select="position()"/> </xsl:if> </xsl:for-each> </xsl:variable> <tr bgcolor="#{$vNum*1234567 mod 16777216}"> <td><xsl:value-of select="@name"/></td> <td><xsl:value-of select="@continent"/></td> </tr> </xsl:template> </xsl:stylesheet> and the result now is: <html> <table> <tr bgcolor="#1234567"> <td>india</td> <td>Asia</td> </tr> <tr bgcolor="#2469134"> <td>spain</td> <td>Europe</td> </tr> <tr bgcolor="#3703701"> <td>germany</td> <td>Europe</td> </tr> <tr bgcolor="#1234567"> <td>india</td> <td>Asia</td> </tr> <tr bgcolor="#4938268"> <td>sri lanka</td> <td>Asia</td> </tr> <tr bgcolor="#2469134"> <td>spain</td> <td>Europe</td> </tr> </table> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to create an array that excludes items from another array in Ruby I have two arrays with different attributes for the objects contained in each. participants guests The only field in common is provider_user_id I want to do something like this all_people = participants.map {|p| p.provider_user_id <> guests.provider_user_id } This is probably not correct. How can eliminate those participants who are also in the guests array? A: The following works, but I'd be interested if there's anything more concise. guest_provider_ids = guest.map(&:provider_id) non_guest_participants = participants.reject do |participant| guest_provider_ids.include?(participant.provider_user_id) end A: Could work... guests.each { |g| participants << g } guests.uniq! { |g| g.provider_user_id } This (should) combine the two arrays first, then removes any duplicates based on the key. A: Good answers but don't forget about |. For 1.9 p (guests | participants).uniq!{|g| g.provider_user_id} For 1.8 p (guests | participants).reject{|p| guests.map{|g| g.provider_user_id}.include?(p.provider_user_id)}
{ "language": "en", "url": "https://stackoverflow.com/questions/7563887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send a message to a would-be-generated object I am in a situation in which I need to send an object and a method name a UIViewController that might or might not be instantiated in the future. To make the matter a bit more interesting, the UIViewController will be pushed to UINavigationController after two or three additional UIViewController being pushed. What would be the best way to do this? An ugly approach would be just relay the message package (an object and a method name) via the controllers in-between. That's ugly. Simply subclass UINavigationController and dangle the object and method name? Maybe. Then how do I know when to clear up that message pack? NSInvocation looks really promising in this case though. Any thought? No no no singleton, or extern struct please. Edit: Thanks for the comments. @Akshay, I have thought about that. Question is what if you want to send the message package (an object and a method name) to a specific object under a particular navigationController? Further, if the target object is not instantiated, you would need to clear your singleton for later use. But then how do you know when to clear up? Using singleton is just a mess. @Praveen-K, NSNotifcation only works for those who already exist. I said I want to send a message package to a would-be-generated object. @PragmaOnce, I and two other team mates are designing the architecture now. Hope this explains. Please, no data center singleton. @Sedate Alien, Exactly! @9dan, Thanks for your input. In fact, we have NSClassFromString, NSSelectorFromString, and performSelector that we can instantiate any object and send a message to execute any method with any number of objects. The question is how to elegantly send that message across multiple objects, in my case UIViewController? Say you are at a UIViewController, and you know you would push few more UIViewControllers on top of current one. After that, you might or might not instantiate an object of a specific class and execute a method with an object. How do we do this w/o using singleton? There must be a way to handle this beautifully. I think NSInvocation has that capacity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding specific records based on user's preferences Given a user, select only the projects that he is interested in. So a user table has x, y, z columns that have a value of 1 (if interested) and 0 (if not interested) Once we get the user we need to get all the projects that have the atleast one of x, y, z value similar. So given: prj title | x | y | z | __________________________________________ prj1 | 1 | 0 | 1 | prj2 | 1 | 1 | 0 | prj3 | 0 | 0 | 1 | and the user table: user id | x | y | z | __________________________________________ user1 | 1 | 0 | 0 | user2 | 1 | 1 | 0 | user3 | 0 | 0 | 1 | Need to find a query that will give me a list of projects that a given user (user1) is interested in. Result should be (if user 1 is selected): prj1 and prj2 Result should be (if user 3 is selected): prj1 and prj3 any ideas on how this can be achieved? I am not sure where to start from. I am not sure if this can be done in just one simple query? A: There's one solution with just one query select p.title from prj as p left join user as u on ( ( (u.x = p.x) && (u.x=1) ) || ( (u.y = p.y) && (u.y=1.... and so on, well I hope you got the idea. A: Try this: SELECT p.prj_title FROM prj AS p JOIN users AS s ON ( (u.x=p.x AND u.x=1) OR (u.y=p.y AND u.y=1) OR (u.z=p.z AND u.z=1) ) WHERE u.user_id='user1';
{ "language": "en", "url": "https://stackoverflow.com/questions/7563893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Magento Extension Override Resource File How do you override a resource file like the following when creating a Magento extension: core/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php I know that you can copy this file to the local path and override it that way, but I'm trying to figure out how to override/extend it for an extension. Specifically, what does the config.xml syntax need to look like? I'm wondering whether this is even possible, because all I see online is how to override model files like this one: core/Mage/Catalog/Model/Product.php Which you could do with the following: <models> <catalog> <rewrite> <product>My_Module_Catalog_Model_Product</product> </rewrite> </catalog> <models> or resource files like this one inside of the Eav/Mysql4 directory: core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php Which I believe you could do like this: <models> <catalog_resource_eav_mysql4> <rewrite> <product>My_Module_Catalog_Model_Resource_Eav_Mysql4_Product</attribute></product> </catalog_resource_eav_mysql4> </models> But I don't see how to handle resource files that are not within the Eav directory. Is it possible? A: What I understand now about the Magento class rewrite system, which I did not understand when I posed this question, is that this particular class that I wanted to override in an extension, is not available to be rewritten. The class in question is really more of an abstract-like class, it's never instantiated directly, instead it is subclassed by other classes which are, and which are in turn candidates for rewriting. So the correct way to achieve what I wanted would be to pick the appropriate concrete child class and rewrite it in the normal way, as outlined for instance by losttime's answer here. And how do you determine whether a class is a candidate for rewriting? One way is after you determine the grouped class name, or URI, for the class (ie catalog/product_index_price), search for it in the Magento source and see whether it's used anywhere to actually instantiate the class. A: From the comments on the accepted answer Zyava linked to, you can check the original Module's config.xml file to see what Models are defined. Once you know that, the syntax to override them is the same. The Catalog Module has this Model defined for resources: <global> <models> .... <catalog_resource> <class>Mage_Catalog_Model_Resource</class> ... </catalog_resource> </models> </global> (Note: There is no Mage_Catalog_Model_Resource class, but that's okay because Magento will use this as a base to call all related Models.) Now we know we should use catalog_resource as the XML container for the rewrite, and we know we should use the text that comes after "resource" in the Model's class name to construct the XML container referring to the specific Model we want to override. core/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php xxxxxxxxxx----------------------|-----------------------------xxxx split Catalog/Model/Resource -> catalog_resource Product/Indexer/Price/Default -> product_indexer_price_default This is how it should look in the custom Module's config.xml file: <global> <models> <catalog_resource> <rewrite> <product_indexer_price_default>CompanyName_ModuleName_Model_Catalog_Resource_Product_Indexer_Price_Default</product_indexer_price_default> <rewrite> </catalog_resource> </models> </global> Exactly what class name you override with depends on your Module's configuration. The sample I've used (CompanyName_ModuleName_Model_Catalog_Resource_Product_Indexer_Price_Default) is the one that would fit the file structure I typically use. Yours looks like it might be something like this: My_Module_Catalog_Model_Resource_Product_Indexer_Price_Default A: as you can see this is also a model file under core/Mage/Catalog/Model/ dir so the extending this in config.xml (rewriting and then extending) looks the same like with any other model. if you wan't completely override it then just copy to local/Mage/Catalog/Model/Resource/Product/Indexer/Price/Default.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7563899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting CSS of an unappended element with jQuery I am generating specific DOM elements dynamically for a specific layout. In certain cases I am able to get the width of a previously created element using jQuery (to determine other layout factors). var width = parseInt((jQuery(element).css("width"))); However this only works after the element has been appended to the window. Is there any way to get the theoretical width of an element which is generated, but not yet appended to the window? (Extra info: Down at the function's bare bones, I am simply generating these with a document.createElement()) A: This isn't very practical or useful but I just wrote this function which creates a 'sandbox' by cloning the parent and placing it in the dom offscreen. var getStyle = function($parent, $element, props){ if(typeof props == 'string'){props = [props];} var $sandbox = $parent.clone().css({ position: 'absolute', display: 'inline-block', width: $parent.width(), height: $parent.height(), top: -1000, left: -1000 }); $('body').append($sandbox); $sandbox.append($element); var result = {}; for(var i=0;i<props.length;i++){ var p = props[i]; if(p == 'width'){ result[p] = $element.width(); } else if (p == 'height'){ result[p] = $element.height(); } else{ result[p] = $element.css(p); } } $sandbox.remove(); return result; } console.log( getStyle( $('#name'), //parent $('<div>helo</div>'), //new elemen ['width','height','color'] //properties to fetch ) ); http://jsfiddle.net/beXyM/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7563901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I generate 'h' x n in javascript? Possible Duplicate: Repeat String - Javascript 'h' x n; Here n is a variable, and the generated string should be n times duplicate of h: hh..h( n occurance of h in all) A: String.prototype.repeat = function(n){ var n = n || 0, s = '', i; for (i = 0; i < n; i++){ s += this; } return s; } "h".repeat(5) // output: "hhhhh" Something like that perhaps? A: If I understood your question following may be the solution. var n = 10; var retStr = ""; for(var i=0; i<n; ++i) { retStr += "h"; } return retStr; A: Here's a cute way to do it with no looping: var n = 20; var result = Array(n+1).join('h'); It creates an empty array of a certain length and then joins all the empty elements of the array putting your desired character between the empty elements - thus ending up with a string of all the same character n long. You can see it work here: http://jsfiddle.net/jfriend00/PCweL/ A: Try, function repeat(h, n) { var result = h; for (var i = 1; i < n; i++) result += h; return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java RPG: Useful tools I was thinking about taking on an rpg project in Java from scratch but I have never tried doing much in the way of Java games. It's not going to be very graphically intense; it is going to be 2-D and I want to use a style similar to the older, tile-based RPGs. I was wondering if there were any useful tools that anyone thinks may help. Currently, I only have Eclipse and NetBeans; any input/suggestions are appreciated! Thank you! A: For developing a 2D Java game from scratch, a good 2d game engine is still needed. I recommend slick, one picture that you may be interested in(from its gallery) JGame is also an option. It supports Eclipse: http://www.13thmonkey.org/~boris/jgame/eclipse.html A good article for introducing JGame: http://www.javaworld.com/javaworld/jw-12-2006/jw-1205-games.html A: I wrote a tile-based Java roguelike/RPG many years ago using just plain vanilla Eclipse. Worked fine for me. Full source code here if you are interested (GPL open source): * *Tyrant - Java Roguelike Nowadays I would probably also add the following tools: * *Maven (m2eclipse) - for handling dependencies / 3rd party libraries *EGit / Github - for source code control *Photoshop - for creating and touching up graphics tiles A: I'm going to be a devil's advocate and tell you about Steve Yegge's adventures developing a Java-based RPG, named Wyvern (sadly now defunct). His view, as I understood it, was that Java made the code too complex to maintain; it got to half a million lines long, at one stage. Sure, you might say your game won't get that big. But don't underestimate the power of scope creep. :-) Nevertheless, some successful games are indeed written in Java. mikera's answer is one example, as are games like Runescape or Minecraft. But still, if your game has the potential to get big, Java probably still isn't (in my opinion, and it seems Steve Yegge's also) your best choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Creating a real-time clock I need to display the date an time in the corner of my site, but to show some motion on the page. The formatting is simple. Tuesday, September 27, 2011 at 1:34:27 am However, I'd like the entire thing to change in real time. So after a day has passed if the visitor is still not he site, Tuesday will say Wednesday. And in seconds, 1:34:27 will be ticking along... 28... 29... etc. Pretty simple, right? It's just text. Can't seem to figure this out. A: So when your user lands on the page, you feed server time and date in whatever format you require to your page. Your Javascript executes and starts counting the seconds, minutes etc and changes accordingly. At any point you need to make a reference to time on the server end for logging or what ever else you may require (this will usually be done through a form submit, page load or AJAX call), use the server based time functions, like date('l, jS F, Y at h:i:s a') (which gets you the format you specified) at the start of the PHP script and manipulate as you want. You then have the timestamp when the user performed that particular action. edit... So you are basically looking for a clock that reads from PHP time? Have a look at this: http://jsfiddle.net/positiv/hC4yc/ - I am sure you can adapt this to do what you wan it to. A: Once you send your HTML to the client you'll never be able to change it using your sever end script without client script. A: Since you already have the date printed like that, you can use Date.parse() to get the timestamp from the string. However from my testing it seems the "at" word throws it off, so you'll need to use replace() to remove the word "at", then put it through Date.parse() to get the timestamp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }