text
stringlengths
8
267k
meta
dict
Q: Where to disable cross-network protection in Opera? In JS security issue with Opera 11.01, after moving from server A to B I learned that opera has some "cross-network" protection. I encountered the same js security problem and I found that Opera 11.10 (“Barracuda”) added a preference to disable cross-network protection. My Opera is 11.50 but I can't find the specific preference. Do I misunderstand the meaning of the "cross-network"? Thanks a lot. A: Nowadays Opera is based on chromium, so you shoud use chromium way to disable SOP and process requests without CORS headers: cd c:\Program Files\Opera\ launcher.exe --disable-web-security --user-data-dir="c:\nocorsbrowserdata" Of course like in chromium, to make this work you should kill all your instances of opera.exe before starting with --disable-web-security flag. If you want more details how to automate this, see tip on my website A: I believe opera:config#Network|AllowCrossNetworkNavigation is the right preference. A: Disabling it entirely has security implications though - see this: Opera won't load some JavaScript files for a safer workaround :) A: If you are on a Unix system be careful when using "~/emptydir" for the argument value in --user-data-dir= from @palaniraja's comment on Make Tips's answer. Depending on your environment '~' might not be converted to your home directory and end up making a new directory wherever you are named '~' I went to delete this mistake '~' directory and accidentally almost deleted my entire home directory instead out of negligence. Try using --user-data-dir=$HOME/emptydir instead if you are on a Unix system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Porting C++ socket code to Windows I am trying to make a C++ library used by one of my classes work on both Windows and Linux (it was designed for Linux). The code for it is here (it's not large). I am compiling with MinGW on Windows 7 64 bit. I'm running into trouble with HTTPInputStream during the final linking stage. I edited the top of HTTPInputStream.cpp so that the includes look like this: #include <sstream> #include <iostream> #include <cctype> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/types.h> #ifdef WIN32 #include <Winsock.h> #define bzero(p, l) memset(p, 0, l) #else #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #endif #include "CS240Exception.h" #include "StringUtil.h" #include "HTTPInputStream.h" Here is my makefile: CPP = g++ -g CS240_UTIL_H = utils/inc/CommandRunner.h utils/inc/FileInputStream.h utils/inc/FileSystem.h utils/inc/HTMLToken.h utils/inc/HTMLTokenizer.h utils/inc/HTTPInputStream.h utils/inc/StringUtil.h utils/inc/URLInputStream.h utils/inc/UnitTest.h utils/inc/CS240Exception.h utils/inc/InputStream.h CS240_UTIL_CPP = utils/src/CommandRunner.cpp utils/src/FileInputStream.cpp utils/src/FileSystem.cpp utils/src/HTMLToken.cpp utils/src/HTMLTokenizer.cpp utils/src/HTTPInputStream.cpp utils/src/StringUtil.cpp utils/src/URLInputStream.cpp CS240_UTIL_OBJ = utils/obj/CommandRunner.o utils/obj/FileInputStream.o utils/obj/FileSystem.o utils/obj/HTMLToken.o utils/obj/HTMLTokenizer.o utils/obj/HTTPInputStream.o utils/obj/StringUtil.o utils/obj/URLInputStream.o all: clean lib lib: $(CS240_UTIL_OBJ) $(CPP) -o lib/cs240utils.LIB -I utils/inc $(CS240_UTIL_OBJ) clean: @- rm utils/obj/*.o #library files utils/obj/CommandRunner.o: utils/src/CommandRunner.cpp utils/inc/CommandRunner.h $(CPP) -c -o utils/obj/CommandRunner.o -I utils/inc utils/src/CommandRunner.cpp utils/obj/FileInputStream.o: utils/src/FileInputStream.cpp utils/inc/FileInputStream.h $(CPP) -c -o utils/obj/FileInputStream.o -I utils/inc utils/src/FileInputStream.cpp utils/obj/FileSystem.o: utils/src/FileSystem.cpp utils/inc/FileSystem.h $(CPP) -c -o utils/obj/FileSystem.o -I utils/inc utils/src/FileSystem.cpp utils/obj/HTMLToken.o: utils/src/HTMLToken.cpp utils/inc/HTMLToken.h $(CPP) -c -o utils/obj/HTMLToken.o -I utils/inc utils/src/HTMLToken.cpp utils/obj/HTMLTokenizer.o: utils/src/HTMLTokenizer.cpp utils/inc/HTMLTokenizer.h $(CPP) -c -o utils/obj/HTMLTokenizer.o -I utils/inc utils/src/HTMLTokenizer.cpp utils/obj/HTTPInputStream.o: utils/src/HTTPInputStream.cpp utils/inc/HTTPInputStream.h $(CPP) -c -o utils/obj/HTTPInputStream.o -I utils/inc utils/src/HTTPInputStream.cpp utils/obj/StringUtil.o: utils/src/StringUtil.cpp utils/inc/StringUtil.h $(CPP) -c -o utils/obj/StringUtil.o -I utils/inc utils/src/StringUtil.cpp utils/obj/URLInputStream.o: utils/src/URLInputStream.cpp utils/inc/URLInputStream.h $(CPP) -c -o utils/obj/URLInputStream.o -I utils/inc utils/src/URLInputStream.cpp And here is the output from that makefile: I:>make -f testmake.txt g++ -g -c -o utils/obj/CommandRunner.o -I utils/include utils/src/CommandRunner.cpp g++ -g -c -o utils/obj/FileInputStream.o -I utils/include utils/src/FileInputStream.cpp g++ -g -c -o utils/obj/FileSystem.o -I utils/include utils/src/FileSystem.cpp g++ -g -c -o utils/obj/HTMLToken.o -I utils/include utils/src/HTMLToken.cpp g++ -g -c -o utils/obj/HTMLTokenizer.o -I utils/include utils/src/HTMLTokenizer.cpp g++ -g -c -o utils/obj/HTTPInputStream.o -I utils/include utils/src/HTTPInputStream.cpp g++ -g -c -o utils/obj/StringUtil.o -I utils/include utils/src/StringUtil.cpp g++ -g -c -o utils/obj/URLInputStream.o -I utils/include utils/src/URLInputStream.cpp g++ -g -o lib/cs240utils.LIB -I utils/include utils/obj/CommandRunner.o utils/obj/FileInputStream.o utils/obj/FileSystem.o utils/obj/HTMLToken.o utils/obj/HTMLTokenizer.o utils/obj/HTTPInputStream.o utils/obj/StringUtil.o utils/obj/URLInputStream.o utils/obj/HTTPInputStream.o:I:/utils/src/HTTPInputStream.cpp:246: undefined reference to `_imp__gethostbyname@4' utils/obj/HTTPInputStream.o:I:/utils/src/HTTPInputStream.cpp:255: undefined reference to `_imp__htons@4' utils/obj/HTTPInputStream.o:I:/utils/src/HTTPInputStream.cpp:258: undefined reference to `_imp__socket@12' utils/obj/HTTPInputStream.o:I:/utils/src/HTTPInputStream.cpp:264: undefined reference to `_imp__connect@12' c:/strawberry/c/bin/../lib/gcc/i686-w64-mingw32/4.4.3/../../../../i686-w64-mingw 32/lib/libmingw32.a(lib32_libmingw32_a-crt0_c.o): In function `main':/opt/W64_156151-src.32/build-crt/../mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain@16' collect2: ld returned 1 exit status make: *** [lib] Error 1 I've been googling about this a lot and haven't found anything that solves this. Adding -lwsock32 to the command line doesn't help. Any ideas? A: Assuming the cs240utils.lib is meant to be a static library, you don't use g++ to create it. Instead, you use ar (or lib, if using the MSVC toolchain) to assemble all the files into the library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mouseMoved not called I have a subclassed NSView which is part of a .xib-file of a subclassed NSDocument, which gets alive by the default behaviour of NSDocumentController's openDocument: method. In this subclassed NSView I have implemented the methods awakeFromNib, in which the view's NSWindow setAcceptsMouseMovedEvents:YES method is called, and acceptsFirstMouse:, which returns YES. But my mouseMoved: method implementation of my subclassed NSView doesn't get called when I move the mouse over it. What might be the problem? A: Be sure to request the mouseMoved event is sent: NSTrackingAreaOptions options = (NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved); NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil]; A: As noted by others, an NSTrackingArea is a good solution, and an appropriate place to install the tracking area is NSView.updateTrackingAreas(). It isn't necessary to set the containing NSWindow's setAcceptsMouseMovedEvents property. In Swift 3: class CustomView : NSView { var trackingArea : NSTrackingArea? override func updateTrackingAreas() { if trackingArea != nil { self.removeTrackingArea(trackingArea!) } let options : NSTrackingAreaOptions = [.mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow] trackingArea = NSTrackingArea(rect: self.bounds, options: options, owner: self, userInfo: nil) self.addTrackingArea(trackingArea!) } override func mouseMoved(with event: NSEvent) { Swift.print("Mouse moved: \(event)") } } A: Deshitified version of @jbouwman s answer: override func updateTrackingAreas() { self.addTrackingArea(NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .mouseMoved, .activeInKeyWindow], owner: self, userInfo: nil)) } A: I haven't used mouseMoved: in a real project (I've just played around with it a little). As far as I can tell, mouseMoved: is only called when your view is the first responder and then not only while the mouse is over your view, but always when the mouse moves. You might be better off using an NSTrackingArea. Check the Cocoa Event Handling Guide for more information. A: Just incase anyone else runs into this. I ran into an issue where I was subclassing a subclass and was trying to add a tracking area to both classes (for two different reasons). If you are doing something like this, you will need to make sure that your mouseMoved:, etc call into the super, or only one of your subclasses will receive the message. - (void) mouseMoved: (NSEvent*) theEvent { // Call the super event [super mouseMoved: theEvent]; } A: oc version: - (void)updateTrackingAreas { [self initTrackingArea]; } -(void) initTrackingArea { NSTrackingAreaOptions options = (NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved); NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil]; [self addTrackingArea:area]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Crash when calling clear on an Empty Map I'm getting a strange crash when I try to interact with a map in this particular class. When I try to call clear() or even begin() on the map it crashes. I haven't added anything to map, at this point nothing has touched it at all. Code in question: spriteMap_.clear(); if (!spriteMap_.empty()) { SpriteMap::const_iterator end = spriteMap_.end(); for (SpriteMap::const_iterator it = spriteMap_.begin(); it != end; ++it) { it->second->draw(screen); } } Even stranger is that this is not unique to the map but to any maps in this particular class. I have another map, that is also not being touched until here (I tested it with a clear call in this function). When I use intelli-sense on the maps both show themselves with tons of values already in them and the empty() call returns false. Similarily, size() returns a non-zero result. Info: I'm compiling in Visual Studios 2010 and linking against SDL. Any help is appreciate. Edit (more info): My header has this line: private: std::map spriteMap_; And the only code that is hit is the function I showed you. I have other code but the break point on the function is never hit (I don't call that function). But here it is: Sprite* SpriteManager::createSprite(std::string fileName) { ... Sprite* newSprite = &Sprite(nextSpriteId_, this, image); nextSpriteId_++; spriteMap_[newSprite->id_] = newSprite; return newSprite; } Fixed: Moral of the story is don't ever do something like this: ObjPtr* objPtr = &Obj(); A: You are probably corrupting the map´s memory somewhere within that class. Get the map memory address, and see what happens when you attach breakpoints to such locations. Edit: Sprite* newSprite = &Sprite(nextSpriteId_, this, image); Here you are taking a pointer to a temporary object; note that is not even legal C++ but a nasty MSVC language extension. Right after you take a pointer to it, the temporary Sprite object is destroyed and you are left with an invalid pointer. You then derreference that pointer to get the id -which works just by chance here-, and then add that invalid pointer to the map. That´s at least one of the problems, it may or may not be related to your crash, there may be more problems out there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I remove the 'people like this' message next to facebook like button? Possible Duplicate: Facebook Like-Button - hide count? I created a facebook like button using their Open Graph protocol. Everything works well, except I would like to remove the message next to the Like button that reads "Name and Name both like this." The class for that div is 'connect_confirmation_cell'. I tried setting display:none on that div but it doesn't work. Any Ideas? A: The answer that worked for me was found here: https://stackoverflow.com/a/6326964/562635 I'm using the XFBML button. This will hide the like count but not hide the facebook comment widget that immediately displays after liking a page. /* make the like button smaller */ .fb_edge_widget_with_comment iframe { width:47px !important; } /* but make the span that holds the comment box larger */ span.fb_edge_comment_widget.fb_iframe_widget iframe { width:401px !important; } A: Both the iframe and FBML versions of the Like button use an iframe to display the actual button and associated text, so any CSS styles you try to apply will not work. If you were using the iframe version of the Like button, you could use a CSS style to limit its dimensions to exclude this text while still displaying the actual button. The "zeckdude and Martey like this" text would still be displayed, but not be visible to the user. A: HTMLS: (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); layout="box_count" removes the "name and name likes this". A: this worked for me: .fb-like.fb_edge_widget_with_comment.fb_iframe_widget { height: 26px; overflow: hidden; width: 138px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bug in Chrome or bad CSS? (anchor with visibility hidden) Test this simple line in any HTML: <a href="anything"><span style="visibility:hidden;">insible text here</span></a> (you can test it directly from here: http://jsfiddle.net/wqS3E/ ) In Firefox and IE you can click the link (even more, you can see the default underline decoration). But in Chrome (v 13.0.782.220 ) is not possible to click/see the link. Is this a bug in Chrome or my CSS is not correct? I have a <li> element with a background image, and some <li> are links, and I want to be able to click those links, but I don't want they visibile because I want to show the background image in <li> (and I don't want to brake the HTML markup), so this is what I have: <ul> <li> <a href="link"><span class="invisible">some text</span></a> </li> ... </ul> .invisible { visibility:hidden; } A: I'm not sure there's a standard behavior for invisible stuff inside an <a>. However, i've noticed that setting the display to either block or inline-block makes the link clickable in Chrome. Not sure about other browsers, but if they already display it, that shouldn't break it. A: How about putting the <span> around the <a> instead of otherwise? <span class="invisible"><a href="link">some text</a></span> A: Logically the link should be clickable. Setting visibility:invisible should do just that, make it invisible, but otherwise not affect function. As an analogy, if Chrome's behaviour were correct then the Active Camouflage should make you invulnerable in Halo. Overall, seems like a bug in Chrome to me. Especially since Firefox agrees with IE - that doesn't happen often!
{ "language": "en", "url": "https://stackoverflow.com/questions/7543696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does "vector::iterator" mean there is a "vector" namespace? I have seen the code vector<char> v(10); vector<char>::iterator p; here what is the need of vector<char>::.Does it mean iterator is a class inside vector namespace? A: Does it mean iterator is a class inside vector namespace? Not quite, is a type inside vector class template. The iterator not only depends on the type of container (here a vector), but on the type of element iterated over as well (here a char). A: Possibly the easiest way is to understand that :: is the scope operator, not just for namespaces. std::vector<char> is a class, and therefore it has its own class scope (3.3.6 in C++03, 3.3.7 in C++11). std::vector<char>::iterator is a fully-qualified name in that scope. In the case of iterator, it names a type -- not necessarily a class, and even if it is the class itself is not necessarily defined in std::vector<char>, since iterator could be a typedef. As it happens, a class scope is not one of those things that C++ calls a "namespace". In everyday[*] English, you could describe it as a kind of namespace, it just isn't the proper terminology in C++. However you call it, though, be aware that it's vector<char> which is the class, and has the scope that contains iterator, not vector. std::vector does guarantee that any vector<T> has an iterator type, but for other templates it is not necessarily the case that every specialization has the same members and nested types. So there is no vector scope. [*] "everyday", if your days are the kind of days had by people who talk a lot about namespaces. A: Yes, it does mean exactly that. Iterator is defined within the scope of the class vector, and for each different type a vector is created, there's a different implementation of the iterator as well. A: It also means that the iterator operates on a vector<char> instead of, say, a vector<int>. A: Namespaces cannot be templetized, so vector cannot be a namespace. In fact vector is a template class (and vector is an instantiation) for which iterator is a nested type. But the question has some point: the A::B syntax is normally not distinguishable. In term of name resolution, if fact, both classes an name-spaces are ... container of names. Classes are more than name containers: they represent data having instances and associated functionalities. Namespaces are just container for names
{ "language": "en", "url": "https://stackoverflow.com/questions/7543697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android run bash command in app Hi i'm developing an application which requires me to run some bash code is there a way i can hard code the script into my app and then run it? For instance (this is a VERY simplified example) #!/system/bin/sh # if [ ! -f /sdcard/hello.txt ] then echo 'Hello World' >> /sdcard/hello.txt else echo 'Goodbye World' >> /sdcard/goodbye.txt fi I have the following method for running one line bash commands but need to run something like that that's on multiple lines. Again that above code is a very simplified example what I am actually doing must be run through a script and can't be done through java. I also want to have it hard coded I know could have the script stored on the phone and run it with the following but do not want the script just out there would rather it hard coded in the app. public Boolean execCommand(String command) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes(command + "\n"); os.flush(); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (IOException e) { return false; } catch (InterruptedException e) { return false; } return true; } Thank you for any help with my issue A: If I understand you correctly, all you have to do is change the one line example method to something which accepts and sends multiple lines, like so: public Boolean execCommands(String... command) { try { Runtime rt = Runtime.getRuntime(); Process process = rt.exec("su"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); for(int i = 0; i < command.length; i++) { os.writeBytes(command[i] + "\n"); os.flush(); } os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (IOException e) { return false; } catch (InterruptedException e) { return false; } return true; } That way, you can call your multiline bash commands like so: String[] commands = { "echo 'test' >> /sdcard/test1.txt", "echo 'test2' >>/sdcard/test1.txt" }; execCommands(commands); String commandText = "echo 'foo' >> /sdcard/foo.txt\necho 'bar' >> /sdcard/foo.txt"; execCommands(commandText.split("\n"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7543700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Error 6017: The NavigationProperty '(propertyname)' on the type '(typename)' is the source of Error 6017: The NavigationProperty '(propertyname)' on the type '(typename)' is the source of a generated property '(otherpropertyname)' which conflicts with a member of the same name. OK, I'm fairly certain I understand why I'm getting this error message, but it is not obvious to me how to work around it. I have a table salesreps which links to a table territories with a simple foreign key relationship. The territories table gets updated via an automated feed, whereas the salesreps table is manually maintained through a web interface I am designing. I don't want the reps to be deleted if the territory goes away; I intend to highlight them for manual corrective action in the UI I am building as orphaned reps needing a territory assignment. The sales reps are defined by an ID that is only unique with a given territory (nothing I can do about this, way outside my control), if a territory is removed, I made the foreign key ON DELETE behavior set the territoryID value to null, and made the column nullable. I then created a computed column called territoryReferenceID on the salesreps table set to isnull(territoryID, 0), made it persisted, and created the primary key based off the repID and the territoryReferenceID columns, since I cannot make a nullable PK column (which I still think is lame, even if I understand why it is). In the database, this works fine, and if somehow two territories are deleted with the same repID at the same time (highly unlikely) I'm ok with a primary key violation error that I can trap. Mapping this to EF gives me the aforementioned error. I don't know why EF has a problem with this, and I don't know how to make the problem go away. I want to keep the behavior as designed in the database schema. How can I correct this issue? A: Here's what I ended up doing: I removed the relationships in the entity model and the navigation properties, intending to just use the key ids directly. This worked, until the next time I updated the model from the database, where it reintroduced the relationship and threw the error. So I made a view of the data with only one territoryID column (referencing the computed column) and created stored procedures for creating, modifying, and removing records from the view. This works. It's ugly, but that's what I get for trying to "save time" with EF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can't my program delete the files it creates under Win7? I've made a Java program in Eclipse. I started on Windows XP, but have recently upgraded. As part of it's saving mechanism, the program writes the settings to a file settings_new.sav. If that goes ok, it deletes the settings.sav, and renames the new one to match the old name. While it worked under winXP (at least I thought it did, but I can't check now), under win7, it fails to delete the file, even though it was the program that created it (although, a different instance of the program). The file is picked up by Eclipse and can be deleted from there quite happily. I can delete it manually. I am the admin on my own computer. The folder is just inside the workspace folder, and is not in Program Files (though, I have no idea if eventual users will install it there). The program can create and modify files just fine. It's not throwing any Exception, which I thought it would if it was win7 blocking it. Any ideas? A: It is due to file-locking mechanism in java.Make sure you close the buffering streams such as BufferedReader, BufferedInputStream on that file when done. A: I used to have this problem, when you are done using your file you have to set your file equal to null. So if you do something like: public void createFile(String path) { File file = new File(path); file.createNewFile(); file = null } you have to set the file to null when you are done using it so that the system stops using that file. you have to do the same thing with FileReader and FileWriter. you have to set your file readers and your file writers to null in order to access the file again. Give this a try and let me know how it goes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Chain trigger in Task Scheduler in Windows I scheduled some tasks in Windows task scheduler. I installed a third party tool called Bmail that added a task that sends email from the task scheduler independently. It can be triggered at a given time. Does any one know how to set this up so that Bmail task sends emails when the original tasks are run? How do I link two different tasks in task scheduler and have one trigger the other? A: Sorry if this is considered resurection of an old thread. But i wanted answer on this myself and came here first. You can have them daisy chained. After the first task, schedule the 2nd task to trigger on the event created when the first task completes. It's all explained a bit messy here, https://blogs.msdn.microsoft.com/davethompson/2011/10/25/running-a-scheduled-task-after-another/ By adding this trigger, and firing the Ping Event, the Pong Task Fires immediately after the Ping is complete. It is now a simple case of reusing this XPath replacing the Task Name, \Ping here, with the task to run after: *[EventData[@Name='TaskSuccessEvent'][Data[@Name='TaskName']='\Ping']] If you want even more control, you can do as one of the commentators done in the blog linked above. I've gone further by adding the condition "executing a task only if the previous was completed with the exit code 0". In order to do that, the "Action completed" event is better than the "task completed" one. The Event Data element of this "Action completed" event contains one more child element with the name "ResultCode" which is exactly what we are looking for ! So the xPath is : *[EventData[@Name='ActionSuccess'][Data[@Name='TaskName']='Ping'][Data[@Name='ResultCode']='0']] I will update this post more when i've got it to work myself. A: You could write a script to emulate what the Bmail task is doing (e.g. Run exe, etc), then change the Bmail task to run that script you just wrote. From there change the original task to call the same script, this way, if Bmail changes something on how they run, you could update both tasks but simply changing the script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "Bindable" variables in JavaScript? From my littleexperience in Flex, I learned about Bindable variables, so that the content of a text element changed with th value of a variable, for example. I'm wondering if it's possible to do such a thing in JavaScript. For instance, suppose I have an <h1 id="big_title"> that I want to contain the document's title. That can easily be done with document.getElementById('big_title').innerHTML = document.title;, but what if document.title changes? I'd have to manually update big_title as well. Another way of putting it, is there a way to create a custom onchange-like event handler on a variable rather than a DOM element? This handler could update the title as needed. EDIT: I know I could use a setInterval to check for variable "bindings" (defined in an array) and update as needed, but this would be somewhat hack-ish and would require a compromise between responsiveness and impact on performance. A: You can "watch" objects in most major browsers. Here is a shim. The idea essentially is to have a setter (in that example it's the function called handler) that will be executed when the value changes. I'm not sure what the extent of browser support is. Although to be honest it sounds like a much easier solution to have your own setter method. Either make it into an object (you can easily extend this example to use a generic handler insetad of always changing the title): function Watchable(val) { // non-prototypal modelling to ensure privacy this.set = function(v){ document.title=val=v; }; this.get = function(){return val;}; this.set(val); } var title = new Watchable("original title"); title.get(); // "original title" title.set("second title"); // "second title" title.get(); // "second title" Or if it isn't something you need to instantiate multiple times, a simple function + convention will do: function changeVal(newVal) { variableToWatch = newVal; // change some DOM content } A: A simple method is to concentrate the related elements under one Javascript variable. This variable has a setter method and is bound to a user specified handler function that is called when the setter is invoked. function Binder(handler) { this._value = 0; // will be set this._handler = handler; } Binder.prototype.set = function(val) { this._value = val; this._handler(this); }; Binder.prototype.get = function() { return this._value; }; The Binder is used as follows: <h1 id="h1">Title 0</h1> <h2 id="h2">Title 0</h2> <script type="text/javascript"> function titleHandler(variable) { var val = variable.get(); document.getElementById("h1").innerHTML = val; document.getElementById("h2").innerHTML = "Sub" + val; document.title = val; } var title = new Binder(titleHandler); title.set("Title 2"); </script> A: The best way: (function (win) { function bindCtrl(id, varName) { var c = win.document.getElementById(id); if (!varName) varName = id; if (c) { Object.defineProperty(win, varName, { get: function () { return c.innerHTML; }, set: function (v) { c.innerHTML = v; } }); } return c; } win.bindCtrl = bindCtrl; })(this); // Bind control "test" to "x" variable bindCtrl('test', 'x'); // Change value x = 'Bar (prev: ' + x + ')'; <h1 id="test">Foo</h1>
{ "language": "en", "url": "https://stackoverflow.com/questions/7543710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Getting the database name from a SQL Server Express database in Visual Studio I'm currently using this connection string to attach to my database that I created in Visual Studio: Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Database1.mdf;User Instance=true I'm trying to host the site with IIS so I can mess around with response headers but I'm getting the problem described here: SQL Server Express connection string for Entity Framework Code First I'm trying to find what database name to specify but not having any luck. I tried Initial Catalog=Database1 but that gave me this error: Cannot create file 'D:\docs\Visual Studio 2010\Projects\QuickHomePage\QuickHomePage\App_Data\Database1.mdf' because it already exists. Change the file path or the file name, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. I'm just trying to attach to Database1.mdf. Why is it giving errors about trying to create it? One comment suggested attaching the .mdf file to another database instance to see what's inside it. Would that require running SQL Server Management studio? Every time I try to connect to Server Type Database Engine and the local machine it gives a connection error. A: The database name is the name you give your .MDF file as you attach it to the SQL Server (Express) server instance. There is no fixed database name "inside" the MDF that you need to discover - it's totally up to you what you call your database on the server. So if you attach your Database1.mdf like this: CREATE DATABASE CrazyDatabase ON ( FILENAME = N’C:\Data\Database1.mdf’ ), ( FILENAME = N’C:\Data\Database1_Log.ldf’ ) FOR ATTACH then your database name is CrazyDatabase - but that has no connection whatsoever to the original MDF's file name or any contents inside it - you could call it anything else, too - whatever you choose. In this case, your new connection string would be: Server=.\SQLEXPRESS;Database=CrazyDatabase;Integrated Security=SSPI;
{ "language": "en", "url": "https://stackoverflow.com/questions/7543711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using NSData efficiently I have a bit off code that manipulates Audio files by first putting all the audio file data in NSData variables. But it crashes sometimes because it uses to much RAM NSData *data1 = [NSData dataWithContentsOfFile: someFile]; I have checked using Instruments that everything was being released and how the RAM was being used and I figured out that it just crashes sometimes when the audio file are to big. Is there a way to store data in smaller bits or in the flash or any other way which would allow me to work with big files without exceeding the maximum RAM on the iPhone. One thing Im using the NSData for example is concatenating 2 files like this: [data1 appendData: data2]; Thanks A: Try this (from this SO question): NSData* myBlob; NSUInteger length = [myBlob length]; NSUInteger chunkSize = 100 * 1024; NSUInteger offset = 0; do {     NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;     NSData* chunk = [NSData dataWithBytesNoCopy:(void*)[myBlob bytes] + offset                                          length:thisChunkSize                                    freeWhenDone:NO];     offset += thisChunkSize;     // do something with chunk } while (offset < length); Then, you could store each smaller chunk somewhere and do what you want with it later after concatenating. This is all untested on my end, but it seems reasonable. A: Is there a way to store data in smaller bits or in the flash or any other way which would allow me to work with big files without exceeding the maximum RAM on the iPhone. of course. the problem is more fundamental than NSData - you don't usually load a set of audio files (in their entirety) into memory, especially when the device has very little memory. it's atypical to load the entire file even on osx, where you can have plenty of memory (unless the file is known to be very small). this is why the audio file apis allow you to read and write in blocks (ref: ExtAudioFileRead or AudioFileReadPackets).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are the advantages and disadvantages of real time collaboration in an IDE? I can think of a few disadvantages of having real time collaboration in an IDE like no two people code in the same way so there are chances of semantically conflicting edits that can break the work. But are there any advantages to it? What are the other disadvantages? Thank you for you answers in advance. A: Real time collaboration in an IDE can be used in case of distant learning. It can also be used to review and correct code. The gretest disadvantage of this is that it will cause many errors when many people code together on the same document. There are chances that they use the same variables for different tasks. So, even if the program is compiled right, there are many changes of getting bugs in the code. A: There are advantages such as using it for teaching and as a code review tool. A: It also has its advantages in telephonic interviews. A: In live project we get more knowledge about requirements of the client directly, by this interaction of user we done and deploy our project with in specified period.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Test in JQuery if an element is at the top of screen I have a div that is positioned about 100px from the top of the browser window. When the user scrolls down, I want the div to stay where it is until it reaches the top of the screen. Then, I'll change some CSS with JQuery to make the position to change to fixed and the margin-top to 0. How can I test in JQuery if this div is at the top of the screen? A: var distance = $('div').offset().top, $window = $(window); $window.scroll(function() { if ( $window.scrollTop() >= distance ) { // Your div has reached the top } }); P.S. For better performance, you should probably throttle the scroll event handler. Check out John Resig's article: Learning from Twitter. A: hey you can do like this : var distance = $('.yourclass').offset().top; $(window).scroll(function() { if ( $(this).scrollTop() >= distance ) { console.log('is in top'); } else { console.log('is not in top'); } }); A: Not so much an answer, but could be helpful to someone else. Using the accepted answer above and also referencing the 'Learning from Twitter' link (thank you @Joseph Sibler) I came up with the following. I am using a Twitter Bootstrap Navbar for my primary navigation. It has an ID of megamenu. I also have a 'login' button on my page that when clicked, slides the navbar and all contents below it down to reveal the login form. So what? Well, now the position of my navbar has changed and if I don't update that position, when I scroll the navbar will fly up to the top of the browser - even though it's not really at the top. I came up with this to update the navbar position so if a user clicks 'login' and then scrolls, the navbar will correctly fix itself to the top. logincollapse is my container div that holds the login form and other hidden content until the login button is clicked. I'm sure there is room for improvement - so please correct me, I'll update accordingly. jquery var did_scroll = false, $window = $(window), megamenu_distance = $('#megamenu').offset().top; // The default position of the navbar $('#logincollapse').slideToggle(300, 'easeInOutQuint', function () { megamenu_distance = $('#megamenu').position().top; // Updated position of the navbar .... }); $window.scroll(function (event) { did_scroll = true; }); setInterval(function () { if (did_scroll) { did_scroll = false; if ($window.scrollTop() >= megamenu_distance) { $('#megamenu').addClass('navbar-fixed-top'); } else { $('#megamenu').removeClass('navbar-fixed-top'); } } }, 250); A: when you have header. and then aside bar. for fixing aside bar, when it is at top of the screen: Javascript: var scroll_happened = false; var aside_from_top = $('aside').offset().top; $window = $(window); $window.scroll(function() { scroll_happened = true; }); setInterval(function() { if(scroll_happened == true) { scroll_happened = false; if($window.scrollTop() >= aside_from_top) { $('#aside_container').addClass('fixed_aside'); } else { $('#aside_container').removeClass('fixed_aside'); } } } , 250); Css: .fixed_aside { position: fixed; top: 0; bottom: 0; } Html: <aside> <div id="aside_container"> <section> </section> <section> </section> <section> </section> </div> </aside> A: $(document).ready(function(){ var $doc = $(document); var position = 0; var top = $doc.scrollTop(); // 현재 스크롤바 위치 var screenSize = 0; // 화면크기 var halfScreenSize = 0; // 화면의 반 /* 사용자 설정 값 시작 */ var pageWidth = 1000; // 페이지 폭, 단위:px var leftOffet = 409; // 중앙에서의 폭(왼쪽 -, 오른쪽 +), 단위:px var leftMargin = 909; // 페이지 폭보다 화면이 작을때 옵셋, 단위:px, leftOffet과 pageWidth의 반만큼 차이가 난다. var speed = 1500; // 따라다닐 속도 : "slow", "normal", or "fast" or numeric(단위:msec) var easing = 'swing'; // 따라다니는 방법 기본 두가지 linear, swing var $layer = $('#quick'); // 레이어 셀렉팅 var layerTopOffset = 140; // 레이어 높이 상한선, 단위:px $layer.css('z-index', 10); // 레이어 z-인덱스 /* 사용자 설정 값 끝 */ // 좌우 값을 설정하기 위한 함수 function resetXPosition() { $screenSize = $('#contact').width(); // 화면크기 halfScreenSize = $screenSize / 2; // 화면의 반 xPosition = halfScreenSize + leftOffet; if ($screenSize < pageWidth) xPosition = leftMargin; $layer.css('left', xPosition); } // 스크롤 바를 내린 상태에서 리프레시 했을 경우를 위해 if (top > 0 ) $doc.scrollTop(layerTopOffset+top); else $doc.scrollTop(0); // 최초 레이어가 있을 자리 세팅 $layer.css('top',layerTopOffset); resetXPosition(); // 윈도우 크기 변경 이벤트가 발생하면 $(window).resize(resetXPosition); // 스크롤이벤트가 발생하면 $(window).scroll(function(){ yPosition = $doc.scrollTop() + layerTopOffset; $layer.animate({"top":yPosition }, {duration:speed, easing:easing, queue:false}); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7543718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: regex (vba) - repeat a pattern My code is: Dim regEx, retVal ' Create regular expression. set text = "update my_table set time4 = sysdate, randfield7 = 'FAeKE', randfield3 = 'MyE', the_field9 = 'test' WHERE my_key = '37', tymy_key = 'me';" Set regEx = CreateObject("vbscript.regexp") regEx.pattern = ".+where.+ \'(.+)\'+.*;" regEx.IgnoreCase = True regEx.MultiLine = True regEx.Global = True Set objRegexMC = regEx.Execute(text) MsgBox objRegexMC(0).SubMatches(0) I want it to msgbox 37 and then msgbox me but it only msgboxes me. A: You need to make the match non-greedy, like this: regEx.pattern = "where.+?\'(.+?)\'.+?\'(.+?)\'" A: Sorry, this answer is for Excel, but maybe it'll help put you on the right track. VBA doesn't support lookbehind, but you given the situation, there's a way you can do this (using a substring of the original). Here is the code. Assuming text was in cell A1, here's what you'd write: =RegexExtract(RegexExtract(A1,"WHERE(.+)"),"\'(\w+)\'") It would yield the result: "37, me" Function RegexExtract(ByVal text As String, _ ByVal extract_what As String, _ Optional seperator As String = ", ") As String Application.ScreenUpdating = False Dim i As Long, j As Long Dim result As String Dim allMatches As Object, RE As Object Set RE = CreateObject("vbscript.regexp") RE.Pattern = extract_what RE.Global = True Set allMatches = RE.Execute(text) With allMatches For i = 0 To .Count - 1 For j = 0 To .Item(j).submatches.Count - 1 result = result & (seperator & .Item(i).submatches.Item(j)) Next Next End With If Len(result) <> 0 Then result = Right$(result, Len(result) - Len(seperator)) End If RegexExtract = result Application.ScreenUpdating = True End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/7543720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 1 table, but two tables. Something like disk partitioning for mysql tables Is there a way to have one table that is split in two, or partitioned like a hard drive, so that I can call SELECT * FROM email validated or SELECT * FROM email pending and get two different results. Both results not containing the other's rows. is this something. I feel like I read about mysql partitioning somewhere, a long time ago, and I was wondering if that is what this is. If not, is this possible. A: MySQL supports a virtual table known as a VIEW. A VIEW is effectively a stored MySQL query that can be queried as though it were a real table. Using the example you provide, you would create a base table called email, as follows: CREATE TABLE `email` ( `email` VARCHAR(64) NOT NULL, `validated` CHAR(1) NOT NULL DEFAULT '0', PRIMARY KEY (`email`)) ENGINE = MyISAM; and then two virtual tables (VIEWS), as follows: CREATE VIEW `email_validated` AS SELECT * FROM `email` WHERE `validated`='1'; CREATE VIEW `email_pending` AS SELECT * FROM `email` WHERE `validated`='0'; You can then query both of the views as though they were actual tables. Recognize, however, that using views contains a performance penalty in that the entire view is queried (the entire select statement for the view is executed) whenever the view is referenced. On an example as trivial as this, it won't be a big deal provided the 'validated' field is indexed in the base table. On a more complicated view, however, it may not make sense to load the entire view virtual table into memory when only trying to retrieve a few rows. Other database engines have a structure called a Materialized View, which is the same thing as a MySQL view, excepting that the materialized view exists as a realized table updated at some frequency or trigger. Any operation that can be done to a real table can be done to a materialized table, including changing indexes or even storage engines. It is completely reasonable to have a transaction history using an Archive storage engine while maintaining a roll-up summary table materialized view using a Memory storage engine. Although MySQL does not natively support Materialized Views, there are tricks to mimic the behavior of Materialized Views. A: Well, even if that was possible using partitioning, it would be wrong, as the user eventually will validate the email, and you will have to move it to another partition, which is expensive operation. You have to add column in the table, to store the value. Then, you can partition on that column, so physically recored would be at different places, even on different servers if you setup multiple servers, but that does not make sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this the suitable scenario for Multi-column Indexes? My programming environment is Rails 2.3 and PostgreSQL 8 (shared Database on Heroku): I have read this http://devcenter.heroku.com/articles/postgresql-indexes#multicolumn_indexes and other related resources on the Internet before I started building my app in the generic way: My table has two columns A and B and are both indexed. (The rows are unique in terms of (A,B) pair) But after I built my app, I found that I only query the table with two types of call: myTable.find_by_A_and_B(a,b) and myTable.find_by_A(a) We are expecting to have 10000+ entries in the table, the ratio of distinct A and distinct B is around 3:1. We expect that for each unique value in A, there would be more than 1000+ rows that have different value in B; and for each unique value in B, there would be no more than 300 rows that have different value in A. My question is: Whether the current database setup (with two separate indexes) can be classified as "efficient" in respect to the myTable.find_by_A_and_B(a,b) call (as I have no idea on the inner working of PostgreSQL). And whether replacing the two indexes with just one multi-column indexes of (A,B) will provide significant speed up? Thank you. P.S. In response to the comment, here is a bit more information: According to this page, http://devcenter.heroku.com/articles/database It is running PostgreSQL 8.3 And the follow is the migration schema for myTable: create_table :myTable do |t| t.string :b t.integer:a t.boolean :c, :default => false end add_index :mytable, :b add_index :mytable, :a A: In recent versions of PostgreSQL multi-column indexes can be used efficiently to filter on just one of the columns. This works best on the first column, but reasonably well for the others, too. Also, 10.000 rows is a piece of cake for PostgreSQL. Tables with millions of rows are not uncommon. Assuming we talk about btree indexes (default) on integer (int4) columns ... ... the answer is: just use one multi-column index on (a,b). Due to the page layout on disk (similar for tables and indexes), there is quite a bit of overhead per index row. Also, due to data alignment restrictions, one index (a,b) will use the exact same amount of disk space as an index on just (a) - on machines with MAXALIGN = 8 bytes (most 64-bit OS). So, especially if you have lots of writes or limited disk space and/or RAM, your best bet is to just use one multi-column index on (a,b). Maintaining indexes on heavily written tables carries quite a cost, too. Edit in response to the update on the question: * *With a being integer, my answer is mostly valid. The index on (a,b) will be all or most of what you need. *Get rid of the separate index on b as you obviously don't have queries on just b. *As b is text, the multi-column index on (a,b) cannot profit from data-alignment as much as described above, but still. The greater the medium length of b, the more likely you will profit from an additional index on just a. With short b it probably doesn't pay. Else I would expect it to speed up myTable.find_by_A(a) by just a bit. *This will likely be faster then two separate indexes on a and b, but not by a huge margin, as Postgres can combine two indexes in a bitmap index scan. This has improved since v.8.3. *Be aware that btree indexes on text only help queries with '=' (more if you run on the C locale). Read the manual about operator classes. You don't have to take my word, run some tests with EXPLAIN ANALYZE. It is very simple and informative and index creation for 10.000 rows is a matter of a second or so. Repeat each query a couple of times to populate the cache and get comparable results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UITableViewCell with UITableViewCellStyleValue1; how to get cell to resize textLabel to respect detailtext UITableViewCellStyleValue1 is the cell style that has left-hand black text and right-hand blue detail text. I can set adjustsFontSizeToFitWidth to ensure that the textLabel respects the width of the cell, but it may still over-display the detailTextLabel. How can I tell the textLabel to adjust it's size for to respect the detailView? Is sub-classing UITableViewCell the only approach? A: Yes, the only way that I would tackle this problem is via a subclass. You could do it with what you are given, but you are in the end, you are putting the same amount of work into it, so I would go with the more control you get with a subclass, so if you wanted to change anything in the future you have the power to do so.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I speed up Rails unit tests involving image upload/resizing? My app does a lot with images. I use paperclip to attach them to models. I have tons of tests (Test::Unit) that involve creating images, these run pretty slowly. I use FactoryGirl to create models in my tests. This is how I create image attachments: factory :product_image_100_100 do image File.new(File.join(::Rails.root.to_s, "/test/fixtures/images", "100_100.jpg")) end How can I fake the image upload or otherwise speed things up? A: This snippet worked for me: require 'test_helper' class PhotoTest < ActiveSupport::TestCase setup do Paperclip::Attachment.any_instance.stubs(:post_process).returns(true) end # tests... end Upd. My current preference is to stub out ImageMagic globally, by adding the following to my test_helper.rb: module Paperclip def self.run(cmd, *) case cmd when "identify" return "100x100" when "convert" return else super end end end (Adapted from here – btw, you may want to take a look at this article if you're interested in speeding up your tests)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java regex error - Look-behind group does not have an obvious maximum length I get this error: java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 22 ([a-z])(?!.*\1)(?<!\1.+)([a-z])(?!.*\2)(?<!\2.+)(.)(\3)(.)(\5) ^ I'm trying to match COFFEE, but not BOBBEE. I'm using java 1.6. A: Java takes things a step further by allowing finite repetition. You still cannot use the star or plus, but you can use the question mark and the curly braces with the max parameter specified. Java determines the minimum and maximum possible lengths of the lookbehind. The lookbehind in the regex (?<!ab{2,4}c{3,5}d)test has 6 possible lengths. It can be between 7 to 11 characters long. When Java (version 6 or later) tries to match the lookbehind, it first steps back the minimum number of characters (7 in this example) in the string and then evaluates the regex inside the lookbehind as usual, from left to right. If it fails, Java steps back one more character and tries again. If the lookbehind continues to fail, Java continues to step back until the lookbehind either matches or it has stepped back the maximum number of characters (11 in this example). This repeated stepping back through the subject string kills performance when the number of possible lengths of the lookbehind grows. Keep this in mind. Don't choose an arbitrarily large maximum number of repetitions to work around the lack of infinite quantifiers inside lookbehind. Java 4 and 5 have bugs that cause lookbehind with alternation or variable quantifiers to fail when it should succeed in some situations. These bugs were fixed in Java 6. Copied from Here A: To avoid this error, you should replace + with a region like {0,10}: ([a-z])(?!.*\1)(?<!\1.{0,10})([a-z])(?!.*\2)(?<!\2.{0,10})(.)(\3)(.)(\5) A: Java doesn't support variable length in look behind. In this case, it seems you can easily ignore it (assuming your entire input is one word): ([a-z])(?!.*\1)([a-z])(?!.*\2)(.)(\3)(.)(\5) Both lookbehinds do not add anything: the first asserts at least two characters where you only had one, and the second checks the second character is different from the first, which was already covered by (?!.*\1). Working example: http://regexr.com?2up96
{ "language": "en", "url": "https://stackoverflow.com/questions/7543746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How often should I open/close my Booksleeve connection? I'm using the Booksleeve library in a C#/ASP.NET 4 application. Currently the RedisConnection object is a static object across my MonoLink class. Should I be keeping this connection open, or should I be open/closing it after each query/transaction (as I'm doing now)? Just slightly confused. Here's how I'm using it, as of now: public static MonoLink CreateMonolink(string URL) { redis.Open(); var transaction = redis.CreateTransaction(); string Key = null; try { var IncrementTask = transaction.Strings.Increment(0, "nextmonolink"); if (!IncrementTask.Wait(5000)) { transaction.Discard(); throw new System.TimeoutException("Monolink index increment timed out."); } // Increment complete Key = string.Format("monolink:{0}", IncrementTask.Result); var AddLinkTask = transaction.Strings.Set(0, Key, URL); if (!AddLinkTask.Wait(5000)) { transaction.Discard(); throw new System.TimeoutException("Add monolink creation timed out."); } // Run the transaction var ExecTransaction = transaction.Execute(); if (!ExecTransaction.Wait(5000)) { throw new System.TimeoutException("Add monolink transaction timed out."); } } catch (Exception ex) { transaction.Discard(); throw ex; } finally { redis.Close(false); } // Link has been added to redis MonoLink ml = new MonoLink(); ml.Key = Key; ml.URL = URL; return ml; } Thanks, in advance, for any responses/insight. Also, is there any sort of official documentation for this library? Thank you S.O. ^_^. A: Should I be keeping this connection open, or should I be open/closing it after each query/transaction (as I'm doing now)? There is probably a little overhead if you will open a new connection each time you want to make a query/transaction and although redis is designed for high level of concurrently connected clients, there might be performance problems if their number is around tens of thousands. As far as I know connection pooling should be done by the client libraries (because redis itself doesn't have this functionality), so you should check if booksleeve supports this stuff. Otherwise you should open the connection when your application starts and keep it open for it's lifetime (in case you don't need parallel clients connected to redis for some reason). Also, is there any sort of official documentation for this library? The only documentation I was able to find regarding how to use it was tests folder in it's source codes. A: For reference (continuing @bzlm's answer), I created a Singleton that always provides the same Redis connection using BookSleeve (if it's closed, it's being created. Else, the existing connection is being served). Look at this: https://stackoverflow.com/a/8777999/290343 You consume it like that: RedisConnection connection = Redis.RedisConnectionGateway.Current.GetConnection(); A: According to the author of Booksleeve, The connection is thread safe and intended to be massively shared; don't do a connection per operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: PHP Form/jQuery validate e-mail address - Display bad email addresses I'm looking for a jQuery plugin to validate a text file that contains many records (including email addresses). Example: Textfile.txt 1)Last Name, First Name, Email Address .. .. 100)Last Name, First Name, Email Address If a bad email address is found, a list of the offending email addresses will be displayed in a textarea before the text file is loaded. The closeset plugin I've found: http://lifeasrose.ca/2011/01/tutorial-using-jquery-to-validate-form-input/ This only validates a single email form input field. Any advise or guidance is greatly appreciated. A: You can use HTML 5 to read file contents with Javascript. Demo here Another nice example [here] http://www.html5rocks.com/en/tutorials/file/dndfiles/ FileReader.readAsText(Blob|File, opt_encoding) - The result property will contain the file/blob's data as a text string. By default the string is decoded as 'UTF-8'. Use the optional encoding parameter can specify a different format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C bitwise shift I suppose sizeof(char) is one byte. Then when I write following code, #include<stdio.h> int main(void) { char x = 10; printf("%d", x<<5); } The output is 320 My question is, if char is one byte long and value is 10, it should be: 0000 1010 When I shift by 5, shouldn't it become: 0100 0001 so why is output 320 and not 65? I am using gcc on Linux and checked that sizeof(char) = 1 A: In C, all intermediates that are smaller than int are automatically promoted to int. Therefore, your char is being promoted to larger than 8 bits. So your 0000 1010 is being shifted up by 5 bits to get 320. (nothing is shifted off the top) If you want to rotate, you need to do two shifts and a mask: unsigned char x = 10; x = (x << 5) | (x >> 3); x &= 0xff; printf("%d", x); It's possible to do it faster using inline assembly or if the compiler supports it, intrinsics. A: Mysticial is right. If you do char x = 10; printf("%c", x); It prints "@", which, if you check your ASCII table, is 64. 0000 1010 << 5 = 0001 0100 0000 You had overflow, but since it was promoted to an int, it just printed the number. A: Because what you describe is a rotate, not a shift. 0 is always shifted in on left shifts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what's the usage of extensions in the build section For some maven POM.xml, I found there are extensions in the build section. What's the purpose to include build extensions? A: Takes less than 6 second in Google and read. See here http://maven.apache.org/pom.html#Extensions Extensions are a list of artifacts that are to be used in this build. They will be included in the running build's classpath. They can enable extensions to the build process (such as add an ftp provider for the Wagon transport mechanism), as well as make plugins active which make changes to the build lifecycle. In short, extensions are artifacts that activated during build. The extensions do not have to actually do anything nor contain a Mojo. For this reason, extensions are excellent for specifying one out of multiple implementations of a common plugin interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How many bits are needed to address this much memory? I'm taking a programming fundamentals course and currently I'm on the chapter where it talks about computer organization and operations on bits - how the CPU (ALU, CU, registers, etc.) works. I have a fairly good understanding of the binary language. I understand sign/magnitude format/ 1's complement, 2's complement, etc. In the book I've learned that a nibble = 4 bits, 8 bits = 1 byte next is a word - which is usually in groups: 8 bits, 16 bits, 32 bits or 64 bits (so on), and all this makes perfect sense to me. Here's my homework question which is kind of confusing to me: "A computer has 64 MB of memory, Each word is 4 bytes. How many bits are needed to address each single word in memory?" Well, I'm confused now. The book just told me that a word is typically in multiples of 8. However I know that 1 byte = 8 bits, so since there are 4 bytes and 1 byte = 8 bytes, would it be correct to think that 4 bytes x 8 bits = 32 bits? Is this the answer? A: A 1-bit address can address two words (0, 1). A 2-bit address can address four words (00, 01, 10, 11). A 3-bit address can address eight words (000, 001, 010, 011, 100, 101, 110, 111). So first answer: How many words do you have? Then answer: How many bits does your address need in order to address them? A: 64MB = 67108864 Bytes/4 Bytes = 16777216 words in memory, and each single word can thus be addressed in 24 bits (first word has address 000000000000000000000000 and last has address 111111111111111111111111). Also 2 raised to 24 = 16777216, so 24 bits are needed to address each word in memory. The requirement is to represent each memory word with an address, which is in bits, in such a way that each and every word can be represented. For example, to represent 4 words, you need 4 addresses, 2 raised to 2 is 4, so you need two bits. 00 is the address of the first word, 01 is the address of the second word, 10 is the address of the third word, and 11 is the address of the 4th word. For 8 words, you need 8 addresses, and 2 raised to 3 is 8, so 3 bits are needed. 000, 001, 010, 011, 100, 101, 110, 111 are the 8 addresses. A: 1 byte = 8 bits, so since there are 4 bytes and 1 byte = 8 bites Would it be correct to think 4bytes x 8 bites = 32 bits?? being the answer??? No, that's not the answer. If your computer has 64 MB of memory and each word is 4 bytes, how many words are there in your memory? How much bits would you need to address each word (bits needed to represent a number from 0 to number of words - 1). A: The formula being: log (Memory Size/Addressable Unit Size) / log 2 Example1: How many address bits are required to address 16GBytes of memory, where each addressable unit is 1 byte wide? Ans: log(16*1024*1024*1024/1)/log2 = 34 bits Example2: How many address bits are required to address 16GBytes of memory, where each addressable unit is 2 bytes wide? Ans: log(16*1024*1024*1024/2)/log2 = 33 bits Example3: How many address bits are required to address 64MBytes of memory, where each addressable unit is 4 bytes wide? Ans: log(64*1024*1024/4)/log2 = 24 bits Example3: How many address bits are required to address 16MBytes of memory, where each addressable unit is 1 byte wide? Ans: log(16*1024*1024/1)/log2 = 24 bits
{ "language": "en", "url": "https://stackoverflow.com/questions/7543763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to stop the forces acting on a body in box2d I am using box2d on the iphone to create a game. I have a body that is effected by gravity to move down and not right or left. It will get hit by another body and will then be moving right or left. I then have a reset button which moves the body back to its starting point. The only problem is that it is still moving right or left. How can I counteract the forces that a ball is already traveling? How can I get rid of this right and left movement when I reset my game? A: Box2d automatically clears the forces each simulation step. I think you are just changing your body's position when resetting, but not its velocity. Add this code to your reset method: body->SetLinearVelocity(b2Vec2(0,0)); body->SetAngularVelocity(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7543764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Pop function and linked list implementation Alright guys, so I know how the pop function works obviously. I also know that I need to set a LinkNode * top = head and that if top == NULL that you need to return NULL. I'm just not sure what I'm honestly supposed to do after that. The return is supposed to remove and return a value and the data type of the function is a pointer. I'm not going to post my code on here unless people are honestly going to help me out because I've already been criticized greatly once and it was quite discouraging. :\ A: “I … know that I need to set a LinkNode * top = head and that if top == NULL that you need to return NULL. I'm just not sure what I'm honestly supposed to do after that.” Well, the things you mention have nothing to do with pop. For a linked list, pop is about unlinking the first node. Depending on the level of abstraction the function might return (a pointer to) that node, or the node’s “value”, or nothing. At the lowest level of abstraction you want just the unlink functionality, which can go like this: struct Node { Node* next; double value; }; Node* unlinked( Node*& p ) { Node* const result = p; p = p->next; return result; } Then, as an example, a pop that destroys the node goes like this: void pop( Node*& first ) { delete unlinked( first ); } while a pop that returns the value in the node goes like this: double pop( Node*& first ) { std::unique_ptr<Node> p( unlinked( first ) ); return p->value; } A subtle point here is whether the value is guaranteed to be copied before the node is destroyed. I'm just assuming it is. I leave it to the lawyers to find the standardese for that. Cheers & hth.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: q(i,j)=X x P1(i,j) + (1-X) x P2(i,j) :how to code it in matlab? q(i,j)=X x P1(i,j) + (1-X) x P2(i,j) where P1 and P2 are two input images and X is any constant value ,e.g X=0.5 how to write the code for it ? A: Assuming P1 and P2 are stored in matrices and have the same size, you can just write q = X * P1 + (1-X) * P2 To read in images you want to use imread A: Consider using the IMLINCOMB function to compute linear combination of images: q = imlincomb(x,P1, 1-x,P2);
{ "language": "en", "url": "https://stackoverflow.com/questions/7543770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Getting the type of an object in Javascript when its prototype is assigned an instance of another object I must have some sort of fundamental misunderstanding of how objects work in Javascript because I am unable to figure out why the following outputs what it does. You can see the jsfiddle of the following code here: http://jsfiddle.net/VivekVish/8Qvkn/1/ Note that is uses the getName function defined here: How do I get the name of an object's type in JavaScript? Object.prototype.getName = function() { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec((this).constructor.toString()); return (results && results.length > 1) ? results[1] : ""; }; function ContentProvider() { } function LessonProvider() { console.log(this.getName()); } lessonProvider1 = new LessonProvider(); LessonProvider.prototype = new ContentProvider(); lessonProvider2 = new LessonProvider(); The above code outputs the following to the console: LessonProvider ContentProvider But why isn't it LessonProvider in both cases and how can one make it LessonProvider in both cases? A: if you insist- LessonProvider.prototype = new ContentProvider() LessonProvider.prototype.constructor=LessonProvider; A: If you don't reset the pointer to the constructor, the all the children will report that the parent object is their constructor. LessonProvider.prototype.constructor = LessonProvider; You may want to try using a function like below for inheritance: function inherit(C, P) { //empty function used as a proxy var F = function() {}; //set F's prototype equal to P's prototype F.prototype = P.prototype; //C will only inherit properties from the F's prototype C.prototype = new F(); //set access to the parents (P's) prototype if needed C.uber = P.prototype; //Set the constructor back to C C.prototype.constructor = C; } inherit(LessonProvider, ContentProvider);
{ "language": "en", "url": "https://stackoverflow.com/questions/7543771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MovieClip does everything it's supposed to, and still there is `error 1009` I'm creating game in which user is given a map and five flags. User must drag flags, one by one to the countries, so after creating MovieClips that represent flags, I started creating code for them. That worked for France, but after I copied it to Germany and changed everything using CTRL+F ('france' to 'germany' and 'France' to 'Germany') it didn't. Well, actually it did, but there is some error. That's funny, coz German flag does absolutely everything it should, and still there is an error in the output. Here, that's the code: package { import flash.display.MovieClip; import flash.events.MouseEvent; public class flagGermany extends MovieClip { public var Name:String="Germany"; public var atX:uint; public var atY:uint; public var wasGuessed:Boolean=false; public var isPressed:Boolean=false; public function flagGermany() { trace(this); this.addEventListener(MouseEvent.MOUSE_DOWN, dragEnable); this.addEventListener(MouseEvent.MOUSE_UP, dragDisable); stage.addEventListener(MouseEvent.MOUSE_UP, dragDisable); } function dragEnable(e:MouseEvent) { isPressed=true; trace(isPressed); atX=stage.mouseX-this.x; atY=stage.mouseY-this.y; this.alpha=0.3; this.mouseEnabled=false; stage.addEventListener(MouseEvent.MOUSE_MOVE, moveFlag); } function dragDisable(e:MouseEvent) { if(isPressed==true) { if(wasGuessed==false) { this.alpha=1; this.mouseEnabled=true; } trace("invoked by "+e.target); if(MovieClip(this.root).germany.currentFrame==2) { MovieClip(this.root).germany.gotoAndStop(3); MovieClip(this.root).germany.removeEventListener(MouseEvent.ROLL_OVER, MovieClip(this.root).hightlight); MovieClip(this.root).germany.removeEventListener(MouseEvent.ROLL_OUT, MovieClip(this.root).unhightlight); correct(); } stage.removeEventListener(MouseEvent.MOUSE_MOVE, moveFlag); isPressed=false; trace(isPressed); } } function moveFlag(e:MouseEvent) { this.x=stage.mouseX-atX; this.y=stage.mouseY-atY; } function correct() { this.removeEventListener(MouseEvent.MOUSE_DOWN, dragEnable); this.removeEventListener(MouseEvent.MOUSE_UP, dragDisable); this.alpha=0; this.mouseEnabled=false; this.wasGuessed=true; } } } And here's an error: TypeError: Error #1009: Cannot access a property or method of a null object reference. at flagGermany() at flash.display::Sprite/constructChildren() at flash.display::Sprite() at flash.display::MovieClip() at EM() EM is main file's Document Class. flagGermany() a constructor for German flag. Both flags are created on second frame of the movie. What's the matter with my code?! A: I believe for stage to non-null, the MovieClip has to be addChild'ed first. I would check out why is France getting stage and Germany not. A: Make sure stage is available before adding event listeners to it: public function flagGermany() { /* .. */ addEventListener("addedToStage", onAddedToStage); } private function onAddedToStage(event:*):void { stage.addEventListener(MouseEvent.MOUSE_UP, dragDisable); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby JSON parse changes Hash keys Lets say I have this Hash: { :info => [ { :from => "Ryan Bates", :message => "sup bra", :time => "04:35 AM" } ] } I can call the info array by doing hash[:info]. Now when I turn this into JSON (JSON.generate), and then parse it (JSON.parse), I get this hash: { "info" => [ { "from" => "Ryan Bates", "message" => "sup bra", "time" => "04:35 AM" } ] } Now if I use hash[:info] it returns nil, but not if I use hash["info"]. Why is this? And is there anyway to fix this incompatibility (besides using string keys from the start)? A: I solved my similar issue with calling the with_indifferent_access method on it Here I have a json string and we can assign it to variable s s = "{\"foo\":{\"bar\":\"cool\"}}" So now I can parse the data with the JSON class and assign it to h h = JSON.parse(s).with_indifferent_access This will produce a hash that can accept a string or a symbol as the key h[:foo]["bar"] #=> "cool" A: * *Use ActiveSupport::JSON.decode, it will allow you to swap json parsers easier *Use ActiveSupport::JSON.decode(my_json, symbolize_names: true) This will recursively symbolize all keys in the hash. (confirmed on ruby 2.0) A: In short, no. Think about it this way, storing symbols in JSON is the same as storing strings in JSON. So you cannot possibly distinguish between the two when it comes to parsing the JSON string. You can of course convert the string keys back into symbols, or in fact even build a class to interact with JSON which does this automagically, but I would recommend just using strings. But, just for the sake of it, here are the answers to this question the previous times it's been asked: what is the best way to convert a json formatted key value pair to ruby hash with symbol as key? ActiveSupport::JSON decode hash losing symbols Or perhaps a HashWithIndifferentAccess A: It's possible to modify all the keys in a hash to convert them from a string to a symbol: symbol_hash = Hash[obj.map{ |k,v| [k.to_sym, v] }] puts symbol_hash[:info] # => {"from"=>"Ryan Bates", "message"=>"sup bra", "time"=>"04:35 AM"} Unfortunately that doesn't work for the hash nested inside the array. You can, however, write a little recursive method that converts all hash keys: def symbolize_keys(obj) #puts obj.class # Useful for debugging return obj.collect { |a| symbolize_keys(a) } if obj.is_a?(Array) return obj unless obj.is_a?(Hash) return Hash[obj.map{ |k,v| [k.to_sym, symbolize_keys(v)] }] end symbol_hash = symbolize_keys(hash) puts symbol_hash[:info] # => {:from=>"Ryan Bates", :message=>"sup bra", :time=>"04:35 AM"} A: The JSON generator converts symbols to strings because JSON does not support symbols. Since JSON keys are all strings, parsing a JSON document will produce a Ruby hash with string keys by default. You can tell the parser to use symbols instead of strings by using the symbolize_names option. Example: original_hash = {:info => [{:from => "Ryan Bates", :message => "sup bra", :time => "04:35 AM"}]} serialized = JSON.generate(original_hash) new_hash = JSON.parse(serialized, {:symbolize_names => true}) new_hash[:info] #=> [{:from=>"Ryan Bates", :message=>"sup bra", :time=>"04:35 AM"}] Reference: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON.html#method-i-parse A: You can't use that option like this ActiveSupport::JSON.decode(str_json, symbolize_names: true) In Rails 4.1 or later, ActiveSupport::JSON.decode no longer accepts an options hash for MultiJSON. MultiJSON reached its end of life and has been removed. You can use symbolize_keys to handle it. Warning: It works only for JSON strings parsed to hash. ActiveSupport::JSON.decode(str_json).symbolize_keys
{ "language": "en", "url": "https://stackoverflow.com/questions/7543779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: How to mock and stub active record before_create callback with factory_girl I have an ActiveRecord Model, PricePackage. That has a before_create call back. This call back uses a 3rd party API to make a remote connection. I am using factory girl and would like to stub out this api so that when new factories are built during testing the remote calls are not made. I am using Rspec for mocks and stubs. The problem i'm having is that the Rspec methods are not available within my factories.rb model: class PricePackage < ActiveRecord::Base has_many :users before_create :register_with_3rdparty attr_accessible :price, :price_in_dollars, :price_in_cents, :title def register_with_3rdparty return true if self.price.nil? begin 3rdPartyClass::Plan.create( :amount => self.price_in_cents, :interval => 'month', :name => "#{::Rails.env} Item #{self.title}", :currency => 'usd', :id => self.title) rescue Exception => ex puts "stripe exception #{self.title} #{ex}, using existing price" plan = 3rdPartyClass::Plan.retrieve(self.title) self.price_in_cents = plan.amount return true end end factory: #PricePackage Factory.define :price_package do |f| f.title "test_package" f.price_in_cents "500" f.max_domains "20" f.max_users "4" f.max_apps "10" f.after_build do |pp| # #heres where would like to mock out the 3rd party response # 3rd_party = mock() 3rd_party.stub!(:amount).price_in_cents 3rdPartyClass::Plan.stub!(:create).and_return(3rd_party) end end I'm not sure how to get the rspec mock and stub helpers loaded into my factories.rb and this might not be the best way to handle this. A: Checkout the VCR gem (https://www.relishapp.com/myronmarston/vcr). It will record your test suite's HTTP interactions and play them back for you. Removing any requirement to actually make HTTP connections to 3rd party API's. I've found this to be a much simpler approach than mocking the interaction out manually. Here's an example using a Foursquare library. VCR.config do |c| c.cassette_library_dir = 'test/cassettes' c.stub_with :faraday end describe Checkin do it 'must check you in to a location' do VCR.use_cassette('foursquare_checkin') do Skittles.checkin('abcd1234') # Doesn't actually make any HTTP calls. # Just plays back the foursquare_checkin VCR # cassette. end end end A: As the author of the VCR gem, you'd probably expect me to recommend it for cases like these. I do indeed recommend it for testing HTTP-dependent code, but I think there's an underlying problem with your design. Don't forget that TDD (test-driven development) is meant to be a design discipline, and when you find it painful to easily test something, that's telling you something about your design. Listen to your tests' pain! In this case, I think your model has no business making the 3rd party API call. It's a pretty significant violation of the single responsibility principle. Models should be responsible for the validation and persistence of some data, but this is definitely beyond that. Instead, I would recommend you move the 3rd party API call into an observer. Pat Maddox has a great blog post discussing how observers can (and should) be used to loosely couple things without violating the SRP (single responsibility principle), and how that makes testing, much, much easier, and also improves your design. Once you've moved that into an observer, it's easy enough to disable the observer in your unit tests (except for the specific tests for that observer), but keep it enabled in production and in your integration tests. You can use Pat's no-peeping-toms plugin to help with this, or, if you're on rails 3.1, you should check out the new functionality built in to ActiveModel that allows you to easily enable/disable observers. A: Although I can see the appeal in terms of encapsulation, the 3rd party stubbing doesn't have to happen (and in some ways perhaps shouldn't happen) within your factory. Instead of encapsulating it in the factory you can simply define it at the start of your RSpec tests. Doing this also ensures that the assumptions of your tests are clear and stated at the start (which can be very helpful when debugging) Before any tests that use PricePlan, setup the desired response and then return it from the 3rd party .create method: before(:all) do 3rd_party = mock('ThirdParty') 3rdPartyClass::Plan.stub(:create).and_return(true) end This should allow you to call the method but will head off the remote call. *It looks like your 3rd Party stub has some dependencies on the original object (:price_in_cents) however without knowing more about the exact dependency I can't guess what would be the appropriate stubbing (or if any is necessary)* A: FactoryGirl can stub out an object's attributes, maybe that can help you: # Returns an object with all defined attributes stubbed out stub = FactoryGirl.build_stubbed(:user) You can find more info in FactoryGirl's rdocs A: I had the same exact issue. Observer discussion aside (it might be the right approach), here is what worked for me (it's a start and can/should be improved upon): add a file 3rdparty.rb to spec/support with these contents: RSpec.configure do |config| config.before do stub(3rdPartyClass::Plan).create do [add stuff here] end end end And make sure that your spec_helper.rb has this: Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } A: Well, first, you're right that 'mock and stub' are not the language of Factory Girl Guessing at your model relationships, I think you'll want to build another object factory, set its properties, and then associate them. #PricePackage Factory.define :price_package do |f| f.title "test_package" f.price_in_cents "500" f.max_domains "20" f.max_users "4" f.max_apps "10" f.after_build do |pp| f.3rdClass { Factory(:3rd_party) } end Factory.define :3rd_party do |tp| tp.price_in_cents = 1000 end Hopefully I didn't mangle the relationship illegibly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Whats design pattern does UITableView use to populate and what are the benefits of delegate and datasource setup? Whats design pattern does UITableView use to populate and what are the benefits? Is it delegate pattern? Reason I am asking is that it's not just delegate but the datasource as well.Seems more like along the line with MVC. I have just gone through a couple of tutorials online their\my code is working but it looks like I am missing the point.I end with all these methods in my main controller. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 10;//any number based on datasource size. } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } // Set up the cell... cell.text = [names objectAtIndex:indexPath.row];//names is an array. return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { } It is a view based application . Should it be in a sperate controller.Otherwise it just looks messy and over the top way of doing something simple. I am not at all saying Objective C or apple is wrong but just that I am a beginner and missing the whole point of this delegate and datasource setup. so to summarise can someone please explain: 1-Whats the benefit of this delegate and datasource setup? 2-Whats the name of this design pattern? 3-Should I have a separate controller (in view based application)? A: * *In Apple's parlance, delegate implements call-back methods which modify the UI behavior, and dataSource provides the data. In a bigger app, you can use two different objects to be the delegate and the data source separately. *I'm not familiar with the official terminology, sorry ... *Depends on the size of your app. Even if you just use appDelegate for everything, it's recommended to add #pragma mark -- table view delegate methods ...methods... #pragma mark -- table view data source methods ...more methods... so that the method list is shown nicely inside Xcode. A: Look into n-tier design methodologies. Most all patterns are to create code thats adaptable to change (and less prone to bugs). The benefit here is that with those pieces abstracted from your view controller will allow more flexibility and ideally less headaches for maintaining the code. If your requirements change, or your data you have to modify this file. Whereas with the data source isolated you could end up just having to modify that one file. More important with the data since it tends to be external and perhaps created by some other entity this is often changed. Also storage strategy may change, you could go from XML to core data with no impact on the view controller, delegate or views. On the delegate, what if design changed and this same data was reused elsewhere. If the delegate isn't tied to this view controller this becomes a simple matter of reusing the delegate code where needed. Then add other complicating factors, maybe you've subclassed UITableView. Perhaps, you display the same data in two different places, and in both cases you've subclassed UITableViewCell. Maybe the requirements aren't for two different views, but this view controller here has an option to display a detailed version and a brief version. Food for thought.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing a directory time/date I tried utime() on both Windows (XP) and Linux. On Windows I get an EACCES error, on Linux I don't get any error (but the time is not changed). My utime() code is fine, because it works on files. I could not find if utime() is supposed to work on directories or not, but if not, how can I change the time and date? I am looking for a solution that would ideally work for both Windows and Linux, but if not, I can always use some OS specific code. [edit] It seems that utime does indeed work on Linux, but it didn't appear to work for me because I was moving files in that directory, and that updated the time stamp to the current time. A: For Windows you can use the SetFileTime which also works for directories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding an ID to a Raphael circle I'm trying to make a drag curver with Raphael. Please look for this: r.circle(x, y, 6).attr({ fill: "#ff0000", stroke: "none", id: "cir1" }), This is my code: $(document).ready(function() { var r = Raphael("holder", 1583, 600), discattr = { fill: "#ff0000", stroke: "none" }; r.rect(9950, 9990, 6199, 4199, 9910, 777777777777).attr({ stroke: "#000000" }); r.text(310, 20, "").attr({ fill: "#fff", "font-size": 16 }); function curve(x, y, ax, ay, bx, by, zx, zy, color) { var path = [["M", x, y], ["C", ax, ay, bx, by, zx, zy]], path2 = [["M", x, y], ["L", ax, ay], ["M", bx, by], ["L", zx, zy]], curve = r.path(path).attr({ stroke: color || Raphael.getColor(), "stroke-width": 4, "id": "path" }), controls = r.set( r.path(path2).attr({ stroke: "#000000", id: 'path' }), r.circle(x, y, 6).attr({ fill: "#ff0000", stroke: "none", id: "cir1" }), r.circle(ax, ay, 6).attr({ fill: '#ff0000', stroke: 'none', 'id': 'cir2' }), r.circle(bx, by, 6).attr({ fill: "#ff0000", stroke: "none", id: "cir3" }), r.circle(zx, zy, 6).attr({ fill: "#ff0000", stroke: "none", id: "cir4" })); t = false; controls[1].update = function(x, y) { var X = this.attr("cx") + x, Y = this.attr("cy") + y; this.attr({ cx: X, cy: Y }); path[0][1] = X; path[0][2] = Y; path2[0][1] = X; path2[0][2] = Y; t = false; controls[2].update(x, y); }; controls[2].update = function(x, y) { var X = this.attr("cx") + x, Y = this.attr("cy") + y; this.attr({ cx: X, cy: Y }); path[1][1] = X; path[1][2] = Y; path2[1][1] = X; path2[1][2] = Y; t = false; curve.attr({ path: path }); controls[0].attr({ path: path2 }); }; controls[3].update = function(x, y) { var X = this.attr("cx") + x, Y = this.attr("cy") + y; this.attr({ cx: X, cy: Y }); path[1][3] = X; path[1][4] = Y; path2[2][1] = X; path2[2][2] = Y; t = false; curve.attr({ path: path }); controls[0].attr({ path: path2 }); }; controls[4].update = function(x, y) { var X = this.attr("cx") + x, Y = this.attr("cy") + y; this.attr({ cx: X, cy: Y }); path[1][5] = X; path[1][6] = Y; t = false; path2[3][1] = X; path2[3][2] = Y; controls[3].update(x, y); }; controls.drag(move, up); t = false; } function move(dx, dy) { this.update(dx - (this.dx || 0), dy - (this.dy || 0)); this.dx = dx; this.dy = dy; t = false; } function up() { this.dx = this.dy = 0; t = false; } // curve(70, 100, 80, 100, 130, 154, 170, 200, "hsb(0, .75, .75)"); curve(100, 100, 100, 100, 100, 100, 100, 100, "#ff0000"); }); I am trying to add an id to each circle, but it is not working for some reason. A: You can add miscellaneous data, like a custom ID, using the element.data() function. Your circle code snippet could be the following: r.circle(x, y, 6).attr({ fill: "#ff0000", stroke: "none" }).data("id", "cir1"),
{ "language": "en", "url": "https://stackoverflow.com/questions/7543792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with heatmaps in Google Fusion Tables These are my two functions for searching my table and making overlays. (the map is created in a different function). For some reason, the dotmap one works fine, but the heatmap one doesn't work with the where clause. Any insight? function heatmap() { var layer = new google.maps.FusionTablesLayer({ query: { select: 'LOCATION', from: '1614684', where: "CRIME = 'HOMICIDE'" }, heatmap: { enabled: true } }); layer.setMap(map); } function dotmap() { var layer = new google.maps.FusionTablesLayer({ query: { select: 'LOCATION', from: '1614684', where: "CRIME = 'HOMICIDE'" } }); layer.setMap(map); } A: I think the problem is the same as mentioned here: https://groups.google.com/forum/#!topic/fusion-tables-users-group/MkZ8KJT6oic In short, Heatmaps in Google Fusion Tables is a little flaky. You might want to use something like gheat which somehow worked, but not as nice and simple as I wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best data structure for an immutable persistent 3D grid I'm experimenting with writing a game in a functional programming style, which implies representing the game state with a purely functional, immutable data structures. One of the most important data structures would be a 3D grid representing the world, where objects can be stored at any [x,y,z] grid location. The properties I want for this data structure are: * *Immutable *Fast persistent updates - i.e. creation of a new version of the entire grid with small changes is cheap and achieved through structural sharing. The grid may be large so copy-on-write is not a feasible option. *Efficient handling of sparse areas / identical values - empty / unpopulated areas should consume no resources (to allow for large open spaces). Bonus points if it is also efficient at storing large "blocks" of identical values *Unbounded - can grow in any direction as required *Fast reads / lookups - i.e. can quickly retrieve the object(s) at [x,y,z] *Fast volume queries, i.e. quick searches through a region [x1,y1,z1] -> [x2,y2,z2], ideally exploiting sparsity so that empty spaces are quickly skipped over Any suggestions on the best data structure to use for this? P.S. I know this may not be the most practical way to write a game, I'm just doing it as a learning experience and to stretch my abilities with FP...... A: I'd try an octtree. The boundary coordinates of each node are implicit in structure placement, and each nonterminal node keep 8 subtree but no data. You can thus 'unioning' to gain space. I think that Immutable and Unbounded are (generally) conflicting requirements. Anyway... to grow a octtree you must must replace the root. Other requirement you pose should be met.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: WebSockets - How to create different messages? I am creating a websocket chat application and I managed to relay chat messages to other browsers connected. I have a console application listening on one port. My question is... If one person logs on to the system I want everybody to know that, how can I do that? I'm using Linq to map the DB but if the logging is ok how do I send that message, that user X has logged in? FINALLY I was able to create a chatroom using websockets, here is the final product, thanks for the orientation! http://ukchatpoint.no-ip.org/Chatpoint/Pages/Uklobby.aspx A: First make sure you're sending messages as JSON (JavaScript Object Notation) as this allows structured data to be sent back and forth, and client & server can differentiate between a chat message and an instruction (e.g. someone new logged in). For instance on the client: mySocket.onmessage = function(event) { var command = JSON.parse(event.data); if(command.type === 'message') { var message = command.message; // handle chat message } else if (command.type === 'newUser') { var username = command.username; // handle new user } }; On the server in ASP.NET C# you'd send them as: public class ChatHandler : WebSocketHandler { private JavaScriptSerializer serializer = new JavaScriptSerializer(); private static WebSocketCollection chatapp = new WebSocketCollection(); public override void OnMessage(string message) { var m = serializer.Deserialize<Message>(message); switch (m.Type) { case MessageType.NewUser: chatapp.Broadcast(serializer.Serialize(new { type = "newUser", username = m.username })); break; case MessageType.Message: chatapp.Broadcast(serializer.Serialize(new { type = "message", message = m.message })); break; default: return; } } } As Hightechrider says, you'll need to keep track of a list of connected clients, that's what WebSocketCollection class does in the code listing above. Check out Paul Batum's WebSocket chat example on github here (https://github.com/paulbatum/BUILD-2011-WebSocket-Chat-Samples/blob/master/BasicAspNetChat/ChatHandler.cs) Also he did a presentation at the recent MS BUILD conference here (http://channel9.msdn.com/Events/BUILD/BUILD2011/SAC-807T) A: You would need to track the connections at the application level so you can send to all of them. But take a look at SignalR instead where a lot of the work involved with webSockets and long polling is being written for you. With SignalR you can use GetClients to get all the clients connected to a Hub. A: When using PostgreSQL, you could use NOTIFY from within the database to notify the application layer, which could generate messages sent via WebSockets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between the Kohana's Request cookie(), Response cookie() and the Cookie class? I'm working on a program dealing with cookies under the kohana's HMVC structure, and I find that Kohana has 3 ways to get/set the cookie. They are Request::current()->cookie(), Response->cookie(), and the cookie class (Cookie::set(), get()) And PHP has a native setcookie() function and $_COOKIE to deal with cookies too. Could anyone explain their differences and, what are the situations that they should be used respectively. A: Request::cookie() prior to calling Request::execute() on the same object is used to set the cookies that will be send (or have been sent in case of the initial request) along with the rest of the request. Request::cookie() during a Request::execute() will replace $_COOKIE. Response::cookie() during a Request::execute() will replace setcookie(). Response::cookie() after a Request::execute() is used to get the cookies set back by the server. The Cookie helper will sign your cookies and is used by HTTP_Header to set cookies set to the Response object in your initial Request object (see Response::send_headers() in index.php). You probably do not want to use it yourself directly if you are trying to code HMVC safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jquery mobile page flash during transition after submit I am using phonegap + jquery mobile and have a submit function that works and after it submits it transitions to another page. these pages are inner pages such as data-role="pages" like jquery mobile uses. The problem is that before it finally transitions to the right inner page, it shows the first page with the data-role="pages" set for a split second. It doesn't prevent it from working I am just trying to prevent it from flashing the first page as its irrelevant and for it to transition properly to the proper page. Here is my javascript: function addarticle(){ var truth=$("#addform").validate().form() if(truth==true){ var headlinetemp=$('#headline').val(); var articletemp=$('#article').val(); navigator.notification.activityStart(); $.ajax({ type:'POST', url: "http://server.net/droiddev/backbone1/index.php/welcome/addarticle/", data: { 'headline': headlinetemp, 'article': articletemp}, success:function(){ $('#headline').val(''); $('#article').val(''); $.mobile.changePage($('#thanks'), { transition: "slide"}); //above is suppose to take you to thank you page without blinking the first page navigator.notification.activityStop(); }, error:function(xhr){ navigator.notification.activityStop(); alert('Error: Article was not added.'); } }); } else{alert('Please Correct the Form');} } here is the html <!DOCTYPE html> <html> <head> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js"></script> <script type="text/javascript" charset="utf-8" src="main.js"></script> <style type="text/css"> #ajaxarea1{width:308px; display:block; margin:2px auto; height:50px; overflow:hidden;} #errorarea ul li{ color:red;} .center{text-align:center;} </style> </head> <body onload="init()" style=""> <!-- Start of first page --> <div data-role="page" id="foo" data-title="Page Foo" data-theme="d" > <div data-role="header" data-theme="d" data-position="fixed"> <h1>Foo</h1><a href="#" data-role="button" style="float:left;" data-rel="back" data-icon="arrow-l" data-iconpos="notext">Back</a> </div><!-- /header --> <div data-role="content"> <p>I'm first in the source order so I'm shown as the page.</p> <p>View internal page called <a href="#bar" data-role="button" data-theme="d" data-transition="slide">bar</a></p> <a href="#addart" data-role="button" data-theme="d" >Add Article</a> <!--<input type="text" id="numinput" placeholder="Enter a number.."></input>--> <div id="ajaxarea1"><p>This should change by hitting the button below</p></div> <button type="button" id="calcbtn" onclick="change_ajaxarea1()">Ajax call</button> </div><!-- /content --> </div> </div><!-- /page --> <!-- Start of second page --> <div data-role="page" id="thanks" data-theme="d"> <p> testing thank you page!</p> </div> <div data-role="page" id="bar" data-theme="d" data-title="Page bar ya fool!"> <div data-role="header" data-theme="d"> <h1>Bar</h1> <a href="#" data-role="button" style="float:left;" data-rel="back" data-icon="arrow-l" data-theme="d" data-iconpos="notext">Back</a> </div><!-- /header --> <div data-role="content"> <p>I'm first in the source order so I'm shown as the page.</p> <p><a href="#foo">Back to foo</a></p> <a href="http://server.net">Test ajax</a> <div style="margin-top:10px;"><input type="text" placeholder="Testing placeholder.." style=""></input></div> </div><!-- /content --> <!--<div data-role="footer" data-position="fixed"> <p style="width:100%;margin:0 auto;display:block;padding:5px;">The footer is over here and i hope this doesnt get cut off. </p> </div> --> <!-- /footer --> </div><!-- /page --> <!-- Start of third(add) page --> <div data-role="page" id="addart" data-theme="d" data-title="Page bar ya fool!"> <div data-role="header" data-theme="d"> <h1>Add article</h1> <a href="#" data-role="button" style="float:left;" data-rel="back" data-icon="arrow-l" data-theme="d" data-iconpos="notext">Back</a> </div><!-- /header --> <div data-role="content"> <form id="addform" style="text-align:center;"> <div id="errorarea"><ul> </ul></div><label for="Headline">Headline</label><br/><input type="text" name="Headline" title="Enter a title for the Headline at least 5 chars" class="required" id="headline" style="margin: 10px auto 20px auto;" placeholder="enter article headline.."></input> <br/> <label for="Article">Article</label><br/><textarea cols="40" rows="8" name="Article" id="article" class="required" title="Enter a article" name="textarea" style="margin: 10px auto 20px auto;" placeholder="enter article content.." id="textarea"></textarea> <br/> <input data-inline="true" style="display:inline-block;clear:both;text-align:center;" type="submit" value="Add Article" onclick="addarticle()"></input> </form> </div> <!-- /content --> <!--<div data-role="footer" data-position="fixed"> <p style="width:100%;margin:0 auto;display:block;padding:5px;">The footer is over here and i hope this doesnt get cut off. </p> </div> --> <!-- /footer --> </div><!-- /page --> </body> </html> I hope I made my problem clear. thank you A: To all that have flashes when the page loads, insert in the head tag: <meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, maximum-scale=1.0, user-scalable=no" />; This should fix any problems. A: I think this is a known issue: https://github.com/jquery/jquery-mobile/issues/455 A: I encountered this very same problem with JQuery Mobile 1.1.1 and JQuery Core 1.7.1. I resolved it by upgrading to JQuery Mobile 1.2.0 beta and JQuery Core 1.8.1. No additional changes were necessary to get rid of the page flicker.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: regex javascript to match both RGB and RGBA Currently I have this regex which matches to an RGB string. I need it enhanced so that it is robust enough to match either RGB or RGBA. rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/; //matches RGB http://jsfiddle.net/YxU2m/ var rgbString = "rgb(0, 70, 255)"; var RGBAString = "rgba(0, 70, 255, 0.5)"; var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/; //need help on this regex //I figure it needs to be ^rgba?, and then also an optional clause to handle the opacity var partsRGB = rgbString.match(rgbRegex); var partsRGBA = RGBAString.match(rgbRegex); console.log(partsRGB); //["rgb(0, 70, 255)", "0", "70", "255"] console.log(partsRGBA); //null. I want ["rgb(0, 70, 255, 0.5)", "0", "70", "255", "0.5"] A: Will this do? var rgbRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/ A: It's not so simple- an rgb is illegal with a fourth parameter. You also need to allow for percentage decimals as well as integer values for the rgb numbers. And spaces are allowed almost anywhere. function getRgbish(c){ var i= 0, itm, M= c.replace(/ +/g, '').match(/(rgba?)|(\d+(\.\d+)?%?)|(\.\d+)/g); if(M && M.length> 3){ while(i<3){ itm= M[++i]; if(itm.indexOf('%')!= -1){ itm= Math.round(parseFloat(itm)*2.55); } else itm= parseInt(itm); if(itm<0 || itm> 255) return NaN; M[i]= itm; } if(c.indexOf('rgba')=== 0){ if(M[4]==undefined ||M[4]<0 || M[4]> 1) return NaN; } else if(M[4]) return NaN; return M[0]+'('+M.slice(1).join(',')+')'; } return NaN; } //testing: var A= ['rgb(100,100,255)', 'rgb(100,100,255,.75)', 'rgba(100,100,255,.75)', 'rgb(100%,100%)', 'rgb(50%,100%,0)', 'rgba(100%,100%,0)', 'rgba(110%,110%,0,1)']; A.map(getRgbish).join('\n'); returned values: rgb(100,100,255) NaN rgba(100,100,255,.75) NaN rgb(127,255,0) NaN NaN A: I made a regex that checks for rgb() and rgba() values. It checks for 3 tuples of 0-255 and then an optional decimal number between 0-1 for transparency. TLDR; rgba?\(((25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*?){2}(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,?\s*([01]\.?\d*?)?\) Broken into the different parts we have: rgba?\( // Match rgb( or rgba( as the a is optional 0-255 is matched with alternation of: \d\d? // Match 0-99 1\d\d // Match 100 - 199 2[0-4]\d // Match 200-249 25[0-5] // Match 250 - 255 The handling of comma and space around the 0-255 tuples takes some space. I match 0-255 tuples with mandatory trailing comma and optional spaces twice (25[0-5]|2[0-4]\d|1([0-9]){1,2}|\d\d?)\s*,\s*){2} Then a 0-255 tuple with optional comma and space - to allow for rgb() values without the trailing comma (25[0-5]|2[0-4]\d|1([0-9]){1,2}|\d\d?),?\s* Then comes an optional 0-1 as whole number or decimal number: ([01]\.?\d*?)? // 0 or 1 needed, dot and decimal numbers optional And we end with a closing bracket \) A: Try the following script for RGBA value, the result is an object. var getRGBA = function (string) { var match = string.match(/^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d*(?:\.\d+)?)\)$/); return match ? { r: Number(match[1]), g: Number(match[2]), b: Number(match[3]), a: Number(match[4]) } : {} }; var rgba = getRGBA('rgba(255, 255, 255, 0.49)'); console.log(rgba); A: If you need to be strict, i.e. rule out rgb(0, 70, 255, 0.5), you need to fuse both cases together with | : var rgbRegex = /(^rgb\((\d+),\s*(\d+),\s*(\d+)\)$)|(^rgba\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+\.\d+)*\)$)/; http://jsfiddle.net/YxU2m/2/ A: You can use this regex: var regex = /(^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6})$|^(rgb|hsl)a?\((\s*\/?\s*[+-]?\d*(\.\d+)?%?,?\s*){3,5}\)$)/igm; Example: function myFunction() { var myRegex = /(^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6})$|^(rgb|hsl)a?\((\s*\/?\s*[+-]?\d*(\.\d+)?%?,?\s*){3,5}\)$)/igm; var el = document.getElementById('input'); document.getElementById('value').textContent = myRegex.test(el.value); } <input id="input" /> <button onclick="myFunction()">Submit</button> <br /> <p id="value"></p> Should match: * *#111 *#1111 *#222222 *rgb(3,3,3) *rgba(4%,4,4%,0.4) *hsl(5,5,5) *hsla(6,6,6,0.6) A: Fun way to spend an evening! Code Here it is: /^rgba?\(\s*(?!\d+(?:\.|\s*\-?)\d+\.\d+)\-?(?:\d*\.\d+|\d+)(%?)(?:(?:\s*,\s*\-?(?:\d+|\d*\.\d+)\1){2}(?:\s*,\s*\-?(?:\d+|\d*\.\d+)%?)?|(?:(?:\s*\-?\d*\.\d+|\s*\-\d+|\s+\d+){2}|(?:\s*\-?(?:\d+|\d*\.\d+)%){2})(?:\s*\/\s*\-?(?:\d+|\d*\.\d+)%?)?)\s*\)$/i This regex isn't case-insensitive for rgba/RGBA so we should probably keep the i flag when running. 192 characters! To avoid negative lookaheads and to only roughly match more common inputs, try /^rgba?\(\d+(?:(?:\s*,\s*\d+){2}(?:\s*,\s*(?:\d*\.\d+|\d+)%?)?)|(?:(?:\s+\d+){2}(?:\s*\/\s*(?:\d*\.\d+|\d+)%?)?)\)$/ Note that this is only presently useful for testing validity. Adding reliable capture groups would lengthen and complicate it past a level I'm comfortable hand-rolling. We can extract the numbers after validating with something like: regexStr .match(/\((.+)\)/)[1] .trim() .split(/\s*[,\/]\s*|\s+/) Background The purpose of this code is particularly to match the current CSS allowed rgb/rgba values. Might not fit everyone's use case, but that's what the Bounty was for. Since posting, CSS now allows rgb(R G B / A). It also allows percentages, negatives, and decimals for all values. These are therefore valid: ✔ rgb(1, -2, .3, -.2) ✔ rgb(1 -2 .3 / -.2) ✔ rgb(1 -2 .3 / -.2%) ✔ rgb(1% -2% .3% / -.2%) ✔ rgb(1% -2% .3% / -.2) When using percentages, all three color values must be percentages as well. The alpha can be a percentage in any environment. While writing this, I also found an area where implementing this was quite difficult with regex. ✔ rgb(1 .2.3) ✔ rgb(1-.2.3) ✘ rgb(1.2.3) ✘ rgb(1 -2.3) The bottom 2 examples are false when using CSS.supports(color, str). Essentially, if it looks like it's possible that the rgb() only contains 2 values, it will register as invalid. We can just handle this directly as a special case by creating a variable-length negative lookahead. This may be important to realize if we want to transfer this regex to another engine. (?!\d+(?:\.|\s*\-?)\d+\.\d+) It just rejects early on matches for 1.2.3, 1 2.3, and 1 -2.3. Code Walkthrough This is a massive one, so I'll take it apart, piece-by-piece. I'm going to pretend we're dealing with Extended Mode and so I'll litter the regex with whitespace and comments to make things clearer. ^rgba?\(\s* (?!\d+(?:\.|\s*\-?)\d+\.\d+) # negative lookahead \-?(?:\d*\.\d+|\d+) # handle 1,-1,-.1,-1.1 (%?) # save optional percentage * *To start, we make the a optional and allow whitespace after the parentheses. *We add our negative lookahead for the 2 special cases. *We then match our first number. Our number can be an integer, fractional, and possibly negative. *We capture the optional percentage. This is to save on characters later by taking advantage of backreferences. We save about 60 characters with this. (?: # next 2-3 numbers either (?: # 2 separated by commas \s*,\s* \-?(?:\d+|\d*\.\d+) \1 ){2} (?: # optional third maybe-percentage \s*,\s* \-?(?:\d+|\d*\.\d+) %? )? * *Next, capture comma separated values. *\1 refers to the % if it existed earlier *Allow our third number to have a percentage irrespective of whether the previous numbers hade one. |(?: # match space-separated numbers (?: # non-percentages \s*\-?\d*\.\d+ # space-optional decimal |\s*\-\d+ # space-opt negative |\s+\d+ # space-req integer ){2} |(?: # or percentages \s* \-?(?:\d+|\d*\.\d+) % ){2} ) (?: # optional third maybe-percentage \s*\/\s* \-?(?:\d+|\d*\.\d+) %? )? * *First try matching non percentage numbers separated by either ., -, or whitespace. *If no match, try percentage numbers, space optional *Optionally match the alpha value, separated by / A: i use this it is help (.*?)(rgb|rgba)\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/i if you check rgba(102,51,68,0.6) it will return 1. [0-0] `` 2. [0-4] `rgba` 3. [5-8] `102` 4. [9-11] `51` 5. [12-14] `68` 6. [15-18] `0.6` and if you check rgb(102,51,68) it will return 1. [21-21] `` 2. [21-24] `rgb` 3. [25-28] `102` 4. [29-31] `51` 5. [32-34] `68` A: This regex is a good compromise between the complexity of the regex and number of use-cases covered. /(rgb\(((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]),\s*){2}([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\)))|(rgba\(((([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]),\s*){3}(1|1.0*|0?.\d)\)))/ rgb and rgba need to be treated differently as one needs the 4th argument and one doesn't. This regex takes that into account. It also deals with: * *1, 2 or 3 digit rgb values *rgb values under 0 and over 255 *(some) spaces *a 4th value missing from rgba *a 4th value in rgb This regex does not take into account: * *every legal type of spacing *percentage based rgb values A: For patterns: rbga(12,123,12,1) rbga(12,12,12, 0.232342) rgb(2,3,4) /^(rgba|rgb)\(\s?\d{1,3}\,\s?\d{1,3}\,\s?\d{1,3}(\,\s?(\d|\d\.\d+))?\s?\)$/ A: /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*((0+(?:\.\d+)?)|(1+(?:\.0+)?)))?\)$/.test('rgba(255,255,255,1.000000)') A: It's impossible to write a regex that does everything you want, exactly. The core difficulty is that on the one hand, you want to capture the color values, yet on the other hand, whether there are commas between G, B and A depends on whether there was a comma between R and G. The only way to have that conditionality is to have a conditional capture group for the G value (and B and A). But you only want a result value that looks like ["rgb(1,2,3)", "1", "2", "3"]. The conditionality means that, if you want an expression that properly parses the syntax rules, you're going to get a result like ["rgb(1,2,3)", null, null, null, null, "1", "2", "3", null]. I don't see any way around that. That said, there is an easy way to handle that slight messiness with a quick post-regex filter. With the right regex, all that is needed is to remove all null's from the result, which can be done by applying a filter() to the result array. Also, non-capturing groups, /(?:...)/, are your friend here - they let us group things to create the alternatives without adding captures to the result array. I've based my rules for color and opacity values on the CSS documentation: * *https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb() *https://developer.mozilla.org/en-US/docs/Web/CSS/number *https://developer.mozilla.org/en-US/docs/Web/CSS/percentage So, here's my best shot: var testStrings = [ // These should succeed: "rgb(0, 70, 255)", "rgba(0, 70, 127, 0.5)", "rgba(0, 70, 255, .555)", "rgba(0, 70, 255, 1.0)", "rgba(0, 70, 255, 5%)", "rgba(0, 70, 255, 40%)", "rgba(0, 70, 255, 0)", "rgba(0 70 255)", "rgba(0 70 25e1)", "rgb( 0 70 255 / 50 )", // These should fail: "rgb(0, 70 255)", "rgb(0 70 255, .5)", "rgb(0, 70 255)", "rgb(2.5.5)", "rgb(100, 100, 100 / 30)", ]; // It's easiest if we build up the regex string from some meaningful substrings. // "comma" supports arbitrary space around a comma. var comma = "\\s*,\\s*"; // "number" supports signed/unsigned integers, decimals, // scientific notation, and percentages. var number = "([+-]?\\d*.?\\d+(?:e[+-]?\\d+)?%?)"; // "commaList" matches 3- or 4-tuples like "0, 70, 255, 50". var commaList = number + comma + number + comma + number + "(?:" + comma + number + ")?"; // "noCommaList" supports "space-separated" format, "0 70 255 / 50". var noCommaList = number + "\\s+" + number + "\\s+" + number + "(?:\\s*/\\s*" + number + ")?"; // Here's our regex string - it's just the "rgb()" syntax // wrapped around either a comma-separated or space-separated list. var rgb = "^rgba?\\(\\s*(?:" + commaList + "|" + noCommaList + ")\\s*\\)$"; // Finally, we create the RegExp object. var rgbRegex = new RegExp(rgb); // Run some tests. var results = testStrings.map(s => s.match(rgbRegex)); // Post-process to remove nulls results = results.map(result => result && result.filter(s => s)); // Log the full regex string and all our test results. console.log(rgbRegex); console.log(results.map(result => JSON.stringify(result)).join('\n')); A: Pistus' answer seemed to be the closest for me to get working properly. The problem is you cannot attempt to run the same matching group twice using {2}, it just gives you the same answer twice of the second matching group. This will handle the following sloppy CSS: rgba(255 , 255 , 255 , 0.1 ) rgba( 255 , 255, 255 , .5 ) rgba( 0, 255 , 255 , 1.0 ) rgb( 0, 255 , 255 ) rgba( 0, 255 , 255 ) // <-- yes, not correct, but works and give you a good, clean response. I didn't really need something that properly validated as much as I needed something that would give me clean numbers. In the end, this is what worked for me: rgba?\(\s*(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,?\s*([01\.]\.?\d?)?\s*\) Link to Regex101: https://regex101.com/r/brjTFf/1 Also, I cleaned up the matching groups so all you get is the cleanest JS array: let regex = /rgba?\(\s*(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,\s*(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*,?\s*([01\.]\.?\d?)?\s*\)/; let bgColor = "rgba(0, 255, 0, .5)"; console.log( bgColor.match( regex ) ); Here's the output from the console: [ "rgba(0, 255, 0, .5)", "0", "255", "0", ".5" ] A: You can concat 2 patterns by |, but then you have to handle 7 groups instead of 4. ^rgb(?:\((\d+),\s*(\d+),\s*(\d+)\)|a\((\d+),\s*(\d+),\s*(\d+),\s*(1|0?\.\d+)\))$ This would look like: (Image by jex.im) It's not really complete, but should answere the question. For test and debug: * *regex101 (use java!) *debuggex To handle the goups, you can work with substituion: $1$4-$2$5-$3$6-$7. So you will get in: rbg(1,2,3) out: 1-2-3- in: rgba(1,2,3,0.3) out: 1-2-3-0.3 then you can split. A: rgba?\((\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(\d{1,3})\s*(,\s*\d*\.\d\s*)?|\s*(\d{1,3})\s*(\d{1,3})\s*(\d{1,3})\s*(/?\s*\d+%)?(/\s*\d+\.\d\s*)?)\) A: Another version to support rgb and rgba separately , with not strict spaces and allowing pattern rgba(255,255,255, .5) (rgb\((((25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*?,\s*?){2}(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*?)?\))|(rgba\(((25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*?,\s*?){2}(25[0-5]|2[0-4]\d|1\d{1,2}|\d\d?)\s*?,\s*(0?\.\d*|0(\.\d*)?|1)?\)) A: You can use that: 100% of capturing rgba or rgb color code ^(rgba(\((\s+)?(([0-9])|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-5]))(\s+)?,(\s+)?(([0-9])|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-5]))(\s+)?,(\s+)?(([0-9])|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-5]))(\s+)?,(\s+)?((0|(0.[0-9][0-9]?)|1)|(1?[0-9][0-9]?\%))(\s+)?\)))|rgb(\((\s+)?(([0-9])|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-5]))(\s+)?,(\s+)?(([0-9])|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-5]))(\s+)?,(\s+)?(([0-9])|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-5]))(\s+)?\))$
{ "language": "en", "url": "https://stackoverflow.com/questions/7543818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Replace multiple occurrences of a string with different values I have a script that generates content containing certain tokens, and I need to replace each occurrence of a token, with different content resulting from a separate loop. It's simple to use str_replace to replace all occurrences of the token with the same content, but I need to replace each occurrence with the next result of the loop. I did see this answer: Search and replace multiple values with multiple/different values in PHP5? however it is working from pre-defined arrays, which I don't have. Sample content: This is an example of %%token%% that might contain multiple instances of a particular %%token%%, that need to each be replaced with a different piece of %%token%% generated elsewhere. I need to replace each occurrence of %%token%% with content generated, for argument's sake, by this simple loop: for($i=0;$i<3;$i++){ $token = rand(100,10000); } So replace each %%token%% with a different random number value $token. Is this something simple that I'm just not seeing? Thanks! A: I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself. It looks to me like this problem works well with explode(). So, using the example token generator you provided, the solution looks like this: $shrapnel = explode('%%token%%', $str); $newStr = ''; for ($i = 0; $i < count($shrapnel); ++$i) { // The last piece of the string has no token after it, so we special-case it if ($i == count($shrapnel) - 1) $newStr .= $shrapnel[$i]; else $newStr .= $shrapnel[$i] . rand(100,10000); } A: I know this is an old thread, but I stumbled across it while trying to achieve something similar. If anyone else sees this, I think this is a little nicer: Create some sample text: $text="This is an example of %%token%% that might contain multiple instances of a particular %%token%%, that need to each be replaced with a different piece of %%token%% generated elsewhere."; Find the search string with regex: $new_text = preg_replace_callback("|%%token%%|", "_rand_preg_call", $text); Define a callback function to change the matches function _rand_preg_call($matches){ return rand(100,10000); } Echo the results: echo $new_text; So as a function set: function _preg_replace_rand($text,$pattern){ return preg_replace_callback("|$pattern|", "_rand_preg_call", $text); } function _rand_preg_call($matches){ return rand(100,10000); } A: I had a similar issue where I had a file that I needed to read. It had multiple occurrences of a token, and I needed to replace each occurrence with a different value from an array. This function will replace each occurrence of the "token"/"needle" found in the "haystack" and will replace it with a value from an indexed array. function mostr_replace($needle, $haystack, $replacementArray, $needle_position = 0, $offset = 0) { $counter = 0; while (substr_count($haystack, $needle)) { $needle_position = strpos($haystack, $needle, $offset); if ($needle_position + strlen($needle) > strlen($haystack)) { break; } $haystack = substr_replace($haystack, $replacementArray[$counter], $needle_position, strlen($needle)); $offset = $needle_position + strlen($needle); $counter++; } return $haystack; } By the way, 'mostr_replace' is short for "Multiple Occurrence String Replace". A: You can use the following code: $content = "This is an example of %%token%% that might contain multiple instances of a particular %%token%%, that need to each be replaced with a different piece of %%token%% generated elsewhere."; while (true) { $needle = "%%token%%"; $pos = strpos($content, $needle); $token = rand(100, 10000); if ($pos === false) { break; } else { $content = substr($content, 0, $pos).$token.substr($content, $pos + strlen($token) + 1); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to remove a specific parameter from the URL in PHP? Example: $url = http://example.com/?arg=val&arg2=test&arv3=testing&arv2=val2 remove_url_arg($url, "arg2") echo($url); // http://example.com/?arg=val&arv3=testing The above remove_url_arg() function removes all occurrence of arg2 argument from the URL A: unset($_GET['arg2']); $query_string = http_build_query($_GET); if it's not on request but to parse whole url $parsed = parse_url($url); $qs_arr = parse_str($parsed['query'],1); unset($qs_arr['arg2']); $parsed['query'] = http_build_query($qs_arr); and then assemble the url back. or one-liner regexp
{ "language": "en", "url": "https://stackoverflow.com/questions/7543826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails testing has_many association failure I have 2 models. A User and a Task. Here's the code for them both: class User < ActiveRecord::Base has_many :tasks has_many :assigned_tasks, :class_name => 'Task', :foreign_key => 'assigned_user_id' end class Task < ActiveRecord::Base belongs_to :user belongs_to :assigned_user, :class_name => 'User', :foreign_key => 'assigned_user_id' end The schema is quite obvious, but for consistency, this is how it looks: ActiveRecord::Schema.define(:version => 20110925050945) do create_table "tasks", :force => true do |t| t.string "name" t.integer "user_id" t.integer "assigned_user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "users", :force => true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end end I've added a test case for the assigned_tasks relationship. It looks like this: class UserTest < ActiveSupport::TestCase test "assigned tasks" do u1 = User.create(:name => 'john') u2 = User.create(:name => 'dave') assert_empty u2.assigned_tasks # LOOK AT ME task = u1.tasks.create(:name => 'some task', :assigned_user_id => u2.id) assert_equal 1, u2.assigned_tasks.size end end Now, this test case fails. It fails on the last assertion. If I remove the previous assertion (marked 'LOOK AT ME'), this test passes fine. It also passes fine if I change this line to assert u2.assigned_tasks. Meaning it appears to break when, and only when, empty? is called against u2.assigned_tasks. Where that assertion passes, the following one fails. Here's the failure: UserTest: FAIL assigned tasks (0.12s) <1> expected but was <0>. test/unit/user_test.rb:12:in `block in <class:UserTest>' So, it appears once empty? is called on the original u2.assigned_tasks Array, the task is not actually added/associated with it's assigned user. This however appears to work fine in console. Apologies if I'm completely overlooking something simple here, but I really can't make any sense of this. Any points in the right direction would be extremely helpful. Thanks PS: Rails 3.1 with a vanilla application A: You need to reload the assigned_tasks, or u2. # This line causes assigned_tasks to be loaded and cached on u2. Not the calling # of empty?, but rather the loading of the association. assert_empty u2.assigned_tasks # but then you actually make the task here task = u1.tasks.create(:name => 'some task', :assigned_user_id => u2.id) # so when this assertion happens, u2 already has an empty set of tasks cached, # and fails assert_equal 1, u2.assigned_tasks.size # however either of these should pass assert_equal 1, u2.assigned_tasks(true).size assert_equal 1, u2.reload.assigned_tasks.size The inverse_of option serves to improve in-memory association behavior, and might also solve your problem (without reloading). Read about that here. It would look something like this (but again I'm not positive it will work in this case): # on User has_many :assigned_tasks, ..., :inverse_of => :assigned_user # on Task belongs_to :assigned_user, ..., :inverse_of => :assigned_tasks # in your test you might have to change the task creation to: u1.tasks.create(:name => 'some task', :assigned_user => u2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with Google Calendar API Java Library I try to use Google Calendar API Java library, and copy this code from example: CalendarService myService = new CalendarService("abc"); try { myService.setUserCredentials("авaea@gmail.com", "1111223"); } catch (AuthenticationException e) { // TODO Auto-generated catch block } I downloaded library from source: gdata-client-1.0, gdata-calendar-2.0, but I got errors: Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/Maps at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118) at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100) at com.google.gdata.client.Service.<clinit>(Service.java:555) at Test.main(Test.java:29) Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 4 more Where can I do mistake? A: Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps The mentioned class is not found in the runtime classpath. The mentioned class is part of Guava. So, if you download and put it in the runtime classpath as well, then this error should disappear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Configure android EditText to allow decimals and negatives I have an Android EditText that I want to have the number keyboard come up. If I set the android:inputType to numberSigned, I get the number keyboard and the ability to type in negatives. However this won't let me use decimals. If I use the numberDecimal inputType I can use decimals but not negatives. How do you get the number keyboard with the ability to type in decimals and negatives? A: See this link may be it's help you http://developer.android.com/resources/articles/creating-input-method.html and The possible values for the android:inputtype are: •none •text •textCapCharacters •textCapWords •textCapSentences •textAutoCorrect •textAutoComplete •textMultiLine •textImeMultiLine •textNoSuggestions •textUri •textEmailAddress •textEmailSubject •textShortMessage •textLongMessage •textPersonName •textPostalAddress •textPassword •textVisiblePassword •textWebEditText •textFilter •textPhonetic •textWebEmailAddress •textWebPassword •number •numberSigned •numberDecimal •numberPassword •phone •datetime •date •time A: Some phones have the decimal and negative in the same button and makes it unable to do negatives. I figured out a way you could separate the buttons by simply adding- android:inputType="numberDecimal|numberSigned|textPersonName" android:digits="0123456789-." That way you still have the number keyboard layout but the negative and decimal buttons will be separate and you cannot use any other digit that messes up the app. A: We can use, edit_text.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED); if we need to use programmatically.. A: You are just missing this in your EditText, android:inputType="numberDecimal|numberSigned" A: Tested, solution is inputET.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED); A: This worked for me programmatically.Below is the code : editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
{ "language": "en", "url": "https://stackoverflow.com/questions/7543835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: difference between ++i and i++ in for loop I understand well how postfix and prefix increments/decrements work. But my question is, in a for loop, which is more efficient or faster, and which is more commonly used and why? Prefix? for(i = 0; i < 3; ++i) {...} Or postfix? for(i = 0; i < 3; i++) {...} A: For ints in this context there is no difference -- the compiler will emit the same code under most optimization levels (I'd venture to say even in the case of no optimization). In other contexts, like with C++ class instances, there is some difference. A: Either works, and one is not more efficient or faster than the other in this case. It's common for people to use ++1, maybe because that is what was used in K&R and other influential books. A: In this particular case, none is actually more efficient than the other. I would expect ++i to be more commonly used, because that's what would be more efficient for other kinds of iterations, like iterator objects. A: In my opinion, choosing prefix or postfix in a for loop depends on the language itself. In c++ prefix is more efficient and consistent. Because in the prefix type, compiler does not need to copy of unincremented value. Besides your value must not be an integer, if your value is an object than this prefix type is more powerful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AntiForgeryToken HtmlHelper throwing NotImplementedException when run within a RazorGenerator class I'm using RazorGenerator to unit test my Razor/MVC3 per David Ebbo's post here http://blog.davidebbo.com/2011/06/unit-test-your-mvc-views-using-razor.html and every time I attempt to use the AntiForgeryToken HtmlHelper (with no method arguments), it throws a NotImplementedException. What gives? As best I can tell, both my cshtml file and the view.generated.cs the correct method in System.Web.Mvc.dll, in the System.Web.Mvc namespace's HtmlHelper class. I've downloaded the latest source for the RazorGenerator project and don't see the word "forgery" contained within it anywhere, so I don't think I'm getting confused about exactly which HtmlHelper.AntiForgeryToken() method I'm hitting. The code sample of my unit test follows: [Test] public void Index_RendersView() { var view = new Index(); // For test to succeed, this should not throw exception view.RenderAsHtml(); } Pretty basic. I'll spend some time digging under the hood to figure this one out and will follow up here if I figure this one out, but in the meantime I'm wondering if anyone else has encountered this and already worked out a solution. A: I corresponded with David Ebbe, one of the (or, the) project owners on CodePlex, and he altered something within the RazorGenerator project source to fix this. Remarkably, he had it fixed within less than 1/2 hour of me asking the question on the CodePlex board. I'm going to vote to have this question deleted since I don't think there's any value to keeping it around this site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove additional padding from a WPF TextBlock? By default a WPF TextBlock seems to have additional top and bottom padding applied. I wish this wasn't so. * *I've tried setting negative padding, but got an exception: 0,-10,0,0' is not a valid value for property 'Padding'. *I've tried setting the LineHeight property, to no apparent effect. This is how the TextBlock looks in Blend. I've marked the problematic portion with maroon red. A: This space is not padding, but part of the font, reserved for accents above and below characters. The accepted answer makes the line height smaller than the font height. A: Some research and H.B. guided me to the right answer, which is setting the following properties: <TextBlock LineStackingStrategy="BlockLineHeight" LineHeight="20"/> <!-- Or some other value you fancy. --> A: This is probably part of the font which is Segoe UI by default, try Segoe instead for example. (You cannot assign negative padding but you could assign negative Margins, e.g.: Margin="0,-3,0,0")
{ "language": "en", "url": "https://stackoverflow.com/questions/7543846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Automatically check for valid HTML on each request I am cleaning up my website and i would like to see html errors and warnings on each page automatically. I use to use Html Validator for firefox (addon) but it doesnt appear to validate automatically anymore. I don't know if its because of the addon version or the fact i use firefox 4. I need to check every page request until i get through the entire site w/o errors. What addon/tool might i use? A: Try this tool Specify your web-site address and enable "Validate entire site" checkbox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cant connect/send from hMailServer I have recently setup hMailServer. I have a domain on godaddy so I am using the MX record given by godaddy. For this example, I am going to say that I am using mail.hmailserver.net as the MX Record. I have added the username and password under SETTINGS > Protocols > SMTP on hMailServer Administrator, and so I have the following configured. I have added an "inbound" firewall rule that opens up Port 25 to make sure that the port is not being blocked. I can ping my MX record and it will resolve the IP fine, but yet if I try to use the following telnet command, I am unable to connect telnet mail.hmailserver.net 25 It tells me it is unable to connect. Initially I was using a simple client application to test this, and I believed it might have been in my code that was causing the problem, but now I am thinking I have something configured incorrectly. public static void Main(string[] args) { MailMessage message = new MailMessage(); message.From = new MailAddress("fromemail@email.com"); message.To.Add("toEmail@email.com"); message.Subject = "Test Subject"; message.Body = "Test Body"; SmtpClient client = new SmtpClient(); client.Host = "mail.hmailserver.net"; client.Port = 25; NetworkCredential login = new NetworkCredential("Administrator", "Password"); client.Credentials = login; try { client.Send(message); } catch (Exception exception) { Console.WriteLine(exception.Message); } } Any ideas if I am doing it incorrectly from the screenshot above? Eventually this will be sending emails from a hosted application in IIS, I am not sure if that makes a difference. Please Help. A: Maybe your provider has blocked outbound traffic to other SMTP servers than the server of your provider? Find your providers SMTP server address and test it with that address.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Weird problems with CSS position:absolute I am having some really weird problems with position:absolute. I have set the main title of my webpage to be position absolute, but when I resize the window, the text moves around. The really weird thing is that the tagline (the Bible verse) is also position:absolute, but it isn't having any problems. Any suggestions? A: I'm guessing your screen resolution is 1920x1080? Looks like you've gone and positioned the element relative to the window, which only works if the window is that size. Try removing the position: absolute and the right properties, and using float:right instead of float:left. As for the tagline element, you made it position: relative and float: right. position: relative, here, does absolutely nothing. A: I suggest adding the position: relative to the #logoWrapper: #logoWrapper { ... position: relative; ... } Thus its children with position: absolute will be positioned relatively to the #logoWrapper, not the body, as Kolink said.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Real Time issues: Oracle Performance tuning (types / indexes / plsql / queries) I am looking for a real time solution... Below are my DB columns. I am using Oracle10g. Please help me in defining table types / indexes and tuned PLSQL / query (both) for the updates and insertion Insert and Update queries are simple but here we need to take care of the performance because my system will execute such 200 times per second. Let me know... should I use procedures or simple queries? It is requested to write tuned plsql and query with proper DB table types / indexes. I would really like to see the performance of my system after continuous 200 updates per second DB table (columns) (I can change the structure if required so please let me know...) Play ID - ID Type - Song or Message Count - Summation of total play Retries - Summation of total play, if failed. Duration - Total Duration Last Updated - Late Updated Date Time Thanks in advance ... let me know in case of any confusion... A: You've not really given a lot of detail about WHAT you are updating etc. As a basis for you to write your update statements, don't use PL/SQL unless you cannot achieve what you want to do in SQL as the context switching alone will hurt your performance before you even get round to processing any records. If you are able to create indexes specifically for the update then index the columns that will appear in your update statement's WHERE clause so the records can be found quickly before being updated. As for inserting, look up the benefits of the /*+ append */ hint for inserting records to see if it will benefit your particular case. Finally, the table structure you will use will depend on may factors that you haven't even begun to touch on with the details you've supplied, I suggest you either do some research on DB structure or ask your DBA's for a 101 class in it. Best of luck... EDIT: In response to: Play ID - ID ( here id would be song name like abc.wav something..so may be VARCHAR2, yet not decided..whats your openion...is that fine if primary key is of type VARCHAR2....any suggesstions are most welcome...... ) Type - Song or Message ( varchar2) Count - Summation of total play ( Integer) Retries - Summation of total play, if failed. ( Integer) Duration - Total Duration ( Integer) Last Updated - Late Updated Date Time ( DateTime ) There is nothing wrong with having a PRIMARY KEY as a VARCHAR2 data type (though there is often debate about the value of having a non-specific PK, i.e. a sequence). You must, however, ensure your PK is unique, if you can't guarentee this then it would be worth having a sequence as your PK over having to introduce another columnn to maintain uniqueness. As for declaring your table columns as INTEGER, they eventually will be resolved to NUMBER anyway so I'd just create the table column as a number (unless you have a very specific reason for creating them as INTEGER). Finally, the DATETIME column, you only need decare it as a DATE datatype unless you need real precision in your time portion, in which case declare it as a TIMESTAMP datatype. As for helping you with the structure of the table itself (i.e. which columns you want etc.) then that is not something I can help you with as I know nothing of your reporting requirements, application requirements or audit requirements, company best practice, naming conventions etc. I'm afraid that is something for you to decide for yourself. For performance though, keep indexes to a minumum (i.e. only index columns that will aid your UPDATE WHERE clause search), only update the minimum data possible and, as suggested before, research the APPEND hint for inserts it may help in your case but you will have to test it for yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: in javascript, call each function in array with a callback using forEach? An array of functions, [fn1,fn2,...], each "returns" through a callback, passing an optional error. If an error is returned through the callback, then subsequent functions in the array should not be called. // one example function function fn1( callback ) { <process> if( error ) callback( errMsg ); else callback(); return; } // go through each function until fn returns error through callback [fn1,fn2,fn3,...].forEach( function(fn){ <how to do this?> } ); This can be solved other ways, but nonetheless would love the syntactic dexterity to use approach. Can this be done? as per correct answer: [fn1,fn2,fn3,...].every( function(fn) { var err; fn.call( this, function(ferr) { err = ferr; } ); if( err ) { nonblockAlert( err ); return false; } return true; } ); seems this has room for simplification. for me, much better approach to solve this type of problem - it's flatter, the logic more accessible. A: If I understand your question correctly and if you can use JavaScript 1.6 (e.g. this is for NodeJS), then you could use the every function. From MDN: every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method immediately returns false. Otherwise, if callback returned a true value for all elements, every will return true. So, something like: [fn1, fn2, fn3, ...].every(function(fn) { // process if (error) return false; return true; }); Again, this requires JavaScript 1.6
{ "language": "en", "url": "https://stackoverflow.com/questions/7543858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Model validation. Don't want to repeat myself. Django I have a model M that has a field num=models.IntegerField() I have a modelform called F for model M. I want to ensure that num is never negative. If I do validation in my form class, F, then I can do clean_num(): if negative then throw ValidationError('Num can never be negative'). This ValidationError will be automatically redisplayed to the user by redirecting him to back to the form that he submitted and displaying the 'Num can never be negative' message on top of the num field. Thats all done automatically by django as soon as I throw the ValidationError from the clean_fieldname method. I would like to be able to do all that, but in the model class. F is the ModelForm created from a model class M. M defines that the field num can never be negative. When I'm calling is_valid() on a form, I want the functions defined in the model to check for validation for any ModelForm that references this model. How can I achieve this? A: See Model validation (Django 1.2+ only). A: You could also use PositiveIntegerField for this particular problem. If your validation depends only on field value, you can implement your own field type as described here: https://docs.djangoproject.com/en/dev/howto/custom-model-fields/ A: Thanks to everyone who posted an answer. But i found exactly what i asked about so if you're interested: You can define the proper validators just once for the model. All the forms using this model will have the ValidationError('cant use this name') be appended to their field_name.errors list. Note, that they will be added to the field in the form for which the model field validator is running. Anyway, check this out: Django: how to cleanup form fields and avoid code duplication
{ "language": "en", "url": "https://stackoverflow.com/questions/7543862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: which operator overloading has been used for ifstream object to evalute to boolean I am new to C++. recently I come across the following code ifstream in("somefile"); if(in){ //read the file.... } I am wondering which operator overloading the ifstream might have used for the in object to automatically evaluate to boolean in if condition. I tried but couldnt find a clue. please help me. thank in advance A: It's actually operator void *. It's overridden to return a non-zero pointer if the stream is valid, and a NULL pointer otherwise. The pointer it returns is meaningless and should not be dereferenced, it's only there to be evaluated in a boolean context. A: The void pointer conversion operator is often used for this purpose. Something similar to struct ifstream { typedef void * voidptr; operator voidptr() const; }; A: std::ifstream gets its conversion to bool from it's base class std::ios (std::basic_ios<char>) which has conversion function declared: explicit operator bool() const; It returns !fail(). (In the previous version of the standard ISO/IEC 14882:2003, std::basic_ios had a conversion function operator void*() const but this version of the standard has now been withdrawn.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MPI Irecv cannot receive correctly to the first element of a buffer? I've just been experimenting with MPI, and copied and ran this code, taken from the second code example at [the LLNL MPI tutorial][1]. #include <mpi.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char ** argv) { int num_tasks, rank, next, prev, buf[2], tag1 = 1, tag2 = 2; MPI_Request reqs[4]; MPI_Status status[2]; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_tasks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); prev = rank - 1; next = rank + 1; if (rank == 0) prev = num_tasks - 1; if (rank == (num_tasks - 1)) next = 0; MPI_Irecv(&buf[0], 1, MPI_INT, prev, tag1, MPI_COMM_WORLD, &reqs[0]); MPI_Irecv(&buf[1], 1, MPI_INT, next, tag2, MPI_COMM_WORLD, &reqs[1]); MPI_Isend(&rank, 1, MPI_INT, prev, tag2, MPI_COMM_WORLD, &reqs[2]); MPI_Isend(&rank, 1, MPI_INT, next, tag1, MPI_COMM_WORLD, &reqs[3]); MPI_Waitall(4, reqs, status); printf("Task %d received %d from %d and %d from %d\n", rank, buf[0], prev, buf[1], next); MPI_Finalize(); return EXIT_SUCCESS; } I would have expected an output like this (for, say, 4 tasks): $ mpiexec -n 4 ./m3 Task 0 received 3 from 3 and 1 from 1 Task 1 received 0 from 0 and 2 from 2 Task 2 received 1 from 1 and 3 from 3 Task 3 received 2 from 2 and 0 from 0 However, instead, I get this: $ mpiexec -n 4 ./m3 Task 0 received 0 from 3 and 1 from 1 Task 1 received 0 from 0 and 2 from 2 Task 3 received 0 from 2 and 0 from 0 Task 2 received 0 from 1 and 3 from 3 That is, the message (with tag == 1) going into buffer buf[0] always gets value 0. Moreover, if I alter the code so that I declare the buffer as buf[3] rather than buf[2], and replace each instance of buf[0] with buf[2], then I get precisely the output I would have expected (i.e., the first output set given above). This looks as if, for some reason, something is overwriting the value in buf[0] with 0. But I can't see what that might be. BTW, as far as I can tell, my code (without the modification) exactly matches the code inthe tutorial, except for my printf. Thanks! A: Array of statuses must be of size 4 not 2. In your case MPI_Waitall corrupts memory when writing statuses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VB.net Populate TreeView with DataSet using Parent-Child Relations I'm working on a program that allows me to edit XML data in a DataGridView. I have most everything working but I don't like my current TreeView Structure. I load the XML data into a DataSet and edit it there, so that is what I'd prefer to base my TreeView on. I've tried a few things such as.. Private Sub updateTree() 'Clear All Previous TreeView Nodes TreeView1.Nodes.Clear() 'Loop Through XML Nodes and Add them to the Tree For Each table As DataTable In ds.Tables Dim node As New TreeNode(table.TableName) If table.ChildRelations.Count = 0 Then node.Text = table.TableName node.Tag = table.TableName TreeView1.Nodes.Add(node) Else node.Tag = table.TableName node.Text = table.TableName & " - No Child Objects" TreeView1.Nodes.Add(node) End If Next End Sub What I'd really like to have is a tree view that shows the Parent Child objects nested. I'm not sure exactly how to accomplish that in this case... Any ideas?? I found this, article, but don't have many more leads... Adding Nested Treeview Nodes in VB.NET? Thanks. A: I found a way to problematically accomplish what I was trying to do. I figured that because the DataSet includes the parent child relationships, I could use those to build my treeview. A DataSet includes two Properties, parent relations and child relations. I the count on those to determine where they were at in the relationship tree. Using an if statement, I first Populate the Parent Node, because the top Parent has no Parent. Then I check to see if there is a child to the parent, and populate those, lastly, I use a counter to populate the grandchild node. 'Sub for calling a treeview update when needed Private Sub updateTree() 'Clear All Previous TreeView Nodes TreeView1.Nodes.Clear() 'Loop Through the database examining the Parent child relationship and Add the nodes to the Tree Dim i As Integer = 0 For Each table As DataTable In ds.Tables Dim node As New TreeNode(table.TableName) If table.ParentRelations.Count = 0 Then node.Text = table.TableName & " -Parent" node.Tag = table.TableName TreeView1.Nodes.Add(node) ElseIf table.ParentRelations.Count = 1 And table.ChildRelations.Count = 1 Then node.Tag = table.TableName node.Text = table.TableName & "-Child" TreeView1.Nodes(0).Nodes.Add(node) ElseIf table.ChildRelations.Count = 0 And table.ParentRelations.Count = 1 Then node.Tag = table.TableName node.Text = table.TableName & "-Grandchild" TreeView1.Nodes(0).Nodes(i).Nodes.Add(node) i += 1 End If Next As always, if anyone has a better idea, I'm all ears:) Thanks....
{ "language": "en", "url": "https://stackoverflow.com/questions/7543873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do ajax requests works if JavaScript is disabled in the browser? I am developing a web application and am using jQuery to provide a good user interface for users. Therefore, I am using ajax requests and many jQuery functions. If I disable JavaScript in the browser most of the function will not work because I am sending asynchronous ajax requests for many functions. But how can I handle this? Do I need to rewrite the code without using jQuery and ajax? Find a below a sample button click event: $("#renameCategory").live('click', function (event) { if ($.trim($("#CategoryNewName").val()) == "") { alert("Please enter a category name"); return; } var selectedCategory = $("#SelectedCategoryId").val(); var newCategoryName = $("#CategoryNewName").val(); var postData = { categoryId: selectedCategory, name: newCategoryName }; $.ajax({ type: "POST", url: '@Url.Action("UpdateCategoryName", "Category")', data: postData, dataType: "json", success: function (data) { $('#' + selectedCategory).text(newCategoryName); $("#selectedCategoryText").html(newCategoryName); }, error: function () { alert('error') } }); }); How can I handle this? A: Ajax call works when javascript is enabled. You can handle it by server-side scripting, when javascript is disabled, you must do works by post/get requests, so you have to recode your web application. A: If a lot of modification is needed for your website to work without javascript, then just force the users to enable javascript. One way to notify users to enable javascript is to use the noscript tag. http://www.w3schools.com/tags/tag_noscript.asp View stackoverflow's page source to see how they use noscript A: If JavaScript is disabled in the browser, the <script> tags won't be interpreted and executed in your document, including all your jQuery and AJAX JS code. The most common way to implement interactive web application other than Javascript is Flash, so you can still have a backup plan. You can also go with the old-school server side only generated dynamic pages. Today, however it is very rare for someone not to have JavaScript enabled, so it should not be an issue at all. Anyway you can make use of the <noscript> html tag to display a message to these users. <script type="text/javascript"> ... Js code ... </script> <noscript>You have JavaScript disabled in your browser. Please enable it.</noscript> A: Obviously any functionality depending on script will not work if scripting is disabled, not available or incompatible with the environment it is trying to run in. It is considered by many to be a good strategy to develop web applications so that they work without script support. You can then add scripting to improve the workflow and efficiency, but you will do so knowing that you have a fall back to a working system available if at any point the script should not run. The discipline of designing and implementing a good workflow based on just HTML and forms may well lead to an easier interface to script and a more efficient workflow. All too often developers throw together some minimal HTML and CSS, then try and do everything in script. The extreme is to have a DOCTYPE, title element, one block element and one script element that does everything. Not recommended. A: Ajax requests and jQuery will not work when the client has JavaScript disabled. The best way to make this work is to use the URL from the <a> tag href like so: <a href="@Url.Action("UpdateCategoryName", "Category")">Click Me!</a> $("#renameCategory").on('click', function (evt) { //To prevent the link from sending the default request //call preventDefault() on the jQuery event object evt.preventDefault(); // if ($.trim($("#CategoryNewName").val()) == "") { alert("Please enter a category name"); return; } //GET THE URL FOR THE AJAX REQUEST var actionUrl = $(this).attr('href'); // var selectedCategory = $("#SelectedCategoryId").val(); var newCategoryName = $("#CategoryNewName").val(); var postData = { categoryId: selectedCategory, name: newCategoryName }; $.ajax({ type: "POST", url: actionUrl, data: postData, dataType: "json", success: function (data) { $('#' + selectedCategory).text(newCategoryName); $("#selectedCategoryText").html(newCategoryName); }, error: function () { alert('error') } }); }); You will also need to check for ajax requests in your Controller like below: public ActionResult UpdateCategoryName() { ... if(Request.IsAjaxRequest()) { return Json(yourData); } return View(); } This way, if your user has JavaScript disabled, the link will function like a normal HTTP request. If the user has JavaScript enabled, then they will get the Ajax experience. This is called graceful degradation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: issue with changing UIButton background image I have the following code which basically just initialize a UIButton. self.button = [[UIButton alloc] init]; self.button.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin; self.button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height); [self.voteSpot setBackgroundImage:buttonImage forState:UIControlStateNormal]; [self.voteSpot setBackgroundImage:[UIImage imageNamed:@"MainButton-Selected.png"] forState:UIControlStateSelected]; [self.button addTarget:self action:@selector(button) forControlEvents:UIControlEventTouchUpInside]; CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height; if (heightDifference < 0) self.button.center = self.tabBar.center; else { CGPoint center = self.tabBar.center; center.y = center.y - heightDifference/2.0; self.button.center = center; } [self.view addSubview:self.button]; When I press on the button I want the button background to be changed, so in the target I have the following: - (void) button { [self setSelectedViewController:[self.viewControllers objectAtIndex:1]]; [self setTabBarWithImage:[UIImage imageNamed:@"Map-Profile.png"]]; } The issue is that when the app first initially loads, I have to press the button twice to make the background change.. why is this? the first time I tap the button this doesn't change the button background image. Any idea? A: I'm not sure what the problem is, but I'd start by creating the button using +buttonWithType instead of +alloc and -init. The buttonType property is read only, and initializing the button with -init doesn't let you set the type. A: You should set the highlighted/selected backgrounds before the user can tap the button. In other words, move the first two lines from the action method to where you create the button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IIS CPU goes bezerk after updating web.config in a C# application with a Singleton with a thread I have a web application that does the following: You click a button to instantiate a singleton, which creates a Thread. That Thread runs continuously doing some HTTP requests to gather some data. You can click a stop button that calls the Abort() method on the thread and the application stops making HTTP requests. When I start/stop it manually, everything works fine. My problem occurs when ever I "touch" web.config. The CPU (w3wp.exe process) spikes and the website stops responding. Does anybody know why this is happening? Shouldn't an update to web.config reset everything? Sample code is below: private static MyProcessor mp = null; private Thread theThread = null; private string status = STOP; public static string STOP = "Stopped"; public static string START = "Started"; private MyProcessor() {} public static MyProcessor getInstance() { if (mp == null) { mp = new MyProcessor(); } return mp; } public void Start() { if (this.status == START) return; this.theThread = new Thread(new ThreadStart(this.StartThread)); this.theThread.Start(); this.status = START; } public void Stop() { if (this.theThread != null) this.theThread.Abort(); this.status = STOP; } private void StartThread() { do { try { //do some work with HTTP requests Thread.Sleep(1000 * 2); } catch (Exception e) { //retry - work forever this.StartThread(); } } while (this.status == START); } A: I suspect this is the problem: private void StartThread() { do { try { //do some work with HTTP requests Thread.Sleep(1000 * 2); } catch (Exception e) { //The recursive call here is suspect //at the very least find a way to prevent infinite recursion //--or rethink this strategy this.StartThread(); } } while (this.status == START); } When your app domain resets, you'll get a ThreadAbort exception which will be caught here and trigger a recursive call, which will hit another exception, and another recursive call. It's turtles all the way down! A: Yes, making any change in web .config resets the application, and asp.net re-build the application. Same is true for some other files like files under Bin and App_Code folders.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I view the response data from the server using TTURLRequest? Is there an easy way to dump the response data from a TTURLRequest? I'm getting a server side error and I'd like to be able to quickly log the response in the console without having to tail the server logs. I'm using Three20's TTURLRequest in conjunction with TTURLJSONResponse, and so far I haven't been able to view that data easily unless the response is a JSON string. Any suggestions? Thanks! A: Try to print the NSERROR NSData *returnData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
{ "language": "en", "url": "https://stackoverflow.com/questions/7543890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doubly-linked list infinite loop? If I were to create a node class, as shown below, and if it were used in a doubly-linked list, would it create an infinite loop upon deconstruction of the doubly linked list? Or would it terminate nicely? class Node { Node( ); ~Node( ) { delete mNext; //deallocs next node } Contact mContact; Node* mPrevious; Node* mNext; }; Edit: If I modified the code to this would it work? ~Node( ) { mPrevious = NULL; if (mNext->mPrevious != NULL) { delete mNext; //deallocs next node } } Edit 2: Or would this work best? ~Node( ) { if (mPrevious != NULL) { mPrevious = NULL; delete mNext; //deallocs next node } } A: If considering the mNext pointer the nodes are forming a loop then then destruction of any of the nodes will indeed probably form an infinite recursive loop and it will terminate the program by blowing up the stack. What it will probably happen is * *The first "external" delete node; is issued. *When entering the node destructor nothing has been done yet as the code destructor is the "first" thing performed in the destruction process (the destruction process itself is quite involved and includes destructor code, class change, member destruction, base destruction in this order: see this answer for a more detailed explanation). *The first destructor instruction fill execute delete mNext; thus triggering the same process on next node in the loop. *Because the nodes are forming a loop this chain will reach node again "from the back" thus making the very first call a recursion that would never end. *Every call none the less will allocate stack space for the activation record, therefore after a while all the memory allowed to be used for the stack will be depleted and the OS will kill the process. The deletion call is not a "tail call" because after the destructor code completes the memory must be deallocated so this recursion cannot easily be optimized away... while delete mNext; is the last statement on the destructor still there are operations that must be performed after the delete operator completes. Note however that in my experience a stack overflow unless you use special compiler options is not going to be checked and the program termination will therefore be quite "abnormal". Note also that under Windows there is some horrible code that in some cases hides segfault errors if they happen on program termination, so it's well possible that a windows program could just apparently terminate gracefully in this operaton is done after quitting the event loop. Give that stack overlflow is not normally considered indeed any behavior is possible, including an apparent "infinite loop" (note that this infinite loop may be not the one of the recursive destructor but somewhere inside the runtime system getting crazy because of the stack overflow). Why did I use the word probably? The reason is that the C++ standard says that multiple destruction of an object is Undefined Behavior. If you add this to the fact that there is no way in C++ to quit a destructor without completing the destruction you will understand that a compiler is in theory allowed to flag an object as "being destroyed" and to make a daemon fly out of your nosrils if you enter the destructor of the same object twice. Checking for this error is not mandatory however and compiler writers are often lazy (this is NOT an insult for a programmer) and therefore is unlikely that this check will be present (except may be if some special extra debugging option is enabled). To sum it up: can it loop forever? yes. Can it crash? sure. Can it stop telling me that an object is being destroyed twice? of course. Can it just terminate the program nicely (i.e. witout setting any error code)? yes, that too. Anything can happen. And Murphy says it will happen whatever is going to do the most damage to you... for example the program will terminate nicely every single time while you are developing it... and it will crash badly in you face during the demo day in front of a thousand prospective customers. Just don't do that :-) A: There is no way for it to know when to stop, so it probably will run infinitely. You should probably write a List class, which has a pointer to a (or an actual) Node. Node's d'tor should only take care of its own fields, in this case mContact. List's d'tor should iterate over all nodes in the list (remembering when to stop), and delete each one (exactly once). A: Assuming you initialize mNext to null, it will not run infinitely. Delete will do nothing when it encounters a null pointer. Thus it would end exactly when you expect it to. I'm not sure what you are doing with the "if previous" options. Those won't work. Either this will be a valid node and thus have a previous node or it will not be a valid node and checking previous will have undefined results. Stick with the simple answer: class Node { Node( mNext = NULL; ); ~Node( ) { delete mNext; //deallocs next node } Contact mContact; Node* mPrevious; Node* mNext; }; Clarification: This solution works, but only if two conditions are met: 1) There are no nodes appearing in the list twice. 2) The list is not circular. If you can guarantee those conditions, this is your simplest answer. If you cannot, you need to do something more complex. A: Personally, I think it's a bit odd that a Node's destructor should have anything to do with other nodes. If the design was up to me, I would create a List class that contains a pointer to Node objects (first and last). The destructor of the List class would take care of iterating through all the nodes in the list and destroying them. A: This is actually simple . Assumptions 1)Its a doubly link list and not a circular one 2)No Loops in the link list: this is a double link list 3)The implementation class has only one instance of Node Probably called HeadNode or LinkList ;) and this is the node that is destroyed explicitly Example : LinkList are 1->2->3->4->5->6->NULL The distructor call for HeadNode(reffer 3rd assumption) will cause a recurssive call as follows: delete(1)->delete(2)->delete(3)->delete(4)->delete(5)->delete(6)->NULL So Please chech if (mNext != NULL) delete mNext and it works :) But:If you want to delete a node specifically : Say we want to delete only 4 in above example ,all the nodes will be deleted till NULL so before deleation please ensure you set the Mnext to NULL. The best practice would be to use the STL library or otherwise use autopointer class for the destruction part of the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7543891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Displaying retrieved value in excel file into ALV Good Day Everyone, There is this something i've been trying to exercise in abap and that is the Displaying of column datas in ALV by retrieving the values from excel file into an internal table. I've been trying to debug my program for quite some time now and i can't seem to solve the error it's been stating which is "Field symbol has not yet been assigned" please guide me. I already made some research on how to solve this short dump error but most of the other issues posted on the net is selected from some specific table with column fields. I was just wondering that maybe my case is a little bit different from others. The function that retrieved the values from excel is properly working and i have no problem at all in displaying them.Below is the code i constructed. TYPE-POOLS: truxs, slis. TYPES: BEGIN OF t_itab, col1 TYPE char20, col2 TYPE char20, col3 TYPE char20, col4 TYPE char20, col5 TYPE char20, END OF t_itab, t_it_itab type STANDARD TABLE OF t_itab. Data: gt_tab TYPE t_it_itab, wa_tab TYPE t_itab, g_numrows TYPE i. PARAMETERS: p_fname TYPE c LENGTH 50. INITIALIZATION. AT SELECTION-SCREEN OUTPUT. AT SELECTION-SCREEN. AT SELECTION-SCREEN on VALUE-REQUEST FOR p_fname. DATA: l_filename LIKE IBIPPARMS-PATH. CALL FUNCTION 'F4_FILENAME' EXPORTING PROGRAM_NAME = SYST-CPROG DYNPRO_NUMBER = '1000' IMPORTING FILE_NAME = l_filename . p_fname = l_filename. START-OF-SELECTION. DATA: lc_fname TYPE RLGRAP-FILENAME, lt_tab TYPE TRUXS_T_TEXT_DATA. lc_fname = p_fname. CALL FUNCTION 'TEXT_CONVERT_XLS_TO_SAP' EXPORTING I_TAB_RAW_DATA = lt_tab I_FILENAME = lc_fname TABLES I_TAB_CONVERTED_DATA = gt_tab EXCEPTIONS CONVERSION_FAILED = 1 OTHERS = 2 . IF SY-SUBRC <> 0. WRITE 'Error'. * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO * WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4. ENDIF. " Delete First Row / HEADER DELETE gt_tab INDEX 1. IF gt_tab[] is INITIAL. MESSAGE 'No Record(s) found' TYPE 'I'. EXIT. ELSE. PERFORM DisplayALv. ENDIF. FORM DISPLAYALV. DATA: l_it_fcat type SLIS_T_FIELDCAT_ALV, l_wa_fcat TYPE SLIS_FIELDCAT_ALV. l_wa_fcat-fieldname = 'col1'. l_wa_fcat-ref_tabname = 'gt_tab'. l_wa_fcat-reptext_ddic = 'Column 1'. l_wa_fcat-outputlen = '30'. APPEND l_wa_fcat TO l_it_fcat. CLEAR l_wa_fcat. CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY' EXPORTING I_CALLBACK_PROGRAM = sy-repid IT_FIELDCAT = l_it_fcat I_DEFAULT = 'X' I_SAVE = 'A' TABLES T_OUTTAB = gt_tab[]. IF SY-SUBRC <> 0. WRITE: 'SY-SUBRC: ', SY-SUBRC . ENDIF. ENDFORM. Any tips, tricks and advice in my program would be highly sought. Thanks in Advance A: You're using a type which is not defined in the data dictionary. This requires a different approach when creating the ALV fieldcat. Try this: l_wa_fcat-fieldname = 'COL1'. l_wa_fcat-inttype = 'C'. l_wa_fcat-outputlen = '30'. l_wa_fcat-text_fieldname = 'Column 1'. l_wa_fcat-seltext_s = 'Column 1'. Also make sure you enter the fieldname value with capitalized letters. A: I'm no ABAP expert but I noticed 2 things in the code you posted: * *you said the error is "Field symbol has not yet been assigned" but you have no field symbol in your code. Maybe it's used inside one of the function modules you call. If so, try to post the code where the error pops up; *you use gt_tab[] which, if I remember well, is the way to access the body of an internal table with header line. In your code gt_tab is not an internal table with header line, but you use it to store one with function 'TEXT_CONVERT_XLS_TO_SAP' ; Try to post the code where the error is being generated. Regards, Sergiu
{ "language": "en", "url": "https://stackoverflow.com/questions/7543894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: mysql error in retrieving data I have data in my webpage that is coming from MySQL. Its a field that is initially zero and increases in value as the users visits more pages, it counts them and writes the tracked value to a cell on the pages. But the problem is it works fine for few weeks then suddenly it again starts from zero. Can somebody tell me what should I do? My MySQL column definition is: column name page_view type INT Length/values 255 Default None
{ "language": "en", "url": "https://stackoverflow.com/questions/7543895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse : Importing Existing Projects into workspace We have a Existing project downloaded from server which was build on Maven . (this is in the form of Folder Structure ) While import that project in Eclipse , should i use Existing Projects into workspace Or File System Please guide me Thank you . A: If you import a project into the workspace the files remain in their original locations. I do not know how to avoid this. Often (always) I would like to have a copy of the files in the workspace and leave the project I imported it from in its original location untouched. A frequent use-case is that I have a project and wish to make some changes to it to test out something without affecting the main project. Thanks John A: If you really have an existing project, then you must have a .project file. Check for that, and if you do have, you should use the Existing Projects into workspace option, and select the root folder of your project. Since you have a Maven project, you could also import it as Existing Maven Projects, given that you have the Maven plugin installed in your eclipse. A: File -> Import... -> General -> Existing Project into Workspace -> Select the archive file by clicking Browse button -> Select the checkbox * Copy projects into workspace. (this answers user462990's question). This way the project is copied into the workspace and the main project is not affected. If you use "File -> Import... -> Maven -> Existing Maven Projects" you don't get the option to copy projects into workspace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inserting into table using Python and MySQLdb I am using Python and MySQLdb, I have a table which is displayed below but I get error message each time I try to insert into the table. INSERT INTO reviews (entry,created_time, user_id, branch_id, title)VALUES('branches that would lead use to the ciyrt', '2011-09-20 00:24:24',1, ,1, 'oogletivers') CREATE TABLE reviews ( id int(9) unsigned not null primary key auto_increment, entry text not null , created_time timestamp not null, user_id tinyint unsigned not null references users(id), branch_id tinyint unsigned not null references branches( id), title varchar(255), FULLTEXT(title, entry) ) mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1, 'oogletivers')' at line 1") A: You have two commas without anything between them. Remove one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I specify an action's default model I want to make an action's model to be the current user's if not specified. How to do that? For example, I have an profile action in user controller. If the url is like /user/profile/3 , It will show profile of user whose id is 3 and if the url is like /user/profile it will show the current user's. public function actionProfile($id){ $model=$this->loadModel($id); $this->render('profile',array( 'model'=>$model )); } A: If I understand the question, you are talking about default scopes. In the model: public function defaultScope () { if (Yii::app ()->user->id) { return array ( 'condition' => 'user_id=' . Yii::app ()->user->id, ); } else { // or whatever return array (); } } Then any query in your controller will use that as a condition. A: How about something like this: public function actionProfile($id=null) { $id=($id===null?Yii::app()->user->id:$id); $model=$this->loadModel($id); ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Add other object and receive error MultiValueDictKeyError (Django admin) I have a relationship follow as: class Question(models.Model): qid = models.PositiveIntegerField(primary_key=True) content = models.CharField(max_length=128) class Answer(models.Model): answerid = models.PositiveIntegerField(primary_key=True) content = models.CharField(max_length=128) question = models.ForeignKey(Question) class AnswerInline(admin.StackedInline): model = Answer readonly_fields = ('answerid',) extra = 0 class QuestionAdmin(admin.ModelAdmin): inlines = [AnswerInline] exclude = ('id') list_display = ('content',) admin.site.register(Question,QuestionAdmin) Suppose I have a question namely A and I haven't any answer for this question yet. So, when I add an answer of A. It's ok. However, I try to add an other answer, system output an error MultiValueDictKeyError: "Key 'oam_answer_set-0-answerid' not found in QueryDict:... Because both of 'qid' and 'answerid' are not an AutoField. So, when I save an object, django admin can not insert a new row into database (missing primary key). The AutoField is declared an IntegerField. However, I would like the field type of primary key is PositiveIntegerField. For that reason, how can I customize an AutoField? Thanks A: Try registering the Answer model with the admin i.e. ... admin.site.register(Answer) at the bottom of the admin.py. You are using fields on the inline (specifically readonly_fields) that are inherited from ModelAdmin, but you might not have registered that model.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .goutputstream-XXXXX - possible to relocate? I've been trying to create a union file system for a college project. One of its features that differentiates it from unionfs is the fact that there are no copy-ups. This means that if a file is located in a certain branch, it will remain there even if it is written to. But my current problem with that is the fact that .goutputstream-XXXXX are created, renamed, and deleted whenever a write operation occurs. This is actually OK if the file being written to is in the highest priority branch (i.e. the default branch where files can be created), but makes my kernel crash if I try to write to a file in a lower branch. How do I deal with this? How can I rig it so that all .goutputstream-XXXXX files are written to only one location? These .goutputstream-XXXXX files seem to be intricately connected to the files they correspond too, and seem to work only the same directory as the file being written to. I also noticed that .goutputstream-XXXXX files appear when a directory is read. What are they for, anyway? A: There has been a bug submitted to the ubuntu launchpad in which the creation of .goutputstream-xxxxx files is discussed. https://bugs.launchpad.net/ubuntu/+source/lightdm/+bug/984785 From what i see now, these files are created when shutting down without preceding logout, but several other sources may occur, like evince or maybe gedit. maybe lightdm has something to do with the creation of these files. which distribution did you use? maybe changing the distribution would help. A: .goutputstream-XXXXX created by gedit and there is no simple way (menu or settings) to relocate them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XML - Need to add more child node with a loop <field name="dob_day" type="list" default="select" description="COM_USERS_REGISTER_DOB_DAY_DESC" filter="string" label="COM_USERS_REGISTER_DOB_DAY_LABEL" message="COM_USERS_REGISTER_DOB_DAY_MESSAGE" required="true" > <option value="select">Day</option> <option value="1">1</option> ....... ....... </field> This is the xml in joomla user registration.xml I want to add days in a loop or something like: for(i=1; i<=31;<i++): <option value="i">i</option> endfor How can I do this in XML? A: Why are you trying to use a loop for this. You can simply write these options manually. Besides you can not use any language in xml files. If you wanted simple way for drop-down select with specific range of numbers there is a special Joomla field called "integer" <field name="dob_day" type="integer" default="0" label="COM_USERS_REGISTER_DOB_DAY_LABEL" description="COM_USERS_REGISTER_DOB_DAY_DESC" message="COM_USERS_REGISTER_DOB_DAY_MESSAGE" first="0" last="31" step="1" required="true" /> A: If you want to extend a form in Joomla 1.6/1.7, your best bet is to use a plugin and attach yourself to the onFormPrepare event, which gives you the possibility to extend the form and especially overwrite existing elements with your own with additional options, etc. Look at the Joomla profile plugin, which does just that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you select all rows which match one individual row in either of a thousand columns? For example, my personality match database has 1000 columns, with genre titles such as: autoid | movie_genre_comedy | movie_genre_action | movie_genre_horror | more genres --> 23432 | 1 | 0 | 1 | 0 3241 | 0 | 1 | 1 | 0 64323 | 0 | 1 | 0 | 0 How do I match every row to the row with autoid 23432 so that the following table is produced: autoid | movie_genre_comedy | movie_genre_action | movie_genre_horror | more genres --> 23432 | 1 | 0 | 1 | 0 3241 | 0 | 1 | 1 | Note that the row with autoid 64323 is not there because it does not have any similar columns to the chosen row with autoid 23432. The simplest way to do this is: SELECT * from genretable WHERE movie_genre_comedy = 1 OR movie_genre_horror = 1 OR ........... and so on for up to 1000 parameters. A: The code you mentioned in your question is really the only way to do what you want with your current table structure. The answer is to create two new tables to map users to personality traits, like so: create table `personality_trait_values` ( `id` smallint auto_increment primary key ,`value` varchar(20) not null unique ); create table `personality_traits` ( `user_id` int not null references `users` (`autoid`) ,`personality_trait_id` int not null references `personality_trait_values` (`id`) ,unique (`user_id`,`personality_trait_id`) ); With that, you can nuke the 1000 columns that describe whether the user has a personality trait or not, and your query becomes much more compact: select u.`autoid` from `personality_traits` pt1 join `personality_traits` pt2 on pt1.`personality_trait_id` = pt2.`personality_trait_id` and pt1.`user_id` != pt2.`user_id` where pt1.`user_id` = `v_user_id_to_compare_to` Where v_user_id_to_compare_to is a variable you have set previously in your stored procedure (to 23432, in the case of your question). Converting the table structure you have now will be a bit tedious, but well worth it, and a lot of the tedium can be relieved by judicious use of copy/paste.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what's the fastest way to tell whether we're on a weekday in a particular hour range? I am using PHP/MySQLin my project, and I have a table that holds time values, and days of week. The rows are SUNDAY_OPEN SUNDAY_CLOSE etc. for the rest of the week. These hold times like 9:00 and 17:00. All I want to do is on a certain time of access, to know whether the NOW() or time() in PHP fall exactly on that time range. A: How about something like: $day_of_week = strtoupper(date("l")); $current_hour = date("G:i"); $sql = " SELECT COUNT(*) AS `open` FROM `schedule` WHERE '{$current_hour}' BETWEEN `{$day_of_week}_OPEN` AND `{$day_of_week}_CLOSE`";
{ "language": "en", "url": "https://stackoverflow.com/questions/7543919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When to use Navigator or Package Explorer view? I have imported an existing project built using Maven into my Eclipse workspace. Should we use Navigator or Package Explorer to view our projects in Eclipse? A: The Navigator is more of a hierarchical file explorer, to explore all artifacts within the project, while the Package Explorer provides a Java package view. So, when you are looking to view/edit code, you would rather use the Package Explorer, while use the Navigator when browsing project artifacts. A: Try both and look at the differences. You'll notice that the Navigator is presented like as a disk file system folder structure (like Windows Explorer) and that the Package Explorer groups the Java classes in packages instead of a bunch of folder trees. Which one to choose is purely a matter of taste and usefulness of the view. When developing in Java, the Package Explorer is more handy. When just scanning for loose files, the Navigator may be more handy. Each has also its own (configureable) set of filters to hide certain types of files. You'll by default not see .class files in Package Explorer, but you can see them in Navigator (in the /bin folder).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Silverlight/Windows Phone ViewModel updating question I have a XAML page whose DataContext is set to my ViewModel. A switch control on the page is bound to the following code in the ViewModel: public bool TeamLiveTileEnabled { get { return Data.Subscriptions.Any(s => s.TeamName == this.Team.Name); } } When this page is initialized, Data.Subscriptions is an empty list. I retrieve the list of subscriptions through an async web service call, so it comes back after the getter above is called. When the web service call comes back, Data.Subscriptions has items added to it, and I'd like the UI to update based on the new result of the LINQ expression. Right now nothing happens, and I confirmed that Data.Subscriptions contains items that satisfy the condition above. Data.Subscriptions is an ObservableCollection of Subscription items. Can someone point me to what to do? Thanks! A: The problem is that your ViewModel is not aware of any changes to the ObservableCollection. Within the ViewModel, subscribe to the CollectionChanged event of Data.Subscriptions. Data.Subscriptions.CollectionChanged += SubscriptionsChangedHandler; Within the event handler notify listeners of TeamLiveTileEnabled by sending a PropertyChanged notification NotifyPropertyChanged( "TeamLiveTileEnabled" );
{ "language": "en", "url": "https://stackoverflow.com/questions/7543921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery: having radio buttons and a textarea update hidden form fields Really new to using jQuery and trying to find an example I need. 1) if I have, say, 5 radio buttons to choose an item, how do I pass the selected item to a hidden form field? 2) same question for a textarea. How do I pass the text written to a hidden form field and make sure it's escaped safely for a form submission? Thanks for any help. A: You can just bind to the change event: <input type="hidden" id="myradiovalue" /> <input type="radio" name="myradio" value="0" /> <input type="radio" name="myradio" value="1" /> $('input[name=myradio]').change(function() { $('#myradiovalue').val($(this).val()); }); And almost the same for textarea: <input type="hidden" id="mytextarevalue" /> <textarea id="mytextareavalue"></textarea> $('textarea').change(function() { $('#mytextareavalue').val($(this).val()); }); A: For both <input type="radio"> and <textarea>, you will want to use jQuery change() method. If you want to sanitize the input before it is inserted into a <input type="hidden"> then you will need to use some regex or a library that does it for you, like jQuery Validation Plugin. Keep in mind that any sanitation/validation you do with javascript/jQuery will need to be double-checked server-side after the form is submitted. But I don't know why you are copying data from one form input to another, can't you just use the form input as it is? What is the point of having the data in both a <textarea> and a <input type="hidden">?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading image from cache using BitmapFactory.decodeStream() in Android UPDATES: Even if i don't retrieve images from cache, i tried to retrieve via Drawable where i stored all the 18 images in the "drawable-mdpi" folder. Still, a blank screen was display. I was able to retrieved images from the server and save the image (.GIF) into the cache. However, when i need to load that image from cache, the image doesn't show up on screen. Here is the codes that does the work: File cacheDir = context.getCacheDir(); File cacheMap = new File(cacheDir, smallMapImageNames.get(i).toString()); if(cacheMap.exists()){ FileInputStream fis = null; try { fis = new FileInputStream(cacheMap); Bitmap local = BitmapFactory.decodeStream(fis); puzzle.add(local); } catch (FileNotFoundException e) { e.printStackTrace(); } }else{ Drawable smallMap = LoadImageFromWebOperations(mapPiecesURL.get(i).toString()); if(i==0){ height1 = smallMap.getIntrinsicHeight(); width1 = smallMap.getIntrinsicWidth(); } if (smallMap instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable)smallMap).getBitmap(); FileOutputStream fos = null; try { cacheMap.createNewFile(); fos = new FileOutputStream(cacheMap); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } puzzle.add(bitmap); } } ArrayList to store the image names: smallMapImageNames (The image names can also be found in the URL) ArrayList to store the URL of the images: mapPiecesURL To sum it up i have 2 questions 1) how to load images from cache? 2) regarding the bitmap.compress(), the images from the server is .GIF format but i apply Bitmap.CompressFormat.PNG. So is there going to be any problem with this? Can anyone please help me with this? The two functions private Bitmap getBitMap(Context context) { // TODO Auto-generated method stub WifiPositioningServices wifiPositioningServices = new WifiPositioningServices(); String[] mapURLandCalibratedPoint1 = wifiPositioningServices.GetMapURLandCalibratedPoint("ERLab-1_1.GIF","ERLab"); //list of map pieces url in the first 9 pieces String[] mapURLandCalibratedPoint2 = wifiPositioningServices.GetMapURLandCalibratedPoint("ERLab-4_1.GIF","ERLab"); //list of map pieces url in the last 9 pieces ArrayList<String> smallMapImageNames = new ArrayList<String>(); ArrayList<String> mapPiecesURL = new ArrayList<String>(); for(int i=0; i<mapURLandCalibratedPoint1.length; i++){ if(mapURLandCalibratedPoint1[i].length()>40){ //image url int len = mapURLandCalibratedPoint1[i].length(); int subStrLen = len-13; smallMapImageNames.add(mapURLandCalibratedPoint1[i].substring(subStrLen, len-3)+"JPEG"); mapPiecesURL.add(mapURLandCalibratedPoint1[i]); } else{ //perform other task } } for(int i=0; i<mapURLandCalibratedPoint2.length; i++){ if(mapURLandCalibratedPoint2[i].length()>40){ //image url int len = mapURLandCalibratedPoint2[i].length(); int subStrLen = len-13; smallMapImageNames.add(mapURLandCalibratedPoint2[i].substring(subStrLen, len-3)+"JPEG"); mapPiecesURL.add(mapURLandCalibratedPoint2[i]); } else{ //perform other task } } Bitmap result = Bitmap.createBitmap(1029, 617, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(result); ArrayList<Bitmap> puzzle = new ArrayList<Bitmap>(); int height1 = 0 ; int width1 = 0; File cacheDir = context.getCacheDir(); for(int i=0; i<18; i++){ File cacheMap = new File(cacheDir, smallMapImageNames.get(i).toString()); if(cacheMap.exists()){ //retrieved from cached try { FileInputStream fis = new FileInputStream(cacheMap); Bitmap bitmap = BitmapFactory.decodeStream(fis); puzzle.add(bitmap); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ //retrieve from server and cached it Drawable smallMap = LoadImageFromWebOperations(mapPiecesURL.get(i).toString()); if(i==0){ height1 = smallMap.getIntrinsicHeight(); width1 = smallMap.getIntrinsicWidth(); } if (smallMap instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable)smallMap).getBitmap(); FileOutputStream fos = null; try { cacheMap.createNewFile(); fos = new FileOutputStream(cacheMap); bitmap.compress(CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } puzzle.add(bitmap); } } } Rect srcRect; Rect dstRect; int cnt =0; for (int j = 0; j < 3; j++) { int newHeight = height1 * (j % 3); for (int k = 0; k < 3; k++) { if (j == 0 && k == 0) { srcRect = new Rect(0, 0, width1, height1); dstRect = new Rect(srcRect); } else { int newWidth = width1 * k; srcRect = new Rect(0, 0, width1, height1); dstRect = new Rect(srcRect); dstRect.offset(newWidth, newHeight); } canvas.drawBitmap(puzzle.get(cnt), srcRect, dstRect,null); cnt++; } } for(int a=0; a<3; a++){ int newHeight = height1 * (a % 3); for (int k = 3; k < 6; k++) { if (a == 0 && k == 0) { srcRect = new Rect(0, 0, width1*3, height1); dstRect = new Rect(srcRect); } else { int newWidth = width1 * k; srcRect = new Rect(0, 0, width1, height1); dstRect = new Rect(srcRect); dstRect.offset(newWidth, newHeight); } canvas.drawBitmap(puzzle.get(cnt), srcRect, dstRect, null); cnt++; } } return result; } private Drawable LoadImageFromWebOperations(String url) { // TODO Auto-generated method stub try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src name"); return d; }catch (Exception e) { System.out.println("Exc="+e); return null; } } I am actually trying to display 18 pieces (3X6) of images to form up a floorplan. So to display the images, i use two for-loop to display it. the two .GIF images, ERLab-1_1.GIF and ERLab-4_1.GIF are the center piece of each group. For example, the first row of would be ERLab-0_0.GIF, ERLab-1_0.GIF, ERLab-2_0.GIF, ERLab-3_0.GIF, ERLab-4_0.GIF, ERLab-5_0.GIF. Second row would be XXX-X_1.GIF and XXX-X_2.GIF for the third row. Lastly, Bitmap resultMap = getBitMap(this.getContext()); bmLargeImage = Bitmap.createBitmap(1029 , 617, Bitmap.Config.ARGB_8888); bmLargeImage = resultMap; Then in the onDraw function would be drawing the image onto the canvas. A: I just solved my own question. In this line, canvas.drawBitmap(puzzle.get(cnt), srcRect, dstRect,null); within each of the for-loop which i am using it to draw the bitmap onto the canvas, i need to cast the each item in the ArrayList (puzzle) to Bitmap. Only then will the image get display. I thought that if the ArrayList is definite as such, ArrayList<Bitmap> puzzle = new ArrayList<Bitmap>(); each items in the ArrayList would be of Bitmap type. But isn't that always true?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I initialize an array in MIPS? In my previous question, I inquired about converting the MAX_ARRAY() function into MIPS. I have completed that task. Now, I wish to initialize an array in my program. How might I achieve this? addi $t1,$zero, 0 # initialize index i to 0 loop: add $t1,$t1,1 # increment index i by 1 beq $t1,$s2,done # if all elements examined, quit add $t2,$t1,$t1 # compute 2i in $t2 add $t2,$t2,$t2 # compute 4i in $t2 add $t2,$t2,$s1 # form address of A[i] in $t2 lw $t3,0($t2) # load value of A[i] into $t3 slt $t4,$t0,$t3 # maximum < A[i]? beq $t4,$zero,loop # if not, repeat with no change addi $t0,$t3,0 # if so, A[i] is the new maximum j loop # change completed; now repeat done: A: http://pages.cs.wisc.edu/~cs354-2/onyourown/arrays.html Hope this helps you... Wasn't able to find more appropriate answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7543929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "error A2006: undefined symbol" in masm32 in window 7 64 bit? When i run this example, I get an error. After removing PROC1 PROC FAR, I get another error "symbol type conflict". With /coff: "leading underscore required for start address : START". Microsoft (R) Macro Assembler Version 6.14.8444 Copyright (C) Microsoft Corp 1981-1997. All rights reserved. Assembling: D:\Linux\test1.asm D:\Linux\test1.asm(28) : error A2006: undefined symbol : START D:\Linux\test1.asm(16) : error A2004: symbol type conflict D:\Linux\test1.asm(28) : error A2148: invalid symbol type in expression : STAR TITLE EXAMPLE DATA SEGMENT VARX DW 6 VARY DW 7 RESULT DW ? DATA ENDS STACK1 SEGMENT PARA STACK DW 20H DUP(0) STACK1 ENDS COSEG SEGMENT PROC1 PROC FAR ASSUME CS:COSEG, DS:DATA, SS:STACK1 START: PUSH DS MOV AX, 0 PUSH AX MOV AX, DATA MOV DS, AX MOV DX, VARX MOV DX, VARY MOV CL, 3 SAL DX, CL SUB DX, VARX SAR DX, 1 MOV RESULT, DX RET PROC1 ENDP COSEG ENDS END START Addendum: After removing start, it left error at line 16. Why happens this error at MOV AX, DATA? Microsoft (R) Macro Assembler Version 6.14.8444 Copyright (C) Microsoft Corp 1981-1997. All rights reserved. Assembling: D:\Linux\test1.asm D:\Linux\test1.asm(16) : error A2004: symbol type conflict A: Because START is defined inside a procedure, it is not a valid identifier outside it. Also, if it did work you would be creating a bug. PROC is a macro that expands to setup a stack frame, so your label START is not actually at the start of the code, while END START indicates that the entry point for your program is START. If you want your program to start with a main procedure you should just use the name of that procedure after END, like END PROC1. If it really was your intent to set the entry point to somewhere in your procedure, you could surround the label with OPTION NOSCOPED and OPTION SCOPED, so the label will be public, and not just visible inside the procedure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Layout form fields without tables I have a very simple HTML layout I'm trying to implement. It is something like this: A Label: [Input ] Another Label: [Input ] The Last Label: [Input ] In the past, I'd just go ahead and use a table for this. Otherwise, it's a pain getting the input controls to line up correctly. Can anyone suggest a simple and reliable way to implement this layout without using a table? Thanks. A: You can use display: inline-block <style type="text/css"> label { display: inline-block; width: 200px; } ul { list-style: none; } </style> <ul> <li><label for="input1">A Label:</label> <input type="text" name="input1" id="input1"></li> <li><label for="input2">Another Label:</label> <input type="text" name="input2" id="input2"></li> <li><label for="input3">The Last Label:</label> <input type="text" name="input3" id="input3"></li> </ul> However, in order for this to line up vertically, you either have to wrap the label-input pairs in another tag (such as <li> or <div>) or put linebreaks after the inputs. A: <style> label { width: 200px; float:left; clear:left; } input { float:left;} </style> <form> <label for="fullname">Full Name:</label> <input type="text" name="fullname" id="fullname"> <label for="email">Email Address:</label> <input type="text" name="email" id="email"> </form> With the added benefit that, if the horizontal space isn't sufficient, the inputs will wrap below the labels. http://jsbin.com/anuziq (narrow down your browser window) If you don't actually want them to wrap around, I suggest this approach: <style> label { white-space: nowrap; } span { width: 200px; display: inline-block; } </style> <form> <label> <span>Full Name:</span> <input type="text" name="fullname"> </label> <label> <span>Email Address:</span> <input type="text" name="email"> </label> </form> From my experience, structuring the HTML like that usually allows for any layout you can possibly think of. Want the inputs always below the label? Use display:block on the span elements. Want the text to the right of the input? Just use float:right on the span. Bonus here is that you don't need the for and id attributes to connect the label with the input. They're only really necessary, if you can't put the label right next to the input, like in 2 separate table cells.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the Pythonic way to merge 2 lists of tuples and add the nonunique values in the tuples? I am looking for the best way to refactor the Python code below. I think there is a Pythonic way to do this in 2 or 3 lines of code, but couldn't figure it out. I have searched Stackoverflow but couldn't find similar problems and solutions. Many thanks! list1 = [(Python, 5), (Ruby, 10), (Java, 15), (C++, 20)] list2 = [(Python, 1), (Ruby, 2), (Java, 3), (PHP, 4), (Javascript, 5)] # I want to make an unsorted list3 like this # list3 = [(Python, 6), (Ruby, 12), (Java, 18), (PHP, 4), (Javasript, 5), (C++, 20)] common_keys = list(set(dict(list1).keys()) & set(dict(list2).keys())) if common_keys: common_lst = [(x, (dict(list1)[x] + dict(list2)[x])) for x in common_keys] rest_list1 = [(x, dict(list1)[x]) for x in dict(list1).keys() if x not in common_keys] rest_list2 = [(x, dict(list2)[x]) for x in dict(list2).keys() if x not in common_keys] list3 = common_lst + rest_list1 + rest_list2 else: list3 = list1 + list2 A: You're looking for collections.defaultdict: from collections import defaultdict from itertools import chain merged = defaultdict(int) for key, value in chain(list1, list2): merged[key] += value If you want a list of tuples: list3 = merged.items() If you want to do it without chain, you can do it as: from collections import defaultdict merged = defaultdict(int) merged.update(list1) for key, value in list2: merged[key] += value Edit: As Beni points out in a comment, on 2.7/3.2+, you can do: from collections import Counter merged = Counter(dict(list1)) merged.update(dict(list2)) Which requires you convert the lists to dicts but is otherwise perfect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating random Unicode between certain range I am trying to generate random Unicode characters with two starting number+letter combination.. I have tried the following below but I am getting an error. def rand_unicode(): b = ['03','20'] l = ''.join([random.choice('ABCDEF0123456789') for x in xrange(2)]) return unicode(u'\u'+random.choice(b)+l,'utf8') The error I am getting: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence I use Python 2.6. A: Yeah, uh, that's not how. return unichr(random.choice((0x300, 0x2000)) + random.randint(0, 0xff))
{ "language": "en", "url": "https://stackoverflow.com/questions/7543945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to compare to datatable with different columns I have the EMP datatable it contains 500 records like this: UserAceNumber UserID emp001 emp002 emp003 emp004 (userid will be empty for all the 500 records) Another Empdetails datatable contains some records which I will keep UserID in this table like this: UserAceNumber UserID emp002 user002 emp004 user004 I need the result in the EMP table like this: UserAceNumber UserID emp001 emp002 user002 emp003 emp004 user004 In this both table common value is UserAceNumber I cant use any SQL queries because these datatables are coming from webservices and also the LINQ because I am using 2005 How to do this? I have done merge but but I need the columns as if in EMP datatable. A: You can use the Datatable.Select query to achieve this the output will be a datarow. var dataRow=dataTable.Select(string.Format("{0}='{1}'", primaryKeyColumnName, valueOfPrimaryKey)); For more infor about the API look here Basically what you do is loop over one of the datatables identify the primary key column in this datatable use that to find a corresponding row in the second datatable
{ "language": "en", "url": "https://stackoverflow.com/questions/7543947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RESTKIT internal mapping fails if json value == NULL I am using RESTKIT to map the properties from the server side to the properties in the client side. I am hitting the [NSNull unsignedIntValue] error when RESTKIT is trying to map a NULL value from the server to a NSUInteger property on the client side. For example: //User object property "new_questions_count" defined on client side with NSUInteger property @interface User : NSObject <NSCoding> { NSUInteger new_questions_count; } @property (nonatomic, assign) NSUInteger new_questions_count; @end //User Object Mapping - mapping "new_question_count" to server's json value RKObjectMapping* userMapping = [RKObjectMapping mappingForClass:[User class]]; [userMapping mapAttributes:@"new_question_count",nil]; [provider setMapping:userMapping forKeyPath:@"user"]; For the above scenario, I will hit the [NSNull unsignedIntValue] error if the json value is "new_questions_count":null. How can I do a check on the client side and resolve this without having to change the implementation on the server side? A: Although you have not showed the code where you actually decode the JSON, I am assuming that you are using a third party library that correctly respects the NSNull class. In this case, you can check if the object for key @"x" is null using this: if ([[dictionary objectForKey:@"x"] isKindOfClass:[NSNull class]]) { // it is NULL } else { // it is not NULL, but it still might // not be in the dictionary at all. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP---if(!session_is_registered deprecated? This if statement has been deprecated if(!session_is_registered('firstname')){ header("location: index.php"); // << makes the script send them to any page we set } else { print "<h2>Could not log you out, sorry the system encountered an error.</h2>"; exit(); } I replaced it with if ( isset( $_SESSION['firstname'] ) ){ header("location: index.php"); // << makes the script send them to any page we set } else { print "<h2>Could not log you out, sorry the system encountered an error.</h2>"; exit(); the initial code is attached to my logout.php script. When i then go to the link logout.php, this is displayed "Could not log you out, sorry the system encountered an error." Is that the right solution since i had no problem with the code A: Based on your first snippet, I think you are failing in logic. Try: if ( !isset($_SESSION['firstname']) ){ header("location: index.php"); // << makes the script send them to any page we set } else { exit('<h2>Could not log you out, sorry the system encountered an error.</h2>'); } A: Do you have session_start(); on your page? http://php.net/manual/en/function.session-start.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7543953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use from one short key on active tab? I have a window that has some tabs,in each tab i can create a new item. I want define a short key for create new item.But i want my short Key work on active tab. For example, when Tab1 was active my short key work on create item in Tab1 or when Tab2 was active my short key work on create item in Tab2. How can i use from one short key on active tab? A: There are many ways to accomplish this. The most common is to use a command. First, here's the XAML I used: <Grid> <TabControl Grid.Row="0" x:Name="AppTabs"> <TabItem Header="Tab 1"> <ListBox x:Name="TabOneList" /> </TabItem> <TabItem Header="Tab 2"> <ListBox x:Name="TabTwoList" /> </TabItem> </TabControl> </Grid> Here's the code-behind: private void Window_Loaded(object sender, RoutedEventArgs e) { // create the new item command and set it to the shortcut Ctrl + N var newItemCommand = new RoutedUICommand("New Item", "Makes a new item on the current tab", typeof(MainWindow)); newItemCommand.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Control, "Ctrl + N")); // create the command binding and add it to the CommandBindings collection var newItemCommandBinding = new CommandBinding(newItemCommand); newItemCommandBinding.Executed += new ExecutedRoutedEventHandler(newItemCommandBinding_Executed); CommandBindings.Add(newItemCommandBinding); } private void newItemCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { // one way to get the ListBox control from the currently selected tab ListBox itemList = null; if (AppTabs.SelectedIndex == 0) itemList = this.TabOneList; else if (AppTabs.SelectedIndex == 1) itemList = this.TabTwoList; if (itemList == null) return; itemList.Items.Add("New Item"); } I wouldn't consider this production code, but hopefully it points you in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: form post in Chrome extension popup not doing anything I am making a chrome extension and I have a popup.html page that contains a form with method post, it does not do anything when opened using the popup button however if the page is opened as an options page or just a normal html page, the form posts fine and the new page is loaded. so something in the popup is preventing the form from working. I cannot figure out why, anyone know how to fix/work around this ? A: You need to do an AJAX POST request. A quick Google search brought up this post. A: Maybe an answer duplicate of Paypal Button For Google Chrome Extension. Just in case that somebody arrives here, try adding a simple target="_blank" to your tag (Works with Paypal donate buttons, for example)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Drawing formatted text I set up a draw rectangle to draw simple formatted text first aligned to the left as *item 1 [1]Something content [2]Something else <a> subsomething else content <b> another subsomething else content *item 2 The end. and I would also like it to automatically create a new column (after checking for the longest string in the first column [drawn stuff on the left hand side]) to draw the rest into it. In order to keep track of the paddings and itemized sections and subsections, I think of using a stack which I can push and pop the current and next positions needed to draw a text line each time I leave a content. Yet, I can't figure out how to jump back to a certain subsection position because stack doesn't offer an inline sub-scripting method. Then I look into a hash-map (in C# I have tried Dictionary) to keep track of it and to access the value via specific key. For that I also use a external global variable to maintain the number of subsections the user may have entered and increase one each time a new subsection is created; and the float value is used to store the x-coordinate value for the drawstring to be done. This is complicated to me at least at present when I don't really have a nerve to go into it anymore. I can only receive false simulated outcomes. So I am asking for an easier approach to tackle this problem, which I think is simple to many of you sure experiencing the same situation. I am desperately looking forward to seeing a short easy method to do this. A: Draw formatted text using .. ..whatever works. I suggest a JLabel, which will render (simple) HTML/CSS formatted content. See LabelRenderTest.java for an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simple hierarchical listing in PyQT I'm trying to create a UI with 3 columns - when you select an item in the left column, the select item is passed to a function, and it returns the items for the middle column (and of course same for selecting items in the middle column) Should be simple, but I can't find any easy way to do this.. I first tried QColumnView, as it seemed perfect.. however implementing the QAbstractItemModel seems excessively complicated, and I couldn't find any useful examples of this. Next, since there is a fixed number of levels, I made three QListView, and modified this example QAbstractListModel ..however there seemed to be no useful signal I could use to trigger the updating of the other levels of the hierarchy. According to the PyQT docs, QListView only has the "indexesMoved" signal. There is also "clicked" and "pressed", however these didn't trigger when changing items with the keyboard The last options is QListWidget, which would work as it has the required signals (itemChanged etc), but the way list items are created is a bit tedious (making QListWidgetItem with the parent set to the QListWidget instance) Edit: QListWidget does pretty much what I need: self.first_column = QListWidget() self.first_column.itemSelectionChanged.connect(self.update_second_column) A: Any QAbastractItemView has a QItemSelectionModel accessible via the selectionModel method. The QItemSelectionModel has signals that may help you: currentChanged ( const QModelIndex & current, const QModelIndex & previous ) currentColumnChanged ( const QModelIndex & current, const QModelIndex & previous ) currentRowChanged ( const QModelIndex & current, const QModelIndex & previous ) selectionChanged ( const QItemSelection & selected, const QItemSelection & deselected ) Hope it helps. A: QListView inherits from QAbstractItemView (I think you knew this), so it gets a few signals, hopefully one (or a few) of them works for you. This is working for me (connect signals when initializing your QMainWindow or main QWidget, as in the SaltyCrane example): connect(your_list_view, SIGNAL("clicked(const QModelIndex&)"), handler_slot) ... def handler_slot(idx): #idx is a QModelIndex #QModelIndex.data() returns a QVariant, Qt4's generic data container celldata = idx.data() #Choose the proper datatype to ask the QVariant for (e.g. QVariant.toInt()) actualvalue = celldata.toInt() #QVariant.toInt() happens to return a tuple print actualvalue[0] Depending on the type of data in your model, you'll want to choose the right data type to ask QVariant for. The sneaky part here is getting the QListView to tell you which cell was clicked (i.e. using clicked(const QModelIndex&) vs clicked()). I think I spent some time looking at the C++ documentation for Qt4 before I realized you could get more out of the signals. From here, I would have the handler_slot() call a setData() method on the model for your second QListView (using data generated by the function you originally planned to use). I'd be glad to elaborate if I haven't quite answered your question. Edit: Working with arrow keys Hmm, it seems weird that there isn't a default QListView signal for arrow movement, but we can make our own. (This almost seems out-of-style for Qt4's signals and slots modus operandi) QListView reimplements a method keyPressEvent(self, QKeyEvent) which acts as a callback function when certain keys are pressed. You can read more. We can use this to grab the keyevent(s) that we want, and emit our own signal. class ArrowableListView(QListView): def keyPressEvent(self, keyevent): #Maintain original functionality by calling QListView's version QListView.keyPressEvent(self, keyevent) #QListView.selectedIndexes returns a list of selected cells, I'm just taking the first one here idx = self.selectedIndexes()[0] #We'll emit a signal that you can connect to your custom handler self.emit(SIGNAL("my_signal"), idx) Once a keypress occurs, we ask the QListView what the selected indices (!) are. Of course, you can choose to filter out certain keys and choose whether to handle multiple selected cells (I think you can set a selection mode where this isn't possible, see QListView documentation). Now that we have the selected indices (list of QModelIndex), we pass the first one (a QModelIndex) along with our signal. Because we're defining this signal in python, we don't have to set a function prototype; I have no idea if this is bad style. Now all you have to do is connect the signal to a handler: self.connect(your_list_view, SIGNAL("my_signal"), handler_slot) and write your handler. I hope this isn't too nasty of a workaround.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set multiple select options by default from array I'm trying to retrieve options/values from my database in the from of an array i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary. //data in database $mytitle = array( 'Arbitrator', 'Attorney', 'Student', 'Other' ); //data for multiple select $title = array( 'Judge' , 'Magistrate' , 'Attorney' , 'Arbitrator', 'Title Examiner' , 'Law Clerk','Paralegal' , 'Intern' , 'Legal Assistant', 'Judicial Assistant', 'Law Librarian' , 'Law Educator' , 'Attorney', 'Student', 'Other' ); echo "<select name='title[]' multiple='multiple'>"; $test = implode(',', $mytitle); for ($i=0; $i<=14; $i++) { if($test == $title[$i]) { echo "<option selected value='$title[$i]'>$title[$i]</option>"; } else { echo "<option value='$title[$i]'>$title[$i]</option>"; } } echo "</select>"; A: I think you may have a logic error. Try this as your loop: foreach ($title as $opt) { $sel = ''; if (in_array($opt, $mytitle)) { $sel = ' selected="selected" '; } echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>'; } A: Use the in_array() function. for ($i=0; $i<=14; $i++) { if(in_array($title[$i], $mytitle)){ echo "<option selected value='$title[$i]'>$title[$i]</option>"; }else { echo "<option value='$title[$i]'>$title[$i]</option>"; } } A: Very simple with the help of jQuery where the select has the id test $('#test option').attr('selected', 'selected'); JSFiddle Example
{ "language": "en", "url": "https://stackoverflow.com/questions/7543965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Raphael + svgweb + svg core Can it be possible to use Raphael js with svg web and svg core (original SVG API), so that I can get the benefit of all available features? I tried to load them together, but nothing would happen. Perhaps they overwrite each other's functionalities. More precisely, once again my question is can I apply Raphael js along with svgweb on a single SVG. A: I tried combining SVG libraries , the main problem is that they use their own canvas so one will always be on top of the other. A: I suppose they wouldn't just conflict with each other, but those libraries are also quite big so that's a lot of stuff to download for your visitors. Also think of the added burden for the browser which has to interpret all of the libs and hold them in memory, potentially making the browsing experience less snappy. What exactly are you trying to achieve that can't be done with a single one of those libs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Options on spinner based on which button clicked in Android I have this layout with buttons A & B and a spinner under them. The A & B buttons work like radio buttons. I want to make it, when the user clicks button A, the spinner shows options for example 1,2,3,4 but when the user clicks the button B, the spinner will only give 1 & 2 as the options. Code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.create_game); Spinner spinner_player = (Spinner) findViewById(R.id.spinner_player); ArrayAdapter<CharSequence> a = ArrayAdapter.createFromResource( this, R.array.player_array, android.R.layout.simple_spinner_item); a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner_player.setAdapter(a); spinner_player.setSelection(1); ((RadioButton)findViewById(R.id.radio_sudoku)).setChecked(true); } A: You set spinner's contents in code, so nothing prevents you from changing them in response to button click. Or just create two spinners and make one hidden, and on button click change visibility of spinners.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to speed of learning android programming by reducing redundant activities? I'm learning android. Fort testing every aspect of android SDK I need to create new project in eclipse and create new class and so on. I need a new way to decrease these redundant activities. In Java programming I use groovy to learn Java faster, what about android? A: * *You could put all your testing code in one project. Just create a new Activity in the same project. Then you can link activities together with a first page ListView. Take a look at API demos: http://developer.android.com/resources/samples/ApiDemos/index.html (they are also in your android SDK under examples I think) *While you can use different JVM languages with Android, most of the examples are in Java, so IMHO this would be fastest way to learn.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying JRuby/Rails to Glassfish: undefined method `bundle_path' for Bundler:Module The following error shows up in my Glassfish log when attempting to access my app: Caused by: org.jruby.exceptions.RaiseException: (NameError) method 'to_yaml' not defined in Object Looking through the log I see this: undefined method `bundle_path' for Bundler:Module I confirmed that warble is definitely putting the Bundler gem in my .war file. (using ruby 1.9, rails 3.1, glassfish 3.0 and 3.1) This also appears in the glassfish log: Policy Provider:Failed Permission Check: context (" myapp/myapp ") , permission (" (java.lang.reflect.ReflectPermission suppressAccessChecks) ") |#] However I've verified that the permission is granted in server.policy. EDIT: I fixed the permission problem and the first two errors persist. (That said, the premission problem required me to edit a file it specifically says not to edit. Attempting to grant this permission in server.policy in Glassfish did not work). Here is the relevant environment info from the Glassfish log file: https://gist.github.com/1245825 A: You can host it outside Glassfish, on a, nginx+passenger or apache2+passenger configuration, and have it proxying Glassfish. It's a win-win solution, if you don't have to integrate with any other java resource/app. A: This affects some application servers but not others. See this thread for further information and a quick fix. https://github.com/jruby/warbler/issues/44#issuecomment-2809940
{ "language": "en", "url": "https://stackoverflow.com/questions/7543974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass -g3 flag to gcc via Make command line? I am debug our project, but I find that the project was compiled with -g ,but not -g3, which means that I can't expand macros in gdb. I want to add -g3 flag to gcc, but I don't want to modify Makefile, I just want to add this flag via Make command line, could anyone tell me how to do it? Thank you! A: That depends on what the Makefile does/how it was written. It might not be possible. If your Makefile is reasonably "standard", then this should work: make CFLAGS="-g3 ..." If it's for C++: make CXXFLAGS="-g3 ..."
{ "language": "en", "url": "https://stackoverflow.com/questions/7543978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: What is causing a NoMethodError '_view_paths' exception? First off, the exception in question: undefined method '_view_paths' for nil:NilClass` The related routes: get 'payments/index' => 'payments#index' get 'payments/class' => 'payments#class' get 'payments/kids' => 'payments#kids' get 'payments/donate' => 'payments#donate' The associated controller: class PaymentsController < ApplicationController def index end def class end def kids end def donate end end So, the exception occurs every time I try to access one of the routes. The views for the routes described above are the simple ones generated with scaffolding and use no other rails API calls. I can't seem to find any other information on this '_view_paths' method. The only assumption I can make thus far is that the proper view isn't being found, but all views reside exactly where expected according to rails conventions (app/views/payments/*). Has anyone stumbled upon this issue and found a solution? A: You can't define a method named "class" as it's already a reserved method to refer to the object's class, for example: Object.new.class #=> Object Technically I suppose you can override it (as you have), but doing so is mostly likely going to have some bizarre consequences unless you know what you're doing. The error is probably happening when the code tries to call something like self.class._view_paths. It expects to be calling PaymentsController._view_paths. However, you've overridden the instance method class with an empty method returning nil, hence the nil exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: urlencoding in pear changes post request values I recently downloaded PEAR package and i'm currently using HTTP_Requst2. It was working find until i tried posting to a site that included a hidden parameter that had a space in the value: &login=Sign In The problem is that the HTTP_Request is urlencoding the request so my post is sent as: &login=Sign+In I tried both adapters(curl & socket) but no luck, I know it's out there but you guys always helped in the pass. A: + is how the space char should be encoded. So HTTP_Request2 behaviour is perfectly valid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I add OnClick function that goes to a page link (url) with javascript/jquery Ok I am using the fantastic map plugin found here: http://jvectormap.owl-hollow.net/#maps I am a noob ... can't figure out how to implement the parameter mentioned in the "reference" part on the documention which states you can use "onRegionClick". Can anyone tell me how to implement this so that when I click on a region ( A State on the US Map ) it goes to a URL? If this helps at all, my current working example shows the info I want on the page using the Parameter I want, but only in a div (div is called #location ) on the existing page. I would like it to got to a url instead. <script> $(function(){ $('#main').vectorMap({ map: 'usa_en', color: '#aaaaaa', hoverColor: false, hoverOpacity: 0.5, colors: {pa:'#F00, ny:'#F00, }, backgroundColor: 'false', onRegionClick: showmyinfo }); }); function showmyinfo(event,label){ switch (label) { case 'pa': $('#location').html('<h3>PA Locations:</h3><ul><li>Location 1</li><li>123 This Street</li><li>Havertown, PA 19083</li></ul>'); break; case 'ny': $('#location').html('<h3>NY Locations:</h3><ul><li>Location 1</li><li>123 This Street</li><li>Brooklyn, NY 11249</li></ul>'); break; } } </script> Any help greatly appreciated A: Maybe doing this would work: $(function(){ $('#main').vectorMap({ .. onRegionClick: function (event, code) { window.location = 'page.php?code=' + code; } }); }); A: I found this to work for me. onRegionClick: function(event, code){ if (code == "US-AZ") {window.location = '/url1'} if (code == "US-TX") {window.location = '/url2'} if (code == "US-CA") {window.location = '/url3'} if (code == "US-NV") {window.location = '/url4'} if (code == "US-LA") {window.location = '/url5'} }, A: i just had the same problem. but i found a solution: $(document).ready (function() { $('#map').vectorMap( { map: 'germany_en', backgroundColor: 'red', hoverColor: 'black', onRegionClick: function(event, code) { if (code === 'th') { window.location = 'index.php?id=2' } else if (code === 'mv') { window.location = 'index.php?id=3' } else if (code === 'rp') { window.location = 'index.php?id=4' } } }); }); now you can create a separate url for every region (identified by its code). the form "index.php?id=2" comes from TYPO3, so you should adapt it to what you're using... greetings
{ "language": "en", "url": "https://stackoverflow.com/questions/7543988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }