text
stringlengths
8
267k
meta
dict
Q: Popup Never Closes WPF is really getting me out of my nerves here. I configured a popup with some complex content (grid, buttons etc..). I set its StaysOpen property to False and IsOpen to True on a textbox MouseDown preview event. Ths thing is that it opens but never closes when clicking anywhere outside the window. Any suggestions? Thanks! UPDATE: My popup has buttons inside. When I click one of those, the popup closes when I click outside of it. Is some weird stuff happening to the events routing? A: Looks like the popup won't close if opened by any other control event. I just binded the IsOpen property to the IsChecked property of a ToggleButton to simulate a combobox. Thanks for all your answers. A: I was also having this issue, except on the PreviewMouseButtonUp event of a Button. The assumption that there is some bug with Popups and trying to open them in Tunneling events was accurate and led me down the path to my fix (which is a little more generic). I needed to resolve this (the host control was generic / could be several types of controls) by listening for the bubbling event instead of the tunneling event, specifically with the AddHandler(RoutedEvent,Delegate,Boolean) method in order to capture handled events. WAG the issue lies somewhere when transitioning from tunneling to bubbling. A: I use code behind to initialize popup, and I've found that it's not closed if ran sync from other UI action like mouse event. To workaround this I run it async: public static void ShowPopupMessage(string message) { DispatcherHelper.UIDispatcher.BeginInvoke(new Action(() => { var popup = new Popup { Child = new AutoHideMessage(message), StaysOpen = false, IsOpen = true }; })); } A: I set IsOpen on a textbox MouseDown preview event. Set it to what? And where is the TextBox hosted? I can only guess with the scant information provided, but I'd say when you click outside the Popup, your event handler is firing and opening it up again. A: You can use LostFocus event of the PopUp. If the focus is not within the popup, set its IsOpen to false to close it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Magento dropdown with existing products I was wondering if it's possible in Magento to make an attribute with a dropdown input type in wich you can select existing products. If so how would one go about in doing this? Also if someone knows how to display the simple products inside a grouped product on the category(catalog) view, that would be real helpfull aswell. A: * *You need to create new attribute with your own source model. I hope you know how to do it. In this model you need to define method toOptionArray() where you can prepare product list as you want. *It's quite easy. If you have grouped product you can fetch all associated simple product like this $product->getTypeInstance(true)->getAssociatedProducts($product); And then you can display this list as you want
{ "language": "en", "url": "https://stackoverflow.com/questions/7603458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java finding a WINDOW My desire is to create a bot for a game, inside the constrains of the game rules, that would send information to a web-server. My first problem is to find the game window, and then find its name. I been trying to use Assistive Technologies, but not totally comfortable with them. To my limited understanding I need to add a classpath, or something that would set both projects in the same virtual machine. I am using netbeans right now, and I when I use: (which I blame) public void topLevelWindowCreated(Window w) { String name = w.getAccessibleContext().getAccessibleName(); System.out.println("Names of toplevel windows "+name); if (!name.equals("Puzzle Pirates")) // Only if we're running alongside a Window named "Puzzle Pirates" return; window = w; createGUI(); frame.setVisible(true); } I will get the name of the window I create, but not of the game. Resources: Game - Puzzle Pirates www.puzzlepirates.com (the download version) Code Examples: http://java.sun.com/javase/technologies/accessibility/docs/jaccess-1.1/examples/Explorer/Explorer.java Hope you can guide me A: No, Netbeans isn't to blame. The classpath bit means that you need to make Puzzle Pirates launch with your bot library available. That means you can't launch PP and the bot in separate Java processes, which is what likely happens if you run the bot from inside Netbeans. If I understand the sample code comment right, when you put your bot's class name into awt.properties as the example code says, it should get loaded automatically as Puzzle Pirates (or any other Java application) starts. To develop the bot, what you'd have to do is include Puzzle Pirates in your Netbeans project somehow, and start the game, not some test window. A: You could always instance puzzle pirates using reflection to load puzzle pirates from your program and thus in the same java process allowing you to hook onto puzzle pirates and grab any necessary information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do make a button find an id name I'm wanting to click a button and have the matching id name show. I don't know how to use contains, has, or filter to make this work. Basically, click a button find it's id name. Then, if it's id name matches one in nameList show only that id. Second question. There has to be a better way to call all the buttonNames than the way I'm doing with variable bn. </head> <body> <div = "list"> <ul class = "nameList"> <li id ="Heather">Heather</li> <li id ="Cruz">Cruz</li> <li id ="Donny">Donny</li> <li id ="Jimmy">Jimmy</li> </ul> </div> <div = "buttonList"> <form class = "buttonNames"> <input type = "button" id = "Heather" value ="Heather"/> <input type = "button" id = "Cruz" value ="Cruz"/> <input type = "button" id = "Donny" value ="Donny"/> <input type = "button" id = "Jimmy" value ="Jimmy"/> </form> </div> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> // JavaScript Document google.load("jquery", "1.6.2"); google.setOnLoadCallback(function(){ $('.nameList').hide(); /* $(nameList).each(function(i) { var i = $(this).text(); console.log("i = " + i); });*/ //var buttons = $('#Heather, #Cruz, #Donny, #Jimmy'); var bn = $('.buttonNames').children(); console.log(bn); $(bn).click(function() { console.log("You have clicked Button = " + $(this).attr('id')); var t = $(this).attr('id'); }); }); </script> </body> </html> A: try this: $('input[type=button]', '#buttonList').click(function() { alert($('ul.nameList #' + this.id).html()); }); edit: make sure you fix your html <div = "list"> to <div id = "list"> <div = "buttonList"> to <div id = "buttonList"> A: You cannot have duplicate IDs in your HTML. And, you already have the button value that gives you the name you want to refer to the appropriate LI tag. So, I'd suggest that you just get rid of the Id values on the buttons and use this.value to give you the name you need. So, to clean up the HTML to make it legal (no dup IDs), I'd use this HTML: <div id="list"> <ul id = "nameList"> <li id="Heather">Heather</li> <li id="Cruz">Cruz</li> <li id="Donny">Donny</li> <li id="Jimmy">Jimmy</li> </ul> </div> <div id="buttonList"> <form class="buttonNames"> <input type="button" value="Heather"/><br> <input type="button" value="Cruz"/><br> <input type="button" value="Donny"/><br> <input type="button" value="Jimmy"/><br> </form> </div> With this javascript to show only the LI tag with the name that matches the button clicked: $("#buttonList input").click(function() { $("#nameList li").hide(); $("#" + this.value).show(); }); And, you can see it work in this jsFiddle: http://jsfiddle.net/jfriend00/Vhgrg/ A: Try this: $('#buttonList input').click(function() { $('li').hide(); $('li#' + this.id).toggle(); }); jsFiffle The div that has the form in it does not have the attribute name buttonList specified to be class or id, I assumed id on it. Also as in the comments the ids have to be unique in the page A: Try the following $('.buttonNames input').click(function() { var id = $(this).attr('id'); $('.nameList #' + id).show(); }); Note that the .nameList part is only required due to the invalid duplication of ids. Also note that in your code you're hiding the whole unordered list, rsther than each item. So replace $('.nameList').hide with $('.nameList li').hide()
{ "language": "en", "url": "https://stackoverflow.com/questions/7603461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cleaning up memory after using EKEvent Was looking at some code and it looks to be leaking memory. And I'm not sure should I clean this up? Or is it ok? EKEvent *event = [EKEvent eventWithEventStore:eventStore]; I would have guessed this is an autorelease since its a connivence method. But when i read event.startDate = [[NSDate alloc] init]; I see an alloc and an init, so I get nervous about wondering will it be leaking. Full block of code below: EKEventStore *eventStore = [[EKEventStore alloc] init]; EKEvent *event = [EKEvent eventWithEventStore:eventStore]; event.title = @"Test Event for Code Demo"; event.startDate = [[NSDate alloc] init]; event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate]; [event setCalendar:[eventStore defaultCalendarForNewEvents]]; NSError *err; [eventStore saveEvent:event span:EKSpanThisEvent error:&err]; [eventStore release]; Thanks, -Code A: I don't think the properties startDate and endDate need to be alloc'd and init'd. You are creating an autoreleased object with your current code. EKEvent *event = [EKEvent eventWithEventStore:eventStore]; // autoreleased this way To fill your dates and properties, try an alternate method to fill. event.startDate = [NSDate date]; event.endDate = [NSDate dateWithTimeInterval:600 sinceDate:event.startDate]; Now you just need to release eventStore like you are currently doing. Hope this helps. A: If you are using EKEventViewController, Apple documentation says following: @property(nonatomic, retain) EKEvent *event Discussion This property must be set before the view is displayed. EKEventViewController Documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/7603466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I change a test user's password Is it possible to change a test user's password so I can logon to any of my test users as normal so I can test my app properly? I've tried : https://graph.facebook.com/{user id}?password={newpassword}&method=post&access_token={the access token} I got the access token from the Roles screen where all my test users are listed. The above link returns : { "error": { "message": "Invalid OAuth access token.", "type": "OAuthException" } } What am I doing wrong? And is there another way to change the password? I have 15 or so test users and I need to be able to log in as any of them. Only my main test user is registered with my app, the others are friends of the main test user (this is by design) I tried creating lots of normal users to test with and quickly realised Facebook do their best to stop people doing this Thanks A: Yes - You can. However I have tried only manually - it works. * *You have to be admin of application for which users You are editing *Go to FB Developers page -> Click 'Edit Roles' *At the bottom of the page there will be all users listed, each having option to set password next to its profile photo. Just Click and change. Hope that helps a bit. As it is not a solution to set manually password for 25 users. But if it is not possible to do it manually then it won't be possible with API. worth to try, just to identify error. Yes - creating real users for testing purposes is not an option A: This is very Easy by using even APP Dashboard as follow All though you can use Graph API for the same ,with User APP Access Toke or User access Token (If user ID is accessed) for this Process Here is Python script of the same A: For some reason, Facebook's documentation says that you should do an HTTP POST, but the example they show uses a query string, not post data. Try submitting all query parameters as post data: curl -H "Content-Type: application/x-www-form-urlencoded" \ --data "access_token=<facebook app access token>&method=post&name=<full user name>&password=<password>" \ -X POST 'https://graph.facebook.com/<facebook test user id>'
{ "language": "en", "url": "https://stackoverflow.com/questions/7603468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JavaScript widget with trust based authentication under active directory I'm building a new project and I'm having some debate over how it needs to be developed. The big picture is to develop a consumable JavaScript widget that other internal developers can embed into their web applications. The trick is that the consumer needs to be able to tell me what AD user is currently logged into their page...and then I need to trust that the passed username is coming from the consumer and hasn't been tampered with via outside sources. The overall solution needs to have a VERY simple set-up on the consuming side involving no compiled code changes. Also it needs to be functional across both ASP.net and PHP applications (hence my decision to go with JavaScript). Overall, it's kind of like an Oauth solution...except the trust between domains can be intrinsic since I'll already know every user in the company trusts the host domain. I started stubbing it out and got kind of stuck. My idea was that I would basically host a JavaScript file that the client host could embed in their page. During their page load cycle, they could init my JavaScript widget and pass it a plain text username (all I really need). Somehow I would establish an secure trust between the client host's web page, and my widget so that it would be impossible for a third-party to embed my widget into a false web page and send action commands under a user other than their own. I hope this makes sense to someone. A: I haven't really discovered an answer so to speak, but I've decided on a method: So, I decided on a pattern where I write my JavaScript and HTML widget using the proposed jQuery UI Widget Factory. That allows the my consumer to implement the widget using simple syntax like: <script src="widget.js"></script> $('#someElement').myWidget({ encryptionUrl: handlerPath }); Now, you'll noticed that as part of my widget, I ask the consumer to pass a "handlerPath." The "handler" is simply an Microsoft MVC Controller which is in charge of getting the logged in user, and encrypting the call. So the handler in my app looks something like this... [Authorize] public JsonpResult GetToken(string body, string title, string sender) { Packet token = new Packet(); try { // Get the widget host's public cert string publicKey = "some.ssl.key.name.here"; // Get the consumer host's private cert string privateKey = "this.consumers.ssl.key.name.here"; // Build a simple message object containing secure details // Specifically, the Body will have action items (in JSON) from my widget // The User will be generated from the consumer's backend, thus secure Message message = new Message(){ Body = body, Title = title, User = System.Web.HttpContext.Current.User.Identity.Name, EncryptionServerIP = Request.UserHostAddress, Sender = new Uri(sender), EncryptionTime = DateTime.Now }; PacketEncryption encryption = new PacketEncryption(); // This class just wraps basic encryption and signing methods token = encryption.EncryptAndSign(message, publicKey, privateKey); token.Trust = "thisConsumerTrustName"; } catch (Exception exception) { throw; } return this.Jsonp(token); } Now, I have an encrypted "token" which has been encrypted using the widget host's public key, and signed using the widget consumer's private key. This "token" is passed back to the widget via JSONP from the consuming server. My widget then sends this "token" (still as JSONP) to it's host server. The widget hosting server has decrypting logic which looks something like this. public Message DecryptAndVerify(Packet packet, string requestIP) { if (packet == null) throw new ArgumentNullException("packet"); if (requestIP == null) throw new ArgumentNullException("requestIP"); Message message = new Message(); try { // Decrypt using the widget host's private key RSAEncryption decrypto = new RSAEncryption("MyPrivateKey"); // Verify the signature using the "trust's" public key // This is important because like you'll notice, I get the trust name // from the encrypted packet. I then maintain a "trust store" mapping // in my web.config, or SQL server RSAEncryption verifyo = new RSAEncryption(GetPublicKeyFromTrust(packet.Trust)); string decryptedJson = decrypto.DecryptString(packet.EncryptedData); // Verify the signature if (!verifyo.Verify(decryptedJson, packet.Signature)) { Exception ex = new Exception("Secure packet was not verified. Tamper evident"); throw ex; } // If the message is encrypted correctly, turn it into a message object message = decryptedJson.FromJson<Message>(); // Verify the ip if (message.EncryptionServerIP != requestIP) { Exception ex = new Exception("Request IP does not match encryption IP. Tamper evident"); throw ex; } // Verify the time if ((DateTime.Now - message.EncryptionTime).Seconds > 30) { Exception ex = new Exception("Secure packet is too old"); throw ex; } } catch (Exception ex) { throw ex; } return message; } The idea is that the JavaScript widget determines the secure actions the end user wants to take. Then it calls back to it's host (using the handler path provided by the consumer) and requests an encrypted token. That token contains the IP address of the caller, a timestamp, the current AD username, and a bundle of actions to be completed. Once the widget receives the token, it passes it over to it's own host server at which point the server checks to make sure that it is * *Signed and encrypted properly according to predefined trusts *Not older than 30 seconds *From the same IP as the initial request to the consumer's server After I determine those checks to be valid I can act on the user's actions by creating a WindowsPrincipal identity from the string username like this: WindowsPrincipal pFoo = new WindowsPrincipal(new WindowsIdentity("username")); bool test = pFoo.IsInRole("some role"); All said and done, I have established a trusted request from the widget consumer, and I no longer have to prompt for authentication. Hopefully this helps you out. It's been running in my internal environment for about a month of QA and it's it's working great so far.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: subtract two dates in php Possible Duplicate: PHP calculate age I'm trying to subtract the years and check the user's age. I keep getting 1969 for $user_birth, which I think the raw date can't be parsed. $raw_birth = "01-19-1980"; $user_birth = date("Y", strtotime($raw_birth)); $today_date = date("Y", time()); echo $raw_birth."<br />".$today_date."<br />".$user_birth."<br />"; echo $today_date-$user_birth; Any ideas? A: $year="1997"; $month="01"; $day="24"; $age=date("Y"); $age-= $year; if(($month>=date("m")) && ($day>date("d"))) { $age--; } This code calculates an accurate age of an user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Ruby Text Analysis Is there any Ruby gem or else for text analysis? Word frequency, pattern detection and so forth (preferably with an understanding of french) A: the generalization of word frequencies are Language Models, e.g. uni-grams (= single word frequency), bi-grams (= frequency of word pairs), tri-grams (=frequency of world triples), ..., in general: n-grams You should look for an existing toolkit for Language Models — not a good idea to re-invent the wheel here. There are a few standard toolkits available, e.g. from the CMU Sphinx team, and also HTK. These toolkits are typically written in C (for speed!! because you have to process huge corpora) and generate standard output format ARPA n-gram files (those are typically a text format) Check the following thread, which contains more details and links: Building openears compatible language model Once you generated your Language Model with one of these toolkits, you will need either a Ruby Gem which makes the language model accessible in Ruby, or you need to convert the ARPA format into your own format. adi92's post lists some more Ruby NLP resources. You can also Google for "ARPA Language Model" for more info Last not least check Google's online N-gram tool. They built n-grams based on the books they digitized — also available in French and other languages! A: The Mendicant Bug: NLP Resources for Ruby contains lots of useful Ruby NLP links. I had tried using the Ruby Linguistics stuff a long time ago, and remember having a lot of problems with it... I don't recommend jumping into that. If most of your text analysis involves stuff like counting ngrams and naive Bayes, I recommend just doing it on your own. Ruby has pretty good basic libraries and awesome support for regexes, so this should not be that tricky, and it will be easier for you to adapt stuff to the idiosyncrasies of the problem you are trying to solve. Like the Stanford parser gem, its possible to use Java libraries that solve your problem from within Ruby, but this can be tricky, so probably not the best way to solve a problem. A: I wrote the gem words_counted for this reason. You can see a demo on rubywordcount.com. It has a lot of the analysis features you mention, and a host more. The API is well documented and can be found in the readme on Github.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: My C++ OpenGL SDL program is not working as I expected I have just started learning OpenGL and I am attempting to make a game of pong. I'm having trouble getting the paddle to appear on the screen and I can't fathom out why: I thought with this code it should appear in the top left corner and move when down and up keys are pressed. main.cpp - #include <SDL/SDL.h> #include <SDL/SDL_opengl.h> #include "classes.h" #include "functions.h" int main (int argc, char *argv[]) { init_everything(); PlayerPaddle paddle; bool quit = false; while( quit == false ) { while( SDL_PollEvent( &event ) ) { paddle.handle_input(); if( event.type == SDL_QUIT ) { quit = true; } } glClear( GL_COLOR_BUFFER_BIT ); paddle.show(); SDL_GL_SwapBuffers(); } SDL_Quit(); return 0; } classes.h - #ifndef CLASSES_H #define CLASSES_H SDL_Event event; // ******************* Beginning of PlayerPaddle class ******************* class PlayerPaddle { private: int xloc; int yloc; int paddle_height; int paddle_width; public: PlayerPaddle(); void show(); void handle_input(); }; PlayerPaddle::PlayerPaddle() { int xloc = 0; int yloc = 0; int paddle_height = 50; int paddle_width = 15; } void PlayerPaddle::show() { glBegin( GL_QUADS ); glColor4f( 1.0, 1.0, 1.0, 1.0 ); glVertex3f( 0, yloc, 0 ); glVertex3f( paddle_width, yloc, 0 ); glVertex3f( paddle_width, paddle_height, 0 ); glVertex3f( 0, paddle_height, 0 ); glEnd(); glLoadIdentity(); } void PlayerPaddle::handle_input() { if( event.type == SDL_KEYDOWN ) { switch( event.key.keysym.sym ) { case SDLK_UP: yloc -= 10; paddle_height -= 10; break; case SDLK_DOWN: yloc += 10; paddle_height += 10; break; } } if (yloc < 0) { yloc += 10; paddle_height += 10; } if (yloc > 640) { yloc -= 10; paddle_height -= 10; } } // ******************* End of the PlayerPaddle class ******************* #endif functions.h - #ifndef FUNCTIONS_H #define FUNCTIONS_H void init_GL() { glClearColor( 0, 0, 0, 0 ); glViewport(0, 0, 640, 480); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( 0, 640, 480, 0, 1, -1 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); } void init_everything() { SDL_Init( SDL_INIT_EVERYTHING ); SDL_SetVideoMode( 640, 480, 32, SDL_OPENGL ); init_GL(); SDL_WM_SetCaption( "Pong by Michael Clover", NULL ); } #endif A: Give this a shot: #include <SDL.h> #include <SDL_opengl.h> class PlayerPaddle { private: int xloc; int yloc; int paddle_height; int paddle_width; public: PlayerPaddle() { xloc = 0; yloc = 0; paddle_height = 50; paddle_width = 15; } void show() { glPushMatrix(); glTranslatef( xloc, yloc, 0 ); glBegin( GL_QUADS ); glColor4f( 1.0, 1.0, 1.0, 1.0 ); glVertex2f( 0, 0 ); glVertex2f( paddle_width, 0 ); glVertex2f( paddle_width, paddle_height ); glVertex2f( 0, paddle_height ); glEnd(); glPopMatrix(); } void handle_input( const SDL_Event& event ) { if( event.type == SDL_KEYDOWN ) { switch( event.key.keysym.sym ) { case SDLK_UP: yloc += 10; break; case SDLK_DOWN: yloc -= 10; break; } } if (yloc < 0) { yloc = 0; } if (yloc > 640) { yloc = 640; } } }; void init_GL() { glClearColor( 0, 0, 0, 0 ); glViewport(0, 0, 640, 480); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( 0, 640, 0, 480, -1, 1 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); } void init_everything() { SDL_Init( SDL_INIT_EVERYTHING ); SDL_SetVideoMode( 640, 480, 32, SDL_OPENGL ); init_GL(); SDL_WM_SetCaption( "Pong by Michael Clover", NULL ); } int main (int argc, char *argv[]) { init_everything(); PlayerPaddle paddle; bool quit = false; while( quit == false ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { paddle.handle_input( event ); if( event.type == SDL_QUIT ) { quit = true; } } glClear( GL_COLOR_BUFFER_BIT ); paddle.show(); SDL_GL_SwapBuffers(); } SDL_Quit(); return 0; } Most notably your constructor was borked. You were declaring and setting local variables instead of your member variables. Which resulted in uninitialized member variables, way off in la-la land (-80 thousand or so on my machine) and (obviously) nowhere near your viewport :) I switched the glOrtho() call around to produce a standard Cartesian coordinate system, with (0,0) in the lower-left and (640,480) in the upper-right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: bbfreeze and protobuf I'm trying to package a script with bbfreeze that uses the protocol buffers. Using bbfreeze like so: #!/usr/bin/python from bbfreeze import Freezer import os f = Freezer('dist') f.addScript('main.py') f() Results in No module named google.protbuf on the client. Reading the docs a bit, I try this: #!/usr/bin/python from bbfreeze import Freezer import os f = Freezer('dist',includes=["google.protobuf"]) f.addScript('main.py') f() Results in ImportError: No module named google when running the bbfreeze script. bbfreeze is at version 0.97.3 installed from easy_install. Anyone run into this issue or a similar one previously? A: Sounds like you have not installed protobuf... try "pip install protobuf" to install it from pypi.python.org/pypi/protobuf .
{ "language": "en", "url": "https://stackoverflow.com/questions/7603491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get the .getJSON() jquery data out of the response? function saveCallerReference(callerReference){ $.getJSON('/index.php?r=site/AJAXsaveCallerReference', function(data) { console.log(data); return data; }); } Given the above, the line "return data;" never gets returned, when the function(data){} exits, where does that return go? I want my outer scope function, saveCallerReference, to return the value from the getJSON(). console.log() is printing correctly so I am getting the data. A: Where do you expect it to be returned to? the function being called is anonymous... You need to understand that $.getJSON happens asyncronously so the normal top-down flow does not apply, you need to do whatever you need to trigger whatever you want to do with data inside the callback... $.getJSON('/index.php?r=site/AJAXsaveCallerReference', function(data) { functionThatDoesWhatYouWant(data); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7603492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to map PostgreSQL enum with JPA and Hibernate I am trying to map a PostgreSQL custom type,named transmission_result, to a Hibernate/JPA POJO. The PostgreSQL custom type is more or less an enum type of string values. I have created a custom EnumUserType called PGEnumUserType as well as an enum class representing the PostgreSQL enumerated values. When I run this against a real database, I receive the following error: 'ERROR: column "status" is of type transmission_result but expression is of type character varying Hint: You will need to rewrite or cast the expression. Position: 135 ' Upon seeing this, I figured I needed to change my SqlTypes to Types.OTHER. But doing so breaks my integration tests (using HyperSQL in memory DB) with the message: 'Caused by: java.sql.SQLException: Table not found in statement [select enrollment0_."id" as id1_47_0_, enrollment0_."tpa_approval_id" as tpa2_47_0_, enrollment0_."tpa_status_code" as tpa3_47_0_, enrollment0_."status_message" as status4_47_0_, enrollment0_."approval_id" as approval5_47_0_, enrollment0_."transmission_date" as transmis6_47_0_, enrollment0_."status" as status7_47_0_, enrollment0_."transmitter" as transmit8_47_0_ from "transmissions" enrollment0_ where enrollment0_."id"=?]' I'm not sure why changing the sqlType results in this error. Any help is appreciated. JPA/Hibernate Entity: @Entity @Access(javax.persistence.AccessType.PROPERTY) @Table(name="transmissions") public class EnrollmentCycleTransmission { // elements of enum status column private static final String ACCEPTED_TRANSMISSION = "accepted"; private static final String REJECTED_TRANSMISSION = "rejected"; private static final String DUPLICATE_TRANSMISSION = "duplicate"; private static final String EXCEPTION_TRANSMISSION = "exception"; private static final String RETRY_TRANSMISSION = "retry"; private Long transmissionID; private Long approvalID; private Long transmitterID; private TransmissionStatusType transmissionStatus; private Date transmissionDate; private String TPAApprovalID; private String TPAStatusCode; private String TPAStatusMessage; @Column(name = "id") @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getTransmissionID() { return transmissionID; } public void setTransmissionID(Long transmissionID) { this.transmissionID = transmissionID; } @Column(name = "approval_id") public Long getApprovalID() { return approvalID; } public void setApprovalID(Long approvalID) { this.approvalID = approvalID; } @Column(name = "transmitter") public Long getTransmitterID() { return transmitterID; } public void setTransmitterID(Long transmitterID) { this.transmitterID = transmitterID; } @Column(name = "status") @Type(type = "org.fuwt.model.PGEnumUserType" , parameters ={@org.hibernate.annotations.Parameter(name = "enumClassName",value = "org.fuwt.model.enrollment.TransmissionStatusType")} ) public TransmissionStatusType getTransmissionStatus() { return this.transmissionStatus ; } public void setTransmissionStatus(TransmissionStatusType transmissionStatus) { this.transmissionStatus = transmissionStatus; } @Column(name = "transmission_date") public Date getTransmissionDate() { return transmissionDate; } public void setTransmissionDate(Date transmissionDate) { this.transmissionDate = transmissionDate; } @Column(name = "tpa_approval_id") public String getTPAApprovalID() { return TPAApprovalID; } public void setTPAApprovalID(String TPAApprovalID) { this.TPAApprovalID = TPAApprovalID; } @Column(name = "tpa_status_code") public String getTPAStatusCode() { return TPAStatusCode; } public void setTPAStatusCode(String TPAStatusCode) { this.TPAStatusCode = TPAStatusCode; } @Column(name = "status_message") public String getTPAStatusMessage() { return TPAStatusMessage; } public void setTPAStatusMessage(String TPAStatusMessage) { this.TPAStatusMessage = TPAStatusMessage; } } Custom EnumUserType: public class PGEnumUserType implements UserType, ParameterizedType { private Class<Enum> enumClass; public PGEnumUserType(){ super(); } public void setParameterValues(Properties parameters) { String enumClassName = parameters.getProperty("enumClassName"); try { enumClass = (Class<Enum>) Class.forName(enumClassName); } catch (ClassNotFoundException e) { throw new HibernateException("Enum class not found ", e); } } public int[] sqlTypes() { return new int[] {Types.VARCHAR}; } public Class returnedClass() { return enumClass; } public boolean equals(Object x, Object y) throws HibernateException { return x==y; } public int hashCode(Object x) throws HibernateException { return x.hashCode(); } public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException { String name = rs.getString(names[0]); return rs.wasNull() ? null: Enum.valueOf(enumClass,name); } public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.VARCHAR); } else { st.setString(index,((Enum) value).name()); } } public Object deepCopy(Object value) throws HibernateException { return value; } public boolean isMutable() { return false; //To change body of implemented methods use File | Settings | File Templates. } public Serializable disassemble(Object value) throws HibernateException { return (Enum) value; } public Object assemble(Serializable cached, Object owner) throws HibernateException { return cached; } public Object replace(Object original, Object target, Object owner) throws HibernateException { return original; } public Object fromXMLString(String xmlValue) { return Enum.valueOf(enumClass, xmlValue); } public String objectToSQLString(Object value) { return '\'' + ( (Enum) value ).name() + '\''; } public String toXMLString(Object value) { return ( (Enum) value ).name(); } } Enum class: public enum TransmissionStatusType { accepted, rejected, duplicate, exception, retry} A: The following might also help to have Postgres convert strings silently to your SQL enum type so you can use @Enumerated(STRING) and don't need @Type. CREATE CAST (character varying as post_status_type) WITH INOUT AS IMPLICIT; A: A quick solution will be jdbc:postgresql://localhost:5432/postgres?stringtype=unspecified ?stringtype=unspecified is the answer A: If you have following post_status_info enum type in PostgreSQL: CREATE TYPE post_status_info AS ENUM ( 'PENDING', 'APPROVED', 'SPAM' ) You can easily map Java Enum to a PostgreSQL Enum column type using the following custom Hibernate Type: public class PostgreSQLEnumType extends org.hibernate.type.EnumType { public void nullSafeSet( PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { if(value == null) { st.setNull( index, Types.OTHER ); } else { st.setObject( index, value.toString(), Types.OTHER ); } } } To use it, you need to annotate the field with the Hibernate @Type annotation as illustrated in the following example: @Entity(name = "Post") @Table(name = "post") @TypeDef( name = "pgsql_enum", typeClass = PostgreSQLEnumType.class ) public static class Post { @Id private Long id; private String title; @Enumerated(EnumType.STRING) @Column(columnDefinition = "post_status_info") @Type( type = "pgsql_enum" ) private PostStatus status; //Getters and setters omitted for brevity } That's it, it works like a charm. Here's a test on GitHub that proves it. A: I figured it out. I needed to use setObject instead of setString in the nullSafeSet function and pass in the Types.OTHER as the java.sql.type to let jdbc know that it was a postgres type. public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { if (value == null) { st.setNull(index, Types.VARCHAR); } else { // previously used setString, but this causes postgresql to bark about incompatible types. // now using setObject passing in the java type for the postgres enum object // st.setString(index,((Enum) value).name()); st.setObject(index,((Enum) value), Types.OTHER); } } A: build.gradle.kts dependencies { api("javax.persistence", "javax.persistence-api", "2.2") api("org.hibernate", "hibernate-core", "5.4.21.Final") } In Kotlin it is important to make a generic extension with EnumType<Enum<*>>() PostgreSQLEnumType.kt import org.hibernate.type.EnumType import java.sql.Types class PostgreSQLEnumType : EnumType<Enum<*>>() { @Throws(HibernateException::class, SQLException::class) override fun nullSafeSet( st: PreparedStatement, value: Any, index: Int, session: SharedSessionContractImplementor) { st.setObject( index, value.toString(), Types.OTHER ) } } Custom.kt import org.hibernate.annotations.Type import org.hibernate.annotations.TypeDef import javax.persistence.* @Entity @Table(name = "custom") @TypeDef(name = "pgsql_enum", typeClass = PostgreSQLEnumType::class) data class Custom( @Id @GeneratedValue @Column(name = "id") val id: Int, @Enumerated(EnumType.STRING) @Column(name = "status_custom") @Type(type = "pgsql_enum") val statusCustom: StatusCustom ) enum class StatusCustom { FIRST, SECOND } A simpler option that I don't recommend is the first option in Arthur's answer which adds a parameter in the connection URL to the db so that the enum data type is not lost. I believe that the responsibility of mapping the data type between the backend server and the database is precisely the backend. <property name="connection.url">jdbc:postgresql://localhost:5432/yourdatabase?stringtype=unspecified</property> Source A: As TypeDef has disappeared in Hibernate 6, and we thus need to annotate each affected property anyway, I've found that using @ColumnTransformer(write="?::transmission_result ") to force a type cast works, without any Hibernate usertype classes needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Should I create a branch for single commits? I'm new to Git and to branching. Within our team, we have a bunch of websites that require simple maintenance (adding a new page, fixing some links, etc). The commits would normally contain all of the requested functionality. I am not sure if we should create a branch, or if we can just commit to master? After all, the commits are named and make it clear what we have done. I feel that branches actually create more complexity for such simple tasks. Or am I mistaken? A: As a rough guideline: Commits exist to update the state of a branch, and branches exist as alternative views of your codebase. If it makes sense that your changes can be seen as moving "forward in time" of the master branch, then you should use commits only. If you are going to do something that is an "alternate reality" of the master branch, you should make a different branch. In this case, if I understand your situation, I would guess you're really truly updating the state of your codebase, so I would just commit your changes. In this respect Git is similar to any SCM. What makes Git different with branching is that branches are very easy to create and (somewhat) easy to merge. That means that a common workflow is to branch master into a work in progress for a new feature, then make your edits. When you're satisfied, you can merge your branch into master. This is just an improvement on straight commits - you are creating an "alternate reality" of an unstable master, improving it, then merging it back into the real master - but the net effect is the same: your commits in the alternate reality end up landing in master as if you had always made them there. The end goal of all this runaround is that your commits show a linear march through time of changes. A: Branches do create more complexity but at the same time they give you more power. Once you start branching you can easily shuffle them, take the changes from one but not the other and so on. For simple scenarios just working on the master branch is enough of course (it becomes really similar to svn use). You would have to find your own way into git which best suits your needs. Here is a good resource. A: May I suggest taking a look at Git flow? http://nvie.com/posts/a-successful-git-branching-model/ https://github.com/nvie/gitflow Some people say that you should avoid branching where possible, but I think that git flow can provide a great solution for an environment where you have people working on different features at once. A: One of the beautiful things about Git is that it accommodates many different ways of working. * *You can create a branch for every change, or never create one at all. *You can use remote branches shared among developers, or only local branches. *You can merge branches and leave the branches visible, or you can heavily rebase and fast-forward merge so your history never shows a single parallel line. Anything we tell you here will be just a matter of personal preference. My personal preference is to always create a local branch for any type of change. That's because: * *I have no-ff turned on, and it's easy to back out a change or series of changes if they have an associated merge commit. *It's easy to keep several different changes from getting mixed up. I may be in the middle of a non-urgent change, when an urgent one comes across. You can use git stash to hold your changes, but I find separate branches less confusing. (Often I'll check in my work with a commit message of "WORK IN PROGRESS." Then when I return to the branch, I do git reset HEAD~1 to undo that last commit [but keep the changes] and keep working.) *Having a branch encourages me to create smaller commits (fewer changes), which makes it easier to merge them correctly later. These are some reasons to consider always creating a branch. Try it for a while, see if it works for you, and then keep it as a new technique or discard it if you don't care for it. A: Here is my way of working. You can also see some good comments from Martin Fowler and others. Good discussion: https://plus.google.com/109096274754593704906/posts/R4qkeyRadLR This may apply well to you if you want to have some control on what you release. But the fact that your "features" are small, you may relate to this type of workflow. Branch-per-Feature The big WHY: Fast, flexible, high quality and confident development/deployment/testing etc. This makes business happy. In point form, unorganized and rough: Features are small Old-school branch-per-feature meant that branches were large and long living to avoid having to integrate because it was a pain. This was a vicious circle as the feature would diverge further and further from other features or the mainline. Features should be as atomic as possible and your development process should abide by the Open Close Principle. Features should be small. Integrate relentlessly They should be integrated into an integration branch almost as often as you commit to them. This gives feedback immediately. You have some sort of CI running off of the integration branch to tell you if your changes are not adversely affecting other work. This gives you the immediate feedback of trunk-based integration while keeping your work organized and malleable. Don't do back-merges Or at least avoid them. A back-merge is where you want to use something from the integration branch to help you get your work done on the feature. This is a smell that you don't have independent stories. A reasonable middle-ground is cherry-picking. A successfully cherry-picked commit will not cause you issues when you merge in the future. Keeping a feature branch filled with commits that only attain what the feature is supposed to do will make working with it much more flexible. Involve QA from the start This should not even be a contentious point anymore. We all know how important tight feedback loops are. There should not be a QA department with QA employees. QA should be a hat that is worn at different or same people at different times. Knowing what your Acceptance Criteria is and how you will prove it from the start is integral to getting a lot of things gelling - including a successful branch-per-feature regiment. A proper DSL a la Ubiquitous Language (see Domain Driven Design) is at the heart of this. The tool that best communicates across to the Product Owner, Regression/Specification Testing and Behaviour Driven Design feedback is currently StoryTeller. One thing that it offers that no other tools offer is communication to the person writing the Acceptance Tests of what the system is capable of doing with the smallest amount of friction caused by technology. You simply pick what you want to do by clicking on links, filling out text boxes and selecting from drop-downs. There is no guessing as to how a tool might interpret your free-form text with it's regex and English-parsing goodness. Share your hard work There will be conflicts when you merge. This is a fact of life when work is done by more than one person. When you integrate often from your feature to the integration branch, the conflicts you solve should be remembered. This is done by git's rerere but could be simulated in other systems with little effort. The key is to set up a way of sharing these auto-resolution conflicts to the rest of the team. Now anyone that tries to integrate that feature and has that conflict will not have to resolve it. No dev required to put together a build. This is a manual share right now if needed. I should have the script published in about a week that does this behind the scenes. If you want to do it yourself, look no further than the .git/rr-cache folder in your repository. Simple synchronization between all devs is the bare minimum that is needed. Taking features out is more powerful than putting them in This might sound counter-intuitive. But at the end of an iteration, a feature that you thought was done may not work as the last bits of testing on the build as a whole make releasing a no-go. Anyone should be able to take out that feature and release anyway. So the trick is not to take the feature out of the build. You make a build with the problem feature omitted. You can integrate that feature in the next iteration when there is time. Releasing a build should be painless. Don't make a build to test out of the integration branch. Make a separate branch that can be reset relentlessly and tag release candidates. Reset this branch to the start commit of your iteration and merge all the features you know work. No conflicts. Remember rerere and the like? Anyone should be able to do this if you followed the practices here. This is "why" the hard work needs to be shared. The key is we "threw away" all previous merges and have to redo them. But remembering our conflict resolutions, this is now a trivial matter. If in doubt, we haven't really thrown them away, they are still there to reference or use. Git's pick-axe functionality makes it really easy to find certain code changes if you don't know where to look. Giant refactorings Your work is as organized as is possible. Whether you elect to do this off of a certain point in time on the integration branch, release candidate branch or you started a feature branch for it, you have a way of tracking that work and can apply it as a merge, rebase or manual patch to another point if necessary. Any hardships that you may encounter will be tempered by the fact that you are relentlessly sharing your conflict resolutions and continuously integrating. PROPER BRANCH-PER-FEATURE RELIES ON RELENTLESS CONTINUOUS INTEGRATION Toggles are a hack There are exceptions. You're a giant company. You need to enable a feature for a small subset of early adopter users. This is now an explicit feature that's important to business. That's where we all want to be but most of us are not. Having to make architectural changes because you can't effectively organize your work is a process smell plain and simple. Some teams are not mature enough and this may be an OK solution temporarily. This is Git Flow Improved Most of this way of working started from the excellent post called "Git Flow a Successful Branching Strategy". The important addition to this process is the idea that you start all features in an iteration from a common point. This would be what you released for the last one. This drives home the granular, atomic, flexible nature that features must exhibit for us to deliver to business in the most effective way. The other key difference is no back-merge into the feature. Otherwise, you will not be able to exclude this feature later in the iteration. It will be bad if you use old tools Not having a snapshot based history will hurt as branching is effectively copying another branch which will be slow. Not having a base of where the branch originated will make merging difficult as you do not have a base to compare how each side of development has changed. There are many other issues with having a connected-only tool to support what you do in order to work with everyone. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get this element from this array I have an array $arr that when I var_dump looks like this. What's the easiest way to get the 2nd last item ('simple' in this case). I can't do $arr[4] because the number of items may vary per url, and I always want just the 2nd last. (note that there's an extra empty string at the end, which will always be there.) array 0 => string 'http:' (length=5) 1 => string '' (length=0) 2 => string 'site.com' 3 => string 'group' 4 => string 'simple' 5 => string 'some-test-url' 6 => string '' (length=0) A: So long as it is not a keyed or hashed array and it has more than two items... $arr[count($arr) - 2]; Note: that my interpretation of second to last is second from the end. This may differ from yours. If so, subtract 3. A: Get the count and subtract 3? $arr[count($arr)-3] A: if (!empty($arr) && count($arr)>1){ //or > 2, -3 for your extra ending $val = $arr[count($arr)-2]; } Should help you. A: $second_last = count($array) - 3; $value = $array[$second_last]; A: $arrayLen=count($arr); echo $arr[$arrayLen-2]; A: Yet another alternative: echo current(array_slice($data, -3, 1));
{ "language": "en", "url": "https://stackoverflow.com/questions/7603505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VBScript error handling in C# I want to access WMI using the AutomationFactory in a Silverlight OOB application. dynamic locator = AutomationFactory.CreateObject("WbemScripting.SWbemLocator"); dynamic wmi = locator.ConnectServer(".", "\\root\\cimv2"); I now want to add error handling to this. MSDN states that the return value is a reference to the connected object if the call is successful and that in case of an error I should check the Err object. However, there are two questions I have with this: * *What is the return value if the call is not successful? null? Some arbitrary pointer that I cannot use? *How can I access the Err object in Silverlight? *How can I detect if the call was successful? May there be any exceptions which I have to catch? *I've seen some examples using the using statement, and some without. Do I have to dispose the dynamic objects manually after I've used them? A: * *What is the return value if the call is not successful? null? Some arbitrary pointer that I cannot use? No value is return and the LHS of an assignment is unmodified when a call into a COM component fails. Instead the COMException is thrown. * *How can I access the Err object in Silverlight? This is no "Err" object, that is a VB(Script) construct, it doesn't exist in C#. However the infor you are after will be available as the properties of the COMException thrown when a call fails. * *How can I detect if the call was successful? May there be any exceptions which I have to catch? Yup, see above. * *I've seen some examples using the using statement, and some without. Do I have to dispose the dynamic objects manually after I've used them? Attempts to manage COM object lifetimes using Dispose have varied results. Personally I'd make sure that anything that has something like a "Close" method has that "Close" method call and leave it at that. If you really want to make user COM objects are released then at an appropriate point (and not too frequently) call GC.Collect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Haskell syntax for 'or' in case expressions In F#, I can use | to group cases when pattern matching. For example, let rec factorial n = match n with | 0 | 1 -> 1 // like in this line | _ -> n * factorial (n - 1) What's the Haskell syntax for the same? A: I'm not entirely familiar with F#, but in Haskell, case statements allow you to pattern match, binding variables to parts of an expression. case listExpr of (x:y:_) -> x+y [x] -> x _ -> 0 In the theoretical case that Haskell allowed the same: It would therefore be problematic to allow multiple bindings case listExpr of (x:y:_) | [z] -> erm...which variables are bound? x and y? or z? There are rare circumstances where it could work, by using the same binding: unEither :: Either a a -> a unEither val = case val of Left v | Right v -> v And as in the example you gave, it could work alright if you only match literals and do not bind anything: case expr of 1 | 0 -> foo _ -> bar However: As far as I know, Haskell does not have syntax like that. It does have guards, though, as mentioned by others. Also note: Using | in the case statement serves a different function in Haskell. The statement after the | acts as a guard. case expr of [x] | x < 2 -> 2 [x] -> 3 _ -> 4 So if this sort of syntax were to be introduced into Haskell, it would have to use something other than |. I would suggest using , (to whomever might feel like adding this to the Haskell spec.) unEither val = case val of Left v, Right v -> v This currently produces "parse error on input ," A: Building on some of the above answers, you can (at least now) use guards to do multiple cases on a single line: case name of x | elem x ["Bob","John","Joe"] -> putStrLn "ok!" "Frank" -> putStrLn "not ok!" _ -> putStrLn "bad input!" So, an input of "Bob", "John", or "Joe" would give you an "ok!", whereas "Frank" would be "not ok!", and everything else would be "bad input!" A: Here's a fairly literal translation: factorial n = case n of 0 -> sharedImpl 1 -> sharedImpl n -> n * factorial (n - 1) where sharedImpl = 1 View patterns could also give you a literal translation. isZeroOrOne n = case n of 0 -> True 1 -> True _ -> False factorial1 n = case n of (isZeroOrOne -> True) -> 1 n -> n * factorial (n - 1) factorial2 n = case n of (\n -> case n of { 0 -> True; 1 -> True; _ -> False }) -> 1 n -> n * factorial (n - 1) Not saying that these are better than the alternatives. Just pointing them out. A: There is no way of sharing the same right hand side for different patterns. However, you can usually get around this by using guards instead of patterns, for example with elem. foo x | x `elem` [A, C, G] = ... | x `elem` [B, D, E] = ... | otherwise = ... A: with guards: factorial n | n < 2 = 1 | otherwise = n * (factorial (n - 1)) with pattern matching: factorial 0 = 1 factorial 1 = 1 factorial n = n * (factorial (n - 1))
{ "language": "en", "url": "https://stackoverflow.com/questions/7603509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Painting checkbox icons in a custom JComponent :Scala I'm creating a custom scala component which needs an unchecked icon at (100,100) and checked icon at (200,100), the same icons used by swing. My code below works, but looks quite weird because I need to create dummy checkboxes. Is there a standard way to accomplish this ? ( No I'm not trying to add components to container etc etc...this is not a layout management problem...am trying to create a custom component ) val comp = new JComponent() { override def paintComponent(g:Graphics) { val cb1 = new JCheckBox() val cb2 = new JCheckBox() cb2.setSelected( true ) val icon = UIManager.getIcon("CheckBox.icon") icon.paintIcon( cb1, g, 100,100) icon.paintIcon( cb2, g, 200,100) } } val f = new JFrame f.getContentPane().setLayout( new BorderLayout ) f.getContentPane().add( comp , BorderLayout.CENTER ) f.pack f.show A: You shouldn't define components within paintComponent. Define them in the component's constructor so that they're not re-defined each time the component is redrawn. The standard thing to do if you don't want the user to change the values of checkboxes would be to use setEnabled(false). Also, have you tried using the scala.swing package?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mac OS X check if flash is installed My Mac OS X application opens a webpage via a WebView that requires flash. If the user does not have flash installed I would like to give them a popup telling them to please install flash. Is there a way to check the webview if the flash plugin is installed? In WebPreferences you can enable/disable PlugIns but I can't find a way to query the currently install/enabled ones. Thanks for any help. A: You may be able to write some JavaScript that does the checks and execute it through the WebView's window object. To do this you'll need to read up on JavaScript's navigator object, specifically navigator.plugins. A: * *You can check the installed Flash version via a shell command: /usr/libexec/PlistBuddy -c 'Print CFBundleVersion' /Library/Internet\ Plug-Ins/Flash\ Player.plugin/Contents/Info.plist *Apple has provided JavaScript code to detect plugins on a variety of browsers. If you include this file, the following can be used redirect either to the Flash site or to your popup: detectFlash("http://www.site.com/flashcontent","http://www.site.com/noflash") *Per @Brian Kyle's excellent suggestion, it is possible to check for Flash in navigator.plugins: var pluginCount = navigator.plugins.length; for(var i = 0; i < pluginCount; i++){ if(navigator.plugins[i].name=="Shockwave Flash") { document.write("Flash version " + navigator.plugins[i].version); break; }; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7603513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PHP Function Argument to an array Can you do something crazy like this function cool_function($pizza, $ice_cream) { make the arguments in the array into an array return $array_of_paramaters // my new array } // end function print_r(cool_function); // outputs array(0 => pizza, 1=> ice cream) A: Actually, this is pretty easy (and read the manual: func_get_args — Returns an array containing a function's argument list, see as well: Variable-length argument lists): function cool_function($pizza, $ice_cream) { return func_get_args(); } but as asked in comments, why do you need this? Or do you need the variable names? Reflection Docs is your friend: function cool_named($neutron, $electron) { $f = new ReflectionFunction(__FUNCTION__); $p = array(); foreach($f->getParameters() as $p1) $p[] = '$'.$p1->name; return $p; } var_dump(cool_named()); Or just both? (Edit: taking under-length, optional and over-length parameters into account): function overall($neutron, $electron, $quark = 'xiaro') { $f = new ReflectionFunction(__FUNCTION__); $defined = $f->getParameters(); $passed = func_get_args() + array_fill(0, count($defined), NULL); foreach($defined as &$param) $param = '$'.$param->name; return array_combine($defined + array_keys($passed), $passed); } var_dump(overall('clara', 'peter', 'moon', 'jupiter')); A: I'm not sure if you're looking for func_get_args which return all arguments passed to a function, or the ReflectionFunction class. A basic example of func_get_args: function cool_function($pizza, $ice_cream) { return func_get_args(); } But you don't need the arguments to make this work: function cool_function() { return func_get_args(); } // cool_function(1,2,3) will return array(1,2,3) The reflection option: /** * Returns an array of the names of this function */ function getMyArgNames($a,$b,$c) { $args = array(); $refFunc = new ReflectionFunction(__FUNCTION__); foreach( $refFunc->getParameters() as $param ){ $args[] = $param->name; } return $args; } Or, for the really crazy: /** * Returns an associative array of the names of this function mapped * to their values */ function getMyArgNames($a,$b,$c) { $received = func_get_args(); $i = 0; $args = array(); $refFunc = new ReflectionFunction(__FUNCTION__); foreach( $refFunc->getParameters() as $param ){ $args[$param->name] = $received[$i++]; } // include all of those random, optional arguments. while($i < count($received)) $args[] = $received[$i++]; return $args; } A: do you mean function valuesToArray($value1,$value2){return array($value1,$value2);} A: If I got you right, you so it like this: function cool_function($pizza, $ice_cream) { return array($pizza, $ice_cream); } but you could simply do that: $new_var = array($pizza, $ice_cream);
{ "language": "en", "url": "https://stackoverflow.com/questions/7603517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to populate SelectList for ViewModel on GET/POST I have the following ViewModel: public class EditViewModel { public int FooType { get; set; } public IEnumerable<SelectListItem> FooTypes { get; set; } } I originally populated it in my Edit action like so: public ActionResult Edit(int id) { EditViewModel model = new EditViewModel(); model.FooTypes = new SelectList(repository.GetFooTypes(), "Id", "Value"); return View(model); } When I created the action to POST the values I had to repeat the same code: public ActionResult Edit(int id, EditViewModel model) { if( !ModelState.IsValid ) { model.FooTypes = new SelectList(repository.GetFooTypes(), "Id", "Value"); return View(model); } return RedirectToAction("Index"); } I don't like having this code in two separate locations. Is there any common practice for refactoring this into a single spot so I dont need to repeat this code? A: Given that c# is an object oriented language, there are plenty of options available. The simplest would be to just wrap it in a method within the controller: private SelectList GetFooTypesList() { return new SelectList(repository.GetFooTypes(), "Id", "Value); } and call it when setting up your model or if you're using it in multiple classes you could create a helper method in another class that accepts the repository or an IEnumerable as a parameter. If you want to get really advanced, you could use a ModelFactory to create the FooType model for you, with a prepopulated FooType property so the controller doesn't need to worry about it at all. There's plenty of options, you just need to pick the one that's best for you. My personal preference is the simple helper method in the controller. A: I've done it in the model before (when it was the coding practice for that project team), but it depends on your philosophy on what's "business logic" and what's "data access", and what belongs in the model vs controller. Different, and justifiable, opinions exist. Model, where you need a nullable type for FooType: public class EditViewModel { public int? FooType { get; set; } public IEnumerable<SelectListItem> GetFooTypes(object selectedFooType = null) { return new SelectList(repository.GetFooTypes(), "Id", "Value", selectedFooType); } } "Get" controller, where you need to create the model first to ensure the Model property is available in the view: public ActionResult Edit(int id) { EditViewModel model = new EditViewModel(); return View(model); } The View (sans Barbara Wawa): @Html.DropDownListFor(m => m.FooType, Model.GetFooTypes(Model.FooType)) An alternative that takes the "view stuff" out of the model might look like so: Model: public class EditViewModel { public int? FooType { get; set; } public IEnumerable<int?> FooTypes { get { // declare/define repository in your model somewhere return repository.GetFooTypes(); } } } View: @Html.DropDownListFor(m => m.FooType, new SelectList(Model.FooTypes, "Id", "Value", Model.FooType)) A: In the reply by "nekno" (answered Sep 30 at 22:19), there are two alternatives of a ViewModel which either returns a 'IEnumerable<SelectListItem>' or a 'IEnumerable<int?>'. Both of these alternative uses a repository but without actually creating it, so I would like to extend the code example a little bit, and chooses the second alternative i.e. the class with the property typed 'IEnumerable<int?>' : using Microsoft.Practices.ServiceLocation; // ServiceLocator , http://commonservicelocator.codeplex.com/ using MyOwnRepositoryNameSpace; // IRepository public class EditViewModel { public int? FooType { get; set; } public IEnumerable<int?> FooTypes { get { return Repository.GetFooTypes(); } } private IRepository Repository { get { return ServiceLocator.Current.GetInstance<IRepository>(); } } } The above kind of code with a "Dependecy Lookup" is now using a dependency to a third-part library, in this case the Common Service Locator library. My question is how can the above code be replaced with "Dependency Injection" ? The ViewModel itself would indeed be very trivial to implement, just like this: using MyOwnRepositoryNameSpace; // IRepository public class EditViewModel { private readonly IRepository _repository; public EditViewModel(IRepository repository) { _repository = repository; } public int? FooType { get; set; } public IEnumerable<int?> FooTypes { get { return _repository.GetFooTypes(); } } } The problem is how to make the ViewModel become injected with an implementation, when the ASP.NET MVC framework will instantiate the 'EditViewModel' and send it as a parameter into an Action method such as tihs method signature: public ActionResult Edit(int id, EditViewModel model) { // How do we make the framework instantiate the above 'EditViewModel' with an implementation of 'IRepository' when the Action method is invoked ??? The official MVC tutorial does not seem to provide any nice solution as far I can see. In the section "Handling Edits" (methods 'public ActionResult Edit(...)' ) at the below pages they are duplicating the creation of the options in a similar way as in the poster of this stackoverflow question you are now reading. http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5 http://mvcmusicstore.codeplex.com/SourceControl/changeset/view/d9f25c5263ed#MvcMusicStore%2fControllers%2fStoreManagerController.cs If there is a solution about how to make the framework inject view model with your data retrievers (such as a repository) then I believe it may be to use some implementation of either 'IModelBinderProvider' or 'IModelBinder' but I have experimented with these without real success... So, can anyone provide a link to a complete working example with ASP.NET MVC 3 code that enables injection of a data retriever into the constructor of a view model that the framework instantiates and will send as parameter into an action method ? Update 2012-01-01: For those intrested in a solution to this specific question about constructor injection of a ViewModel instance, when the framework instantiates it and sends it as parameter to an MVC Action Method parameter, I have created a new question with a more specific subject, and thus hopefully more likely that someone with a solution will find it and post a good answer: Constructor injection of a View Model instance used as an Action method parameter
{ "language": "en", "url": "https://stackoverflow.com/questions/7603519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: API to access Google Profile on Android Google accounts come with a pretty nice profile already, and since all Android phones connect to that profile for most of the google services. I'd like to add an option to my application to simply register with my application using your google profile on the phone. Not only would I have access to information like email address, name, aliases, but also profile images people use on google services. Which Google API provides me access to that? Is there something in the Android API's that already provides this that I'm missing? I'm not just looking for authentication, as with OAUTH, but access to the profile information as well. Are there any existing libraries I can use? A: Turns out there is a way to get access to the google profile(s) the user has: http://code.google.com/p/google-api-java-client/wiki/AndroidAccountManager That's awesome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: strong-typed profile values in ASP.NET membership (MVC) I've been using ASP.NET MVC with membership-based login for several years and everything is working fine (it's now MVC3, but membership didn't change since the first version which was MVC1). Now I need to add a value into the profile (just one value, of very seldom use - so it doesn't warrant custom membership provider or custom tables) I got it working through profile.SetPropertyValue("myprop"), but I would really want to get profile.myprop to work. Is it possible? I saw some advise to have a custom class MyProfile : ProfileBase and have myprop as a property of that class. For some reason, casting ProfileBase.Create(currentUser.UserName) to MyProfile gives me an error (illegal cast). Is there an example somewhere of ASP MVC application with Profile, similar to this Old Post by ScottGu? A: Joel Spolsky had a great answer to this question on this post. You're basically on the right track. If you're getting the illegal cast error, its most likely due to a problem in the config file. Make sure this is included; more specifically the <profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile"> section. <profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile"> <providers> <clear /> <add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="sqlServerMembership" /> </providers> </profile>
{ "language": "en", "url": "https://stackoverflow.com/questions/7603527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: css make a dropdow appear under ajoining text: please see screenshot the client want something like this. I can manage the styling (corners and all) but i can't get the "dropdown" to drop under the text in the cell to the left. My html follows. Thanks in advance <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script> <script type="text/javascript"> $(document).ready(function () { $('div.outside').hide(); $('div.selector').click(function () { var hidden = $(this).parents('td').find('div.outside :hidden').length > 0; $('div.outside').hide(); if (hidden) { $(this).parents('td').find('div.outside').show().animate('slow'); } else { $(this).parents('td').find('div.outside').hide().animate('slow'); } }); }); </script> <style type="text/css"> ul.action { list-style-type: none; list-style-position: outside; padding: 0px; text-align: left; margin: 0px; } ul li { margin: 1px 0px 1px 0px; } div.content { border-style: solid; border-width: 1px; padding: 1px; white-space: nowrap; overflow: auto; } div.outside { width: 200px; position: absolute; z-index: 100; } div.top { width: 200px; } div.selector { cursor: pointer; padding: 1px 1px 0px 1px; float: right; border-style: solid; border-width: 1px; border-bottom-style: solid; top: 2px; position: relative; } .popup-dropdown { background-color: #FFFFE1; } thead td { font-weight: bold; width: 100px; } </style> <title></title> </head> <body> <table> <thead> <tr> <td> Name </td> <td> Rank </td> <td colspan="2" style="width: 20px;"> Style </td> </tr> </thead> <tr> <td> Jimmi Hendrix </td> <td> 1 </td> <td> Blues-Rock </td> <td style="width: 20px;"> <div class='top'> <div class='selector popup-dropdown'> X</div> </div> <div style='clear: both;'> </div> <div class='outside'> <div class='content popup-dropdown'> <ul class='action'> <li>Make God Status</li> <li>Elevate</li> <li>Respect</li> </ul> </div> </div> </td> </tr> <tr> <td> Carlos Santana </td> <td> 2 </td> <td> Blues-Rock </td> <td style="width: 20px;"> <div class='top'> <div class='selector popup-dropdown'> X</div> </div> <div style='clear: both;'> </div> <div class='outside'> <div class='content popup-dropdown'> <ul class='action'> <li>Make God Status</li> <li>Elevate</li> <li>Respect</li> </ul> </div> </div> </td> </tr> </table> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vulputate pulvinar nisi vel tincidunt. Mauris eget pulvinar enim. Suspendisse vitae turpis id orci porttitor auctor nec ut nisi. Nunc euismod. </div> </body> </html> A: Alright. Correct me if I misunderstood, but I think you wanted to just basically get rid of that gap next to the 'X' and have the right edge of the popup aligned with the right edge of the 'X' box. You can accomplish this with absolute positioning. I've made changes to the fiddle here: http://jsfiddle.net/F5bn4/2 I changed the inline style on the tds and I changed 200px to 20px on div.top
{ "language": "en", "url": "https://stackoverflow.com/questions/7603533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: js option to emulate overflow: scroll on handhelds with keyboard support? I have a need to create a part of a mobile web page that can scroll on its own (even though I tend to disagree with that being a good thing on mobile). The standard method is to set it to overflow: scroll and there you go. Alas, on iOS one needs to use two fingers to scroll that area which many still feel is unintuitive. This will be fixed in iOS5, but until then, I need to support it with one touch. So I found a few JS options. One is Scrollability. The catch is that it only supports iOS. In addition to iOS I need to support android, BlackBerry OS6 and Nokia. So that one is out. I then tried iScroll. This works pretty well. The catch, for me, is that it does this through pure JS in that you never see a native scrollbar. As such, the scrollbar it generates is more of a dummy in that there's no way to make it work with a mouse or keyboard. So, the question: Is anyone aware of a JS solution for creating a scrolling div on a mobile web page that a) allows for one-touch scrolling on touch devices and b) uses a native scroll bar to enable keyboard devices? If there isn't one, we can revert to device detection, giving touch devices the JS and keyboard devices the scrollbar...though that still leaves us the issue of some touch devices also having keyboards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple mobile platform game development (Android/iOS) I'm currently developing a small indie game for the Android framework, however in order to save my some future work - I was wondering, is there a way to develop a game for the Android and iOS at the same time? I'm aware of HTML 5 solutions, but I'm unsure if you can use them in order to develop games. My requirements: * 2D Graphics with animations * Play sounds (music/sfx) * Touch gestures (click, drag, pinch, etc) Any suggestions? A: Check out Corona SDK. They offer exactly what you are looking for - 2D graphics, animations, physics engine, touch, sounds; and they offer it as a cross-platform solution for both iOS and Android. The engine is OpenGL based, and they use Lua as a language. The main drawback is that it costs $200 per platform, or $350 if you want support for both. However, you need the subscription only when you actually get to publishing your game; you can use it for free locally to build for your own device. A: You may also want to check Gideros Studio, which includes * *Box2D physics engine *OpenAL sound system *Plugins (native code support) *Instant testing on the phone (no compile needed) *Tweening *Movieclips *Sprites & sprite sheets *Analytics *Ad support Using Gideros Studio is free, and you can develop for both Android and iOS at the same time with native (OpenGL rendered) functions. A: I suggest writing your main game engine code in C++ because Android supports that with the NDK: http://developer.android.com/sdk/ndk/overview.html And iPhone has Objective-C++ which is explained pretty well here: How well is Objective-C++ supported? You're fortunate enough that both platforms use OpenGL ES, so not much will be required to port that over. The only differences at this point will be sound, touching, file management, etc. (anything in the APIs).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PostgreSql Integer out of range error when inserting small numbers into integer fields I'm getting an "integer out of range" error in postgres, though none of the numbers inserted are 'big'. They are well under a million. The query is generated via the Django ORM, and is pretty standard looking. Any idea what I'm missing here? Thanks! # INSERT INTO "index_index" ("word_id", "ad_id", "field", "position", "created_at") VALUES (98036, 703906, E'y.x', 0, E'2011-09-29 22:02:40.252332') RETURNING "index_index"."id"; ERROR: integer out of range # \d index_index; Table "public.index_index" Column | Type | Modifiers ------------+--------------------------+---------------------------------------------------------- id | integer | not null default nextval('index_index_id_seq'::regclass) word_id | integer | not null ad_id | integer | not null field | character varying(50) | not null position | integer | not null created_at | timestamp with time zone | not null Indexes: "index_index_pkey" PRIMARY KEY, btree (id) "index_index_ad_id" btree (ad_id) "index_index_word_id" btree (word_id) Foreign-key constraints: "index_index_ad_id_fkey" FOREIGN KEY (ad_id) REFERENCES campaigns_ad(id) DEFERRABLE INITIALLY DEFERRED "index_index_word_id_fkey" FOREIGN KEY (word_id) REFERENCES index_word(id) DEFERRABLE INITIALLY DEFERRED A: Maybe the sequence has exceeded the max. value for an integer (2147483647). As a sequence is based on a bigint, this is possible. You can test that using SELECT nextval('index_index_id_seq')
{ "language": "en", "url": "https://stackoverflow.com/questions/7603540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# SQL To Linq - Where Clause with multiple variables Comparison (var1+var2) !=(var1+var2) I have these working in sql for large data set working great. However I'm having hard time converting to linq-I'm new to linq Select * from table1 t1, table2 t2 where (t1.RoleId+t1.UserId)!=(t2.RoleId+t2.UserId). On a side note, when the two variables are separated, I get undesired results. Meaning the following: where (t1.RoleId != t2.RoleId && t1.UserId != t2.UserId) In c# I have two anonymous lists. The last linq statement works great till nulls come into the picture. Nothing returns. I even thought of using a left join with no success. So how would you tackle the above query with anonymous type lists? Linq statments I have so far var roleUserList = ( from rls in roleResouceList join user in userResourceList on rls.FullResource.ToUpper() equals user.FullResource.ToUpper() orderby rls.RoleID, user.UserID, rls.Res1, rls.Res2, rls.Res3 select new { RoleID = rls.RoleID, UserID = user.UserID, ServerId = rls.ServerID, FullResource = rls.FullResource, RlsRes1 = rls.Res1, RlsRes2 = rls.Res2, RlsRes3 = rls.Res3 }).Distinct().ToList(); var missingRoleUserList = ( from rls in rlsCount join usr in usrCount on rls.Res1 equals usr.Res1 where rls.Total > usr.Total select new { UserID = usr.UsrID, RoleID = rls.RoleID }).Distinct().ToList(); List<string> outputRoleUserList = ( from rls in roleUserList from mis in missingRoleUserList where (rls.RoleID + rls.UserID) != (mis.RoleID +mis.UserID) select rls.UserID + ",\"" + rls.RoleID ).DefaultIfEmpty().Distinct().ToList(); A: I'm not entirely certain that this is what you're looking for, but I'm going to give it a shot: Try chaining your where clauses in Linq to SQL, and you may get a better result: List<string> outputRoleUserList = from rls in roleUserList from mis in missingRoleUserList where rls.RoleID != mis.RoleID where rls.UserID != mis.UserID select rls.UserID + ",\"" + rls.RoleID This will actually generate SQL as follows: rls.RoleId != mis.UserID AND rls.UserId != mis.UserID However, you have already forced execution on roleUserList and missingRoleUserList, so what you're using in the third Linq statement is not really Linq to SQL but rather Linq to Objects, if I'm reading this correctly. I'd be curious to see some additional information or clarification and then maybe I'll understand better what's going on! EDIT: I realized another possibility, it's possible that the object.UserID or object.RoleID is throwing an internal NullPointerException and failing out because one of those values came back null. You could possibly solve this with the following: List<string> outputRoleUserLIst2=roleUserList .Where(x => x != null && x.UserID != null && x.RoleID != null && missingRoleUserList .Where(y => y != null && y.UserID != null && y.RoleID != null && y.RoleID!=x.RoleID && y.UserID!=x.UserID) .FirstOrDefault()!=null) .Select(x => x.UserID + ",\"" + x.RoleID).Distinct().ToList(); This is not pretty, and this is the other Linq syntax (with which I am more comfortable) but hopefully you understand what I am going for here. I'd be curious to know what would happen if you dropped this into your program (If I've guessed all of your meanings correctly!). I'll look back in a bit to see if you have added any information!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to import a certificate to a key container in usb token? I have a problem, I am currently working in a project PKI, I must to create a module to renewal certificate using exits public/private key pair . I can get information about key container from usb token but i don't know how to import new certificate created using same public/private keypair like old certificate? Can every tell me how can i achieve this using CryptoAPI?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delayed Chained Payments in PayPal with initially-unknown Secondary Receiver Reading through PayPal's API documents I don't see a clear way to do this, but I don't want to assume that it's impossible because I don't know how to do it. Use case: I'm building a marketplace for a client that allows a consumer to purchase a commodity service, then we find a provider to fulfill that service. (specifics are omitted for confidentiality and irrelevancy) The problem: At the time of purchase the provider is unknown, but we want to authorize payment when the consumer buys the service (and trigger payment after fulfilled). From PayPal's Adaptive Payments API I see it's possible to create a Delayed Chained Payment (which is great), but the secondary receiver must be declared when created. That's not possible because we don't yet know who's going to fulfill the consumer's request. One somewhat naive solution is to have the consumer pay us directly, then we trigger a secondary transaction between us and the provider. This isn't great because it incurs double the transaction fees. Is there another way to accomplish this with PayPal? Is there another payment provider that might be a better fit? Thanks!! A: The Permissions API should allow you to setup the payment on behalf of the buyer at a later time, when all parties are known. A: If the secondary receiver is unknown - probably the best way to implement this is to obtain a Preapproval from the user and then use it to pay the secondary receiver in the future. Here is how you can do it: https://developer.paypal.com/docs/classic/adaptive-payments/ht_ap-basicPreapproval-curl-etc/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jquery: what happens when you pass a deferred object into "then"? I have been researching jquery deferred objects for a while now and I'm stumped on one thing. The "done," "always," "then," etc methods take, as their arguments, functions which should be called when the deferred object is resolved. However I tried chaining requests by passing a deferred object into the "always" method, and that seems to work too: // A is an array of data var req = ajax(url + "?d=" + A[0]).done(processResults).fail(reportFailure); for (var i = 1 ; i < A.length ; i++) { var tmp = ajax(url + "?d=" + A[i]).done(processResults).fail(reportFailure); req.always(tmp); req = tmp; } However, it doesn't really work. Because when I follow the above code with this: req.always(foobar); foobar seems to get called at some random time, not necessarily after the last element in the array is processed. Would it be better to use when? // A is an array of data var req = $.when(ajax(url + "?d=" + A[0]).done(processResults).fail(reportFailure)); for (var i = 1 ; i < A.length ; i++) { req = $.when(req, ajax(url + "?d=" + A[i]).done(processResults).fail(reportFailure)); } req.always(foobar); Would the above code (using "when") result in the ajax requests happening one after the other, or would they occur simultaneously? I looked into chaining with "pipe" by the way, but because of scoping issues I think it would be harder to use "pipe" with a for loop as above. Also, why does the original code "almost work"? What is happening there? Is it executing the deferred object as if it were a function, and what happens when it does that? A: You should build an array and use javascript apply : //create an array of one deferred per element var requests = $.map(A, function(index, a){return= $.ajax(url + "?d=" + a);}); //merge all deferreds into a single one var mergedRequest = $.when.apply(null, requests); mergedRequest.done(function(res0, res1, ...){ //your code goes here //if you want results as an array just use arguments arguments.length == A.length; }); EDIT: If you want your calls to be made serially do : var result = $.ajax(url + "?d=" + A[0]); for (var i = 1 ; i < A.length ; i++) { result = result.pipe(function() { return $.ajax(url + "?d=" + a[i]); } } result.done(processResults).fail(reportFailure);
{ "language": "en", "url": "https://stackoverflow.com/questions/7603556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to create a vector of cell arrays I want to store all the contents like name and marks for 30 students. I am keeping the information of name and marks together in a cell array. But to compare 2 students I need to store the cell arrays in a vector of 30 elements so that I can access later. A: I would recommend using an array of structs. For example students(1) = struct('name','Andrew', 'mark',90); students(2) = struct('name','Betty', 'mark',92); students(3) = struct('name','Charles', 'mark',88); You can then simply refer to them by indexing as student(n). You can also get and set their specific fields such as someName = student(2).name or student(1).mark = 98. A: Is it a 2D cell array that you want: students = cell(30, 2); students{1,1} = 'Andrew'; students{1,2} = 90; % or students(2,:) = {'Becky' 92}; % etc Or a cell array of cell arrays? students = cell(30, 1); students{1}{1} = 'Andrew'; students{1}{2} = 90; % or students{2} = {'Becky' 92}; % etc In any case, I strongly recommend using an array of structures, as suggested by @Phonon. Alternatively, you can use an array of objects. Check out the object-oriented programming information in the MATLAB help. A: Say you had the following: names = {'Andrew'; 'Betty'; 'Charles'} marks = [90; 92; 88] I suspect you tried this: >> C = {names marks} C = {3x1 cell} [3x1 double] Basically it creates a 1x2 cellarray (vector). You can access the values for a student as: C{1}{3} and C{2}(3). A more convenient form is to create a 3x2 cellarray (matrix): >> C = [names num2cell(marks)] C = 'Andrew' [90] 'Betty' [92] 'Charles' [88] which is easier to manipulate. For example if you want to extract the first and last students for comparison: C([1 end],:) You can do things like sort by grade or by name: [~,idx] = sort(marks); C(idx,:)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# equivalent to toSource() of javascript Possible Duplicate: Can I convert a C# string value to an escaped string literal How I can show the contents of a string in 'pure mode',including \r,\n,\t etc.. equivalent to .toSource() method of javascript For example: JavaScript: var str = "foo\nbaa\ttest"; console.log(str.toSource()); Output: (new String("foo\nbaa\ttest")) it is possible do this in C#? Thanks in advance! A: See the answer to Can I convert a C# string value to an escaped string literal . He wrote this extension method that does exactly what you're wanting: static string ToLiteral(string input) { var writer = new StringWriter(); CSharpCodeProvider provider = new CSharpCodeProvider(); provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null); return writer.GetStringBuilder().ToString(); } A: Regex.Escape("foo\nbaa\ttest") A: Looking at the general problem - reconstructing some source code - there is no language option on C# that would let you do it automagically. However (this is theory on my part) you should be able to use expressions to get to the IL equivalent (using the Reflection.Emit or Mono.Cecil libraries perhaps). You could I suspect then use the libraries from the ILSpy project to reconstruct the C#.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cakephp dropdown selected value not coming correctly in firefox when a page is refreshed I'm having error in setting up a drop down selected value returned from a controller in firefox only.. Im using cakephp 1.3. It comes right when i first time load the pages but if i change the drop down value and refresh the page the value doesnt changed. It should be the one coming from controller. But when i press ctrl+f5 the right value is showed up. I guess it is something to do with the browser cache. Im not having this problem in google chrome. im setting the value of the dropdown with selected value using this code echo $this->Form->input('to_country_code',array( 'options'=>$countries, 'id'=>'to_country_code', 'label' => __('Country',true), //'selected'=>$selectedCountryCode 'div' => false, 'default'=>$selectedToCountryCode ) ); Any answers would be highly appreciated. A: This is something particular to Firefox, not CakePHP. It caches some of the form data unless you hard refresh. A: Firefox will retain your form values when you refresh the page, no doubt it will reflect the changes. Its only to help users for not to loose the input which is already entered. But if you click on the address bar and press enter then entire page will be loaded with initial values. Its not a Cakephp issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP MySQL Multi-statement works on my webpage but not on XAMPP So I use this code to connect to MySQL and execute multiple statements: $connect=@mysql_connect($host,$user,$pass,false,65536) or die("Can't connect"); mysql_select_db($base,$connect); When connected I do: mysql_query("CREATE TABLE IF NOT EXISTS tablename ...;\nINSERT INTO tablename ...;"); I use this code to execute backup files containing the same code above (\n=new line). When I run this script on my webpage (hosted server) it works but on my local computer where I use XAMPP it shows an error : 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 'INSERT INTO tablename' at line 2 I have checked php.ini and I have safe_mode = Off and sql.safe_mode = Off too. Any ideas what am I missing? A: According to the PHP manual, mysql_query does not support multiple queries. However, in the comments there's a guy stating that it it possible: However, multiple queries seem to be supported. You just have to pass flag 65536 as mysql_connect's 5 parameter (client_flags). (Source) On the other hand, manual only mentions two parameters to the function, so I wonder what we are supposed to pass as the 3rd and 4th parameters if that 5th one really does the trick!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Obtaining Google Maps API key I'm using Windows 7. I have tried several times with the debug.keystore with appears in c:\users\YOURUSER.android\ using the command: keytool -list -alias androiddebugkey -keystore c:\Users\YOURUSER\.android\debug.keystore -storepass android -keypass android It gives me a MD5, but then I go to Google MD5 registration page and it sais it is not a valid fingerprint. I searched for more information, and I finally created a new debug.keystore into c:\users\YOURUSER\ to avoid rewriting the original one. I used this command: keytool -genkey -keypass android -keystore c:\users\YOURUSER\debug.keystore -alias androiddebugkey -storepass android -validity 10000 -dname "CN=Android Debug,O=Android,C=US" It works, so I use the previous command to get the MD5, and it gives me a new MD5. Then I go to Google again and the same problem: "not a valid fingerprint". The I made a second attempt. This is what I did then: 1) Opened a Windows7 terminal, went to c:\program files\java\jdk1.7.0\bin\ 2) Wrote command: keytool -genkey -v -keystore c:\eclipse\my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000 3) Then I tried to get the MD5 code from my keystore, using comand: keytool -list -alias alias_name -keystore c:\eclipse\my-release-key.keystore and writing the password I am asked. It gives me a MD5. 4) I go to maps api key sign up and write the MD5. "FINGERPRINT NOT VALID" I don't know what the problem is. And I am supposed to do this for every app I program? What a headache! Can anybody help me please? A: Are you sure you get the MD5 and not the SHA1 fingerprint? Tryed the -v option? see: How can I get the MD5 fingerprint from Java's keytool, not only SHA-1? A: google maps has deprecated its previous version API v1 and introduced a new version of google maps API v2. previously we generated md5 key but now we need to generate sha-1 fingerprint certificate. The Maps API key is based on a short form of your application's digital certificate, known as its SHA-1 fingerprint. The fingerprint is a unique text string generated from the commonly-used SHA-1 hashing algorithm. Because the fingerprint is itself unique, Google Maps uses it as a way to identify your application. please go through the links it could help you https://developers.google.com/maps/documentation/android/start#the_google_maps_api_key https://developers.google.com/maps/documentation/android/intro#sample_code also see the same kind of post in stack over flow How to implement Google Maps new version of API v2 A: * *In command line you need to open Java-> jdk-> bin as for me it is "C:\Program Files\Java\jdk1.7.0_03\bin" *There is "keytool" program which u need. In command line enter "cd C:\Program Files\Java\jdk1.7.0_03\bin" *And enter "keytool -list -v -keystore C:\Users\John\.android\debug.keystore" So the final string in command line must look like: "C:\Program Files\Java\jdk1.7.0_03\bin>keytool -list -v -keystore C:\Users\John\.android\debug.keystore". Whare usually u need only to change the name "John" There will be SHA-1, MD5, etc Finally, go to Google Access API google access api
{ "language": "en", "url": "https://stackoverflow.com/questions/7603577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: array amplitude through a php function I have this question, which I need to solve, help needed please. A non-empty zero-indexed array A consisting of N integers is given. The amplitude of this array is defined as the largest possible difference between two of its elements, i.e.: amplitude(A) = max{ A[P] − A[Q] : 0 ≤ P, Q < N } Write a function function amplitude($A); that, given a non-empty zero-indexed array A consisting of N integers, returns its amplitude. Assume that: N is an integer within the range [1..1,000,000]; each element of array A is an integer within the range [0..5,000,000]. For example, given array A such that A[0] = 10 A[1] = 2 A[2] = 44 A[3] = 15 A[4] = 39 A[5] = 20 the function should return 42. Complexity: expected worst-case time complexity is O(N); expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified. A: you just go through the array. you start with a max value and a min value. than, for each element, if it's larger than max, update max, if it's lower than min, update min. at the end you just do the difference between computed max and min. this will take only one walk through the array so it's O(N) function amplitude(array $A) { return max($A) - min($A); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: qt hiding a control on showEvent() I call show() on a window and it has several controls and all controls are displayed. One of the controls is a custom control that inherits from QFrame. I want to hide this control if a particular flag is set. So, I have void MyCustomControl::showEvent ( QShowEvent * /* evt */ ) { if (!m_visibleAllowed) hide(); } While this hides the control, it makes the control goofy; it looks frozen. When the window is resized, the area where the control is supposed to be does not get refreshed. Searching around forums, the idea that I get is that hiding the control is not supposed to be done on showEvent() is that true? if so then how/where should I try to hide the control. If hiding the control from showEvent() is possible, how can I prevent the control getting frozen. Thanks for you time. A: If the problem is with calling hide() during your show event (I can't confirm that it's explicitly disallowed, but it doesn't sound like a good idea in general) and calling hide from your show event is where you really need to have this code then you could use a single shot timer: QTimer::singleShot( 0, this, SLOT(hide()) ); which will simply defer the execution of the hide() function until the next round of the event loop. A: Maybe you could use a QStackedLayout or a QStackedWidget that has two widgets in the stack: your control, and a "blank" QWidget. If you did that, instead of using show() and hide() on your control, you switch what's on top of the stack. That way you never try to render a hidden widget - if your control isn't visible, you render the blank QWidget instead - and I suspect this will solve your graphics glitches. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby C extension not resolving 3rd party dlls at runtime I have a Ruby C extension that is providing a ruby interface to use a third part C library. I am able to build the library, let's call it something.so just fine. However, it's compiled against the third party .lib and .dll files dynamically. When I actually try to run a ruby script that has require 'something' it fails. Ruby doesn't know how to find the DLLs the something.so was linked against. It gives me an error like: --------------------------- ruby.exe - System Error --------------------------- The program can't start because SomeThirdParty.dll is missing from your computer. Try reinstalling the program to fix this problem. --------------------------- OK --------------------------- What do I need to do to tell ruby how to find this dll? If I put all the third party dlls in the same directory as the ruby script I'm running it works, but I'd rather not do that. A: Just put it in a place that is inside your PATH. A good place may be the ruby\bin directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UDP File Transfer - Yes, UDP I have a requirement to create a UDP file transfer system. I know TCP is guaranteed and much more reliable, but I need to transfer huge files between locations and I think the speed advantage in this project outweighs the benefits using TCP. I’m just starting this project, but would like some guidance if anyone has done this before. I will be writing both sides (client and server) so I don’t need to worry about feature limitations in other products. In a nutshell I need to: * *Take large files and send them in chunks *Be able to throttle bandwidth from the client *Create some kind of packet numbering system for errors, retransmitions and assembling files by chunk on server (yes, all the stuff we get from TCP for free :-) *Configurable datagram size – I think some firewalls complain if they get too big? *Anything else I may be missing I’m starting this journey using UdpClient and would like to write this app in C#. Any words of wisdom (other than to use TCP)? It’s been done with huge success. We used to use RocketStream.com, but they sold their product to another company for internal use only. We typically get speeds that are 30X faster than FTP or raw TCP byte transfers. A: in regards to Configurable datagram size – I think some firewalls complain if they get too big? one datagram could be up to 65,536 bytes. cosidering all the ip header information you'll end up with 65,507 bytes for payload. but you have to consider how all devices are configured along you network path. typically most devices have set an MTU-size of 1500 bytes so this will be typically your limit "on the internet". if you set up a dedicated network between your locations you can increase your MTU an all devices. further in regards to Create some kind of packet numbering system for errors, retransmitions and assembling files by chunk on server (yes, all the stuff we get from TCP for free :-) i think the best thing in your case would be to implement a application level protocol. like 32 byte sequence number 8 byte crc32 checksum (correct me on the bytesize) any bytes left can be used for data hope this gives you some bit of a direction ::edit:: from experience i can tell you UDP is about 10-15% faster than TCP on dedicated and UDP-tuned networks. A: I'm not convinced the speed gain will be tremendous, but an interesting experiment. Such a protocol will look and behave more like one of the traditional modem based protocols, and probably ZModem is one of the better examples to get some inspiration from (implements an ack window, adaptive block size, etc). There are already some people who tried this, check out this site. A: That would be cool if you succeed. Don't go in it without WireShark. You'll need it. For the algorithm, I guess that you have pretty much the idea of how to start. Maybe some pointers: * *start with MTU that will be common to both endpoints, and use packets of only that size, so you'll have control over packet fragmentation (when you come down from TCP, I hope that this is for the more control over low level stuff). *you'll probably want to look into STUN or TURN for punching the holes into NATs. *look into ZModem - that also has a nostalgic value :) *since you want to squeeze maximum from you link, try to put as much as you can in the 'control packets' so you don't waste a single byte. *I wouldn't use any CRC on packet level, because I guess that networks underneath are handling that stuff. A: I just had an idea... * *break up a file in 16k chunks (length is arbitrary) *create HASH of each chunk *transmit all hashes of the chunks, using any protocol *at receiving end, prepare by hashing everything you have on your hard drive, network, I mean everything, in 16k chunks *compare received hashes to your local hashes and reconstruct the data you have *download the rest using any protocol I know that I'm 6 months behind the schedule, but I just couldn't resist. A: Others have said more interesting things, but I would like to point out that you need to make sure you use a good compression algorithm. That will make a world of difference. Also I would recommend validating your assumptions as to the speed improvement possibility, make a trivial system of sending data (not worrying about loss, corruption, or other problems) and see what bandwidth you get. This will at least give you a realistic upper bound for what can be done. Finally consider why you are taking on this task? Will the speed gains be worth it after the amount of time spent developing it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Django norel access to different nosql at the same time? i'm new to the nosql world, and from forums and articles that i've read: most of users try to "mix" nosql tools, for example, they use Cassandra and MongoDB together to make a "powerful system", because am beginning with MongoDB, i've downloaded the DjanMon project (am a django fan ^_^ ), of course i've downloaded the special version of django that accepts the NoSql use: Django NonRel, and i've noticed that the Setting file dont "oblige" you to use one specific NoSql solution like in Django with RDBMS where you must specify MySql or PostegreSql or other solution, so, is it possible to mix lot of (or two of course) NoSql solution using Django (for example MongoDB+Cassandra)? A: There's nothing to stop you using multiple storage solutions, whether SQL or NoSQL - but the NoSQL solutions all have different architectures, data models and APIs (For example, MongoDB is a document-oriented database, whereas Cassandra is Column-oriented), so you can't usually swap one for another without some effort. Can you clarify what you are actually trying to achieve? I.e. why are you interested in mixing these two specific solutions?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Draw on the screen, C# I seek a C# method that can print data on the screen 'externally'. Basically, I have an DX9 application, and I want to 'paint on it.'. I tried the Graphics.FromHwnd(0); method, but its flickering and its not as good as I want it to be. I know theres a lot of application like Skype that can draw on the monitor, 'above' all other applications, but I can't understand how to do it programically. I will be very greatful if you could help me. Mark A: Just create a form whose form.TopMost=true You may want to create a transparent form so that the form itself is invisible. You may even want to create a non-rectangular form. A: Sometimes overriding the OnBackgroundPaint event will produce fewer flickers. You might want to try that. Otherwise, I don't know what your code is doing to cause the flickers in the first place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Start eclipse with no plugins? I installed the Aptana eclipse plugin and restarted and now my eclipse (Indigo) won't start up. As soon as I load it, it freezes - I waited for 15 min and tried several times and no success. I also tried starting up eclipse with the -clean command and same thing. How do I startup eclipse with no plugins loaded? I'd like to be able to do that so I can get back in and hopefully uninstall the Aptana through the eclipse UI. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7603605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to implement Uniform LBP? Possible Duplicate: Local Binary Pattern in MATLAB I would like to implement uniform LBP. This is the definiton given by wikipedia for uniform LBP. A local binary pattern is called uniform if the binary pattern contains at most two bitwise transitions from 0 to 1 or vice versa when the bit pattern is traversed circularly. For example, the patterns 00000000 (0 transitions), 01110000 (2 transitions) and 11001111 (2 transitions) are uniform whereas the patterns 11001001 (4 transitions) and 01010010 (6 transitions) are not. In the computation of the LBP labels, uniform patterns are used so that there is a separate label for each uniform pattern and all the non-uniform patterns are labeled with a single label. For example, when using (8,R) neighborhood, there are a total of 256 patterns, 58 of which are uniform, which yields in 59 different labels. I have written code for LBP but not sure how to convert it to a uniform LBP. Below is the code for LBP. for i=2:m-1 for j=2:n-1 J0=I2(i,j); I3(i-1,j-1)=I2(i-1,j-1)>J0; I3(i-1,j)=I2(i-1,j)>J0; I3(i-1,j+1)=I2(i-1,j+1)>J0; I3(i,j+1)=I2(i,j+1)>J0; I3(i+1,j+1)=I2(i+1,j+1)>J0; I3(i+1,j)=I2(i+1,j)>J0; I3(i+1,j-1)=I2(i+1,j-1)>J0; I3(i,j-1)=I2(i,j-1)>J0; LBP(i,j)=I3(i-1,j-1)*2^7+I3(i-1,j)*2^6+I3(i-1,j+1)*2^5+I3(i,j+1)*2^4+I3(i+1,j+1)*2^3+I3(i+1,j)*2^2+I3(i+1,j-1)*2^1+I3(i,j-1)*2^0; end end figure,imshow(uint8(LBP)) Any help would be appreciated. I am using MATLAB. A: Steps * *Your next step is to construct a lookup table for the values that are stored into LBP. * *The lookup table maps the 256 possible combinations into 59 different labels. *If speed is not important, the table can be built with a for-loop. *Map LBP into the 59 labels using the table. * *labeled = table(LBP) % this is called table lookup or MATLAB indexing. *Perform any additional work with those 59 labels. Suggestions (although not necessary for implementation) * *There is no need to use a 2D matrix for I3. The eight neighbors of the current pixel are local to the current pixel you are processing; therefore you can simply assign them to I3(1), I3(2), ... I3(8) because they will be reassigned each time you move on to the next center pixel (i,j). function table = BitwiseToLBP % we reserve label 0 for non-uniform table = zeros(1, 256); nextLabel = 1; for k = 1:256, bits = bitand(k, 2.^(0:7)) > 0; if IsUniformLBP(bits), table(k) = nextLabel; nextLabel = nextLabel + 1; else table(k) = 0; end end end function IsUniformLBP(bits) nnz(diff(bits([1:end, 1]))) == 2; end A: I tried this code: sum = abs(I3(k-1,l-1)-I3(k-1,l))+ abs(I3(k-1,l)-I3(k-1,l+1))+ abs(I3(k-1,l+1)-I3(k,l+1))+ abs(I3(k,l+1)-I3(k+1,l+1))+abs(I3(k+1,l+1)-I3(k+1,l))+abs(I3(k+1,l)-I3(k+1,l-1))+abs(I3(k+1,l-1)-I3(k,l-1)); if(sum <=2) UniformHist = [UniformHist Hist]; end
{ "language": "en", "url": "https://stackoverflow.com/questions/7603608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MPMoviePlayerController prepareToPlay not working with HTTP Live Streaming I'm trying to play an HTTP live streaming video using a MPMoviePlayerController object, inside a modal view controller. If I run the code like this, everything works fine. I get a MPMoviePlaybackStatePlaying notification, and the video plays. - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil]; NSURL *url = [NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"]; self.moviePlayerController = [[[MPMoviePlayerController alloc] initWithContentURL:url] autorelease]; self.moviePlayerController.view.frame = CGRectMake(0,0,320,416); self.moviePlayerController.controlStyle = MPMovieControlStyleNone; self.moviePlayerController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self.view addSubview:self.moviePlayerController.view]; self.moviePlayerController.fullscreen = NO; [self.moviePlayerController play]; } I would prefer to use the prepareToPlay method, so that I can show a loading indicator, and for a nicer experience. However, I don't seem to be able to get this working. No MPMoviePlayerPlaybackStateDidChangeNotification ever gets called, and the stream doesn't play. The activity indicator just sits there spinning forever. I've confirmed that prepareToPlay does get called, but nothing else seems to happen after that. I've also confirmed that this code works fine with a local movie file. It just seems to be with HTTP Live Streaming which fails. Can anyone see what I'm doing wrong? - (void)viewDidLoad { [super viewDidLoad]; [self.activityIndicator startAnimating]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil]; NSURL *url = [NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"]; self.moviePlayerController = [[[MPMoviePlayerController alloc] initWithContentURL:url] autorelease]; [self registerForMovieNotifications]; } - (void)registerForMovieNotifications { //movie is ready to play notifications if ([self.moviePlayerController respondsToSelector:@selector(loadState)]) { //this is a 3.2+ device [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadStateChanged:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; self.moviePlayerController.movieSourceType = MPMovieSourceTypeStreaming; [self.moviePlayerController prepareToPlay]; } else { //pre-3.2 device [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePreloadDidFinish:) name:MPMoviePlayerContentPreloadDidFinishNotification object:nil]; } //movie has finished notification [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayBackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; } - (void) moviePlayerPlaybackStateDidChange:(NSNotification*)notification { NSLog(@"playbackDidChanged"); MPMoviePlayerController *moviePlayer = notification.object; MPMoviePlaybackState playbackState = moviePlayer.playbackState; if(playbackState == MPMoviePlaybackStateStopped) { NSLog(@"MPMoviePlaybackStateStopped"); } else if(playbackState == MPMoviePlaybackStatePlaying) { NSLog(@"MPMoviePlaybackStatePlaying"); } else if(playbackState == MPMoviePlaybackStatePaused) { NSLog(@"MPMoviePlaybackStatePaused"); } else if(playbackState == MPMoviePlaybackStateInterrupted) { NSLog(@"MPMoviePlaybackStateInterrupted"); } else if(playbackState == MPMoviePlaybackStateSeekingForward) { NSLog(@"MPMoviePlaybackStateSeekingForward"); } else if(playbackState == MPMoviePlaybackStateSeekingBackward) { NSLog(@"MPMoviePlaybackStateSeekingBackward"); } } //3.2+ devices - (void)moviePlayerLoadStateChanged:(NSNotification*)notification { NSLog(@"load state changed"); //unless state is unknown, start playback if ([self.moviePlayerController loadState] != MPMovieLoadStateUnknown) { [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; self.moviePlayerController.view.frame = CGRectMake(0,0,320,416); self.moviePlayerController.controlStyle = MPMovieControlStyleNone; self.moviePlayerController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self.view addSubview:self.moviePlayerController.view]; self.moviePlayerController.fullscreen = NO; [self.moviePlayerController play]; } } //pre 3.2 devices - (void) moviePreloadDidFinish:(NSNotification*)notification { // Remove observer [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerContentPreloadDidFinishNotification object:nil]; [self.moviePlayerController play]; } A: I don't know why, but I was able to solve this by moving the line self.moviePlayerController.controlStyle = MPMovieControlStyleNone; out of the moviePlayerLoadStateChanged: method, and into the viewDidLoad method. Anyone have any ideas why this made a difference?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Controlling window position of a Powershell console This works: (Get-Host).UI.RawUI $a = (Get-Host).UI.RawUI $a.BackgroundColor = "white" $a.ForegroundColor = "black" $size = (Get-Host).UI.RawUI.WindowSize $size.Width = 80 $size.Height = 30 (Get-Host).UI.RawUI.WindowSize = $size But this doesn't work, and I am not sure how to make it work: $position = (Get-Host).UI.RawUI.Windowposition $position.X = 0 $position.Y = 30 (Get-Host).UI.RawUI.Windowposition = $position The error I get is strange. It complains about "buffer" when I am trying to set external window position: Exception setting "WindowPosition": "Cannot use the specified Window X (column) position because it extends past the width of the screen buffer. Specify another X position, starting with 0 as the left most column of the buffer. A: The error is not really strange, because WindowPosition Gets and sets the position, in characters, of the view window relative to the screen buffer. It does not set the position of the Window, but to put it crudely, the position in the buffer that you see through the view of the window. So in your case, you are getting the error because it is outside the buffer. http://msdn.microsoft.com/en-us/library/system.management.automation.host.pshostrawuserinterface.windowposition%28v=vs.85%29.aspx Unfortunately, setting the position of the window is not simple. There is a snapin for it though - http://wasp.codeplex.com/ ( use Set-WindowPosition) A: Take a look at this script: Resize-Console.ps1 – Resize console window/buffer using arrow keys. It is hopefully useful itself and partially should answer the question (the size part).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: need a way to change the wordpress media uploader div TB_window css apologies for the question again my last question was poorly asked and code was missing. I'm having trouble with my plugin I'm trying to implement the wordpress media uploader, unfortunately iv ran into a problem i have it working and showing up when a upload button is clicked but it shows only half of the uploader i think i found the problem for some reason the TB_window div opens with margi-left: -334px; i adjusted this in fire fox (fire bug) to auto it appears normally e.g. the current div looks like this. <div id="TB_window" style="width: 670px; height: 351px; margin-left: -335px; top: 20px; margin-top: 0pt; display: block;"> and if i change it to <div id="TB_window" style="width: 670px; height: 351px; margin-left auto; margin-right: auto; top: 20px; display: block; position: fixed;"> there must be a simple hook / way to change the css for this box for my plugin how can i do this ? A: Well I think the easiest would be to just edit the CSS file for your Wordpress installation. Log into Wordpress and navigate to Appearance -> Editor. Then find styles.css in bottom right. Add your CSS markup to here. div#TB_window { margin-left: auto; } If that doesn't work then you can insert code into the head of your blog using a callback. add_action('wp_head', 'InsertMyStyleSheet'); function InsertMyStyleSheet() { echo '<link href="pathToStylesheet" type="text/css" rel="stylesheet" /> } And add your own CSS for your theme there. A: As long as relying on Javascript isn't a problem, you could try the following: _tbw = document.getElementById('TB_window'); _tbw.style.margin = "auto"; Or, if you're using jQuery: $(document).ready(function(){ var _TBwindow = $('#TB_window'); _TBwindow.css('margin-left', 'auto'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the best way to build a C# .NET client-server chat application? Possible Duplicate: multi client/server chat program in c#? I've been trying for some time to build a simple client-server chat, and I keep finding that there are a number of different ways. I was just curious as to what the most correct way would be. The first involves creating a new socket, binding it to a specific port and any IP Address, then listening for new connections (and that's as far as the tutorial leads). The next involves using a TcpListener to listen on a specific port (though it issues a warning saying that its deprecated, and I must include an IP address), it then waits for a new TCP connection, then creates either a new hashtable or new list to store the TcpClient(s). And that's all server side. Client side its pretty much the same, always trying to connect to the server. So, what's the best way to go about building one? Also, should I use StreamReader and StreamWriter (which some tuts use), or should I use NetworkStream, what should I use to transfer the messages? A: You are on the right track. However you might want to look into some of the more advanced features of WCF, such as Duplex services that will allow a push from the server based on an event. A: Personally, I would just setup a XMPP server and talk it with Jabber.net (http://code.google.com/p/jabber-net/) or something else but I haven't looked in a few years.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can one mongoid model query another? If I have a model called Product class Product include Mongoid::Document field :product_id field :brand field :name ... belongs_to :store And then I have a model called Store class Store include Mongoid::Document field :name field :store_id ... has_many :products def featured_products Products.where(:feature.exists => true).and(store_id: self[:store_id]).asc(:feature).asc(:name) end How do I create an accessible @store.featured_products which is the results of this query? Right now I get an error that reads uninitialized constant Store::Products A: Use Product, not Products. A: I just stumbled on this looking for something else and although the above answer is correct, and the question is ages old, it is very inefficient for what is being asked. As I stumbled on it, so might others. The example usage above wished to scope the products relationship to just featured products, so a model such as this would work faster (assumed Mongoid 3.0+): class Product include Mongoid::Document field :product_id field :brand field :name field :feature ... belongs_to :store scope :featured, where(:feature.exists => true).asc(:feature).asc(:name) end class Store include Mongoid::Document field :name field :store_id ... has_many :products end Then instead of @store.featured_products, you could call @store.products.featured. Now if you assume Mongoid 2.x was used, as this was 2011, and looking at this then Mongoid 1.x maybe not have had scopes, the same thing could be achieved like this: class Product include Mongoid::Document field :product_id field :brand field :name field :feature ... belongs_to :store end class Store include Mongoid::Document field :name field :store_id ... has_many :products def featured_products self.products.where(:feature.exists => true).asc(:feature).asc(:name) end end Now the reason both of these are more efficient that just a boolean search on the Products collection is that they start with a cursor creation across the _id field. This is indexed and limits the subsequent where query to just the related documents. The difference would be noticeable on most collection sizes, however the bigger the collection grew the more time would be wasted on a boolean of the entire collection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating preferences in real time I have a Preferences Screen which has some prefs that are interconnected. Which means, if I have pref x and y, I sometimes need y to change to something when x changes. What I'm doing at the moment is listening to prefs change event, and do this: SharedPreferences.Editor editor = prefs.edit(); editor.putString("y_pref", "somevalue"); editor.commit(); The problem is, that to actually see the change I have to first close the prefs screen and then open it again, only that way will I see the newly set prefs. Is there a way to change the prefs so that the change is visible right away, without the need to reload the prefs screen? A: Try to call the setter of the preference itself instead updating it on your own: E.g. EditTextPreference.setText(). So the preference itself updates it's own value too. If you do the update on your own the preference will not fetch the new value because it doesn't even know that the persisted value has changed. If you have a PreferenceFragment, you can get the preference with PreferenceFragment.findPreference(). If you have a PreferenceActivity, you can get the preference with PreferenceActivity.findPreference(). You call that with the preference key you assigned in your settings XML file and you get an instance of the corresponding preference. Then you cast it to an CheckBoxPreference, EditTextPreference, etc (the type you set in your XML file).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: decompiling chm file: hh.exe requires only the filename. no full path is allowed I noticed that hh.exe is capable of decompiling a .chm file to a set of .html files. But in order to work it requires the path to the file be current directory and the filename be the filename itself, apparently without allowing a full path. For example, this will work (in cmd): c:\MyDir>hh -decompile extracted MyFile.chm This won't work: c:\>hh -decompile extracted c:\MyDir\MyFile.chm This is relevant because I want to use a shell command from the registry to decompile the .chm file, and the parameter "%1" gives me the full path to the file only, and I don't know of a way to receive only the filename without the path A: Try passing forward slash eg: c:\>hh -decompile extracted c:/MyDir/MyFile.chm A: You could also try to open command line in the folder containing your .chm file, try 'shift' key and 'right click' mouse button and "Open command window here" option. Make sure no file is sellected. regards, joe A: It won't work with paths quoted or otherwise. It's easiest to just move the output folder and input *.chm into the root of the drive, cd there, and then simply run the hh.exe -decompile outputfolder input.chm command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascripts added via appendChild don't seem to run I've got a javascript file being added dynamically to a page. If I use document.write, it works fine: <html> <head></head> <body> <script type="text/javascript"> var src = 'myDynamicScript.js'; document.write('<scr' + 'ipt type="text/javascript" src="' + src + '"></scr' + 'ipt>'); </script> </body> </html> However, if I use appendChild, as outlined in this answer, the script gets downloaded, but never runs: <html> <head></head> <body> <script type="text/javascript"> var src = 'myDynamicScript.js'; var script = document.createElement("script"); script.type = "text/javascript"; script.src = src; document.body.appendChild(script); </script> </body> </html> I've got a simple example set-up here (write) and here (append). Should I expect it to run, or is that the known behavior? If it should, why isn't it? A: Your script is running all right, you just can't document.write from it. Use an alert or something to test it and avoid using document.write altogether. A: Your examples work for me in Safari. Here are some questions: What browsers are you testing? (Guessing you're having trouble on IE.) Are you trying this from a server and not just dragging index.html into your browser? What else is running on the page that might be blocking myDynamicServer.js? Has something hijacked window.onload? Have you tried appending myDynamicServer.js to document.getElementsByTagName('BODY')[0] and not document.body?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Intermittent missing email address in facebook API My application uses the "https://graph.facebook.com/me" request with an OAuth token to obtain properties about the user. Email address is one of the properties we need, and we do explicity request that permission when we request access. It's working fine 99% of the time, but on a few occasions the response comes back without any object in the jSON data named "email". Is there an explanation as to why this might happen, such as a way a user could grant us permission but still block their email address? Or could it be found under another key? Thanks. A: The mobile signup form at http://touch.facebook.com/r.php allows you to signup with an email address or phone number. So I don't think all Facebook users have an email address stored with them. A: The user can revoke the email address permission on the app privacy settings page without revoking the full application. You could first call /me/permissions to make sure the email permission is still granted. A: If you are using facebook SDK 2.4 or higher you need to add "fields" in the strategy Below is an example for oAuth library. FacebookStrategy.php line 131 BEFORE: $me = $this->serverGet('https://graph.facebook.com/me', array('access_token' => $access_token), null, $headers); AFTER: $me = $this->serverGet('https://graph.facebook.com/me', array('access_token' => $access_token,'fields'=>'email,name,first_name,last_name,age_range,gender'), null, $headers); Regardless of the field list, if you want to get more information that is not by default provided by Facebook, the permissions need to be in the "scope" array. Default data provided by SDK includes: email, public profile, user_friends A: Had the same problem and discovered that in the rare cases where this happens the user did not have a primary E-Mail-Address defined (although 2 Addresses were registered). We're not able to reproduce such a costellation, since normally it is not possible not to have a primary e-mail address. Can anyone confirm something similar? A: Missing email field happens where user doesn't confirm his primary address via clicking link from activation message. A: Short answer: Not all users have an email address available and those who do may not have a valid, reachable email address The documentation for the email field of the user object ( https://developers.facebook.com/docs/reference/api/user/ ) clarifies the expected behaviour here, which is: "this field will not be returned if no valid email address is available" There are a number of circumstances in which you may think a user should have an email address returned but they will not. Some common reasons: * *No Email address on account *No confirmed, verified email address on account *User entered a security checkpoint which required them to reconfirm their email address and they have not yet done so *Users's email address is unreachable You also need the email extended permission (which users can choose not to allow), even for users who have a valid, confirmed, reachable email address on file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Can Silverlight 4 establish a TCP connection to localhost? Please excuse the backwards architecture on this one and assume there's not a better way... I have a Windows Service running on localhost, it listens on TCP port 5432 and broadcasts events to any connected sockets. Is it possible for a Silverlight 4 in-browser app to connect to this service (thereby receiving these events)? Or are there security restrictions around Silverlight sockets preventing localhost access? A: Yes - that is possible though not easy because of security reasons... please see the following links: * *http://msdn.microsoft.com/en-us/library/cc645032%28v=vs.95%29.aspx *http://msdn.microsoft.com/en-us/library/cc296248%28v=vs.95%29.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7603646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: A few questions about SQLite database cursors in Android To implement database access in my application I followed Lars Vogel tutorial, but I'm very confused about a couple of things... * *Every time a call is made to fetchTodo a new cursor will be created and returned. Leaving the previous cursor for the garbage collector. So, if I don't use startManagingCursor or even the CursorLoader for that matter, should I call a .close() on the cursor when I'm done with it ? Outside of fetchTodo scope of course, example: Cursor cursor = mNotesAdapter.fetchTodo(); // do something... cursor.close(); I'm done with this cursor and new one will be created on the next fetch, should I close it like this then or should I leave it for the garbage collector? Although I think I'm talking about 2 things entirely different... Point being, should I close it like in the example above or not? *Cursor also has a .deactivate() method and the documentation says it uses less resources (than active cursors). When exactly should I use this? For instance, in my app, I have a ListActivity which is populated through a SimpleCursorAdapter (the code initialization for this is only called once). The cursor being used is a class member variable, because I need it outside the method that populates the list. I need it to requery the database when something is deleted from it. But until a record is deleted, which is a user action and may take a while to happen, should I deactivate the cursor in the meantime? Cause it will be active again when I call .requery() again. Or the SimpleCursorAdapter is going to stop working because the cursor is not active? EDIT: I just tested this one and found out that I can't call deactivate() after setting up the cursor adapter. The list will be empty if the cursor is not active, so it needs to remain active for as long as the ListActivity is displayed. In the end, we should just let StartManagingCursor handle it then. Or the new CursorLoader. *I know that startManagingCursor/stopManagingCursor are deprecated but I'm not targeting Honeycomb (at least for the time being) and I don't want to deal with the new CursorLoader for now. But in the tutorial above, startManagingCursor is used everywhere, but stopManagingCursor is never called once. Why not? Does Android deals with that in it's own way? Any situation I should call stopManagingCursor? A: Edit: Updated answer to reflect updated question 1: 1) Every time a call is made to fetchTodo a new cursor will be created and returned. Leaving the previous cursor for the garbage collector. So, if I don't use startManagingCursor or even the CursorLoader for that matter, should I call a .close() on the cursor when I'm done with it ? Yes, you should definitely either tell Android to startManagingCursor(), use LoaderManager/CursorLoader or close() it yourself. Not doing so will leak memory, the GC won't help with that as there's native resources behind the Cursor (e.g. file handles to the database). 2) Cursor also has a .deactive() method and the documentation says it uses less resources (than active cursors). When exactly should I use this? ... EDIT to other readers: The OP found an answer and posted it in his question. The following still holds: I've never used deactivate() (there's no deactive()), maybe someone else can explain this. If you want really painless requery/updates, do check out the LoaderManager framework -- it's not only for Honeycomb: using the compat library you can use LoaderManager (and Fragments) down to Android 1.6. Not only is it less code for you to write, but it completely offloads these things to Android, much more so than startManagingCursor(). EDIT2: Some notes on LoaderManager There are LoaderManager tutorials on developer.android.com but these are quite... complex and hard to understand the first time like most of the tutorials there. I also had to dig a lot, the best all-in-one stop I found so far is http://mobile.tutsplus.com/tutorials/android/android-sdk_loading-data_cursorloader/ (plus all the javadocs and compat lib source you can find) --- the way LoaderManager works is very similar to the (now also deprecated, replaced by DialogFragment) managed dialogs with their onCreateDialog, onPrepareDialog methods where you just tell Android to "show dialog #123" and then Android calls your code with that ID; same for loaders: "load loader #123", Android calls on onCreateLoader(). The only obvious drawback is initially, that LoaderManager relies heavily on the ContentProvider framework and some people seem to really dislike that. Sure, it's additional learning and code, but once you have a ContentProvider for your own data (even if only used privately in your app), all the data-to-view bindng is a breeze with CursorLoader. IMHO, there's little difference between rolling your own "content provider" and actually implementing the ContentProvider -- but this is just my highly controversial opinion :) 3) I know that startManagingCursor/stopManagingCursor are deprecated but I'm not targeting Honeycomb (at least for the time being) and I don't want to deal with the new CursorLoader for now. But in the tutorial above, startManagingCursor is used everywhere, but stopManagingCursor is never called once. Why not? Does Android deals with that in it's own way? Any situation I should call stopManagingCursor? Once you call startManagingCursor() the Cursor is no longer your problem. Android will take care of closing the Cursor when your Activity gets destroyed (user navigates away, orientation change, ...). There's no need to match a call to startManagingCursor() with a call to stopManagingCursor() -- you usually don't want to take on the burden of managing a Cursor again once you've gotten rid of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Modeling asynchronous game-like environment The idea is to model an environment for agents. In the most basic case it looks likes this: * *System asks the agent for the next action *Agent responds (e.g. "move left!") *System moves the agent to the appropriate state However, I am having trouble implementing this in an asynchronous manner (with threading and such). Currently my system looks like this: void Start(){ while(true && !gameOver){ askAgent() moveAgent() if(agentState == terminalState){ gameOver = True; } } } Clearly, this blocks the thread this is running on. (What's more embarrassing is I am using OSGi, so any single bundle should not be hogging all the processing time!) Also, I would like the system to react to new agents appearing in the environment, and engage with them (my runtime, OSGi, already has the facility of notifying me if something appears or disappears from the system) something like: void setAgent(Agent agent){ system.addAgentToEnvironment(agent); system.simulateAgent(agent); } Instead of just running from main straight away... I know this is very confusing, and I am not sure if I am even posing the question correctly - so any tips on the architecture or approaches I can look at are greatly appreciated. A: You will definitely need some data protection (perhaps on a master list of agents, and some kind of protection on each individual agent and its data). Other than that, I would follow this kind of model: while (waiting for events) spawn thread to respond to event // add agent, calculate and perform move, etc. // even better would be to enqueue the event into a thread pool if (terminal) break // end game HTH A: In order to help think about the future of the application, I would urge you to use two loops. long then = System.currentTimeMillis(); for(Agent a : agents) { agent.calcuateNextMove(getEnvironment()); } for(Agent a : agents) { agent.performNextMove(getEnvironment()); } long now = System.currentTimeMillis(); sleep(TIME_STEP_DURATION + now - then); // give you a steady frame rate in relation to real time This snippet gives you two things. * *Moves are made independently of other moves on the same step. This way you do not have your current move influenced by those who happened to move before you. *An agent merely exists, and is simply told to calculate his next move based on the environment you give it. This makes it incredibly easy to change states, copy agents into multiple environments, and give the illusion that the environment is different than it really is. For example, you may have a filterFor(Environment e, Agent a) that makes a mocked up version of the environment for that particular agent. Like wearing drunk-goggles or a blindfold or something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: url helper in cake is returning 127.0.0.1:8888? Why? I'm using the cakephp url HTML helper like following: <?php echo $this->Html->url(array('controller' => 'communities', 'action' => 'view'), true); ?> but, it's returing the following url: http://127.0.0.1:8888/communities/view where is coming this 127.0.0.1:8888 ? How can I change that? PS: If I remove the 'true' for second parameter, this isn't happens. A: you are returning controller url address. second parameter says, that path should be relative. controller address is "communities/view" but with second parameter (relative=false) it is http://127.0.0.1:8888/communities/view A: The Html::url() method's first argument is the CakePHP URL array, and the second is a boolean value that indicates whether or not the full (absolute) URL should be returned. In your case, <?php echo $this->Html->url(array('controller' => 'communities', 'action' => 'view'), true); ?> displays the URL http://127.0.0.1:8888/communities/view because you've indicated that you want the full, absolute URL by setting the second argument to true, you're running the site on localhost (IP address 127.0.0.1) and using port 8888 (the :8888 part). If you used <?php echo $this->Html->url(array('controller' => 'communities', 'action' => 'view')); ?> you would see only /communities/view because the second argument is not set and it defaults to false. When the second argument is set to true, it always displays the full, absolute URL based on the domain that the app is running on. So when you upload your site to your production environment, Html::url() would return http://www.example.com/communities/view, for example. If you check the API, you might not be able to find the url method on the HtmlHelper's page. This is because the HtmlHelper actually inherits the method from the Helper class (http://api.cakephp.org/file/cake/libs/view/helper.php#method-Helperurl).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python stripping chars from list item I'm trying to strip characters from timestamp stored in matrix (or list of lists if you want). I want to extract the item and use it as a filename after stripping unwanted characters (it should stay unchanged in the original list). I'm quite familiar with stripping and other string operations I use it routinely, but now I stucked with this, I don't know what's happening, I've tried almost everything. I want to get '2011092723492' instead of original '2011.09.27 23:49 2'. In this example is just ':' to be replaced to make it easier. Am I missing something ?: for x in FILEmatrix: flnm = str(x[4]) # or just 'x[4]' doesn't matter it is a string for sure print type(flnm) # <type 'str'> OK, not a list or whatever print 'check1: ', flnm # '2011.09.27 23:49 2' flnm.strip(':') # i want to get '2011092723492', ':' for starters, but... print 'check2: ', flnm # nothing... '2011.09.27 23:49 2' string.strip(flnm,':') print 'check3: ', flnm # nothing... '2011.09.27 23:49 2' flnm = flnm.strip(':') print 'check4: ', flnm # nothing... '2011.09.27 23:49 2' flnm.replace(':', '') print 'check5: ', flnm # nothing... '2011.09.27 23:49 2' thanks a lot! A: That's not what str.strip() does, and that's not how it works. Strings are immutable, so the result is returned from the method. flnm = flnm.replace(':', '') Repeat with the other characters you want to remove. A: Try this: import re flnm = re.sub('[^0-9]', '', flnm) A: This is pretty fast (if you want to strip those known non-alpha chars from the string): flnm.translate(None, ' .:') A: In Python there is usually more than one way to do it. But first, strip doesn't work the way you think it does. >>> flnm = '2011.09.27 23:49 2' >>> flnm.strip('2') # notice that strip only affects the ends of the string '011.09.27 23:49 ' You could join characters that aren't rejected. rejected = ' :.' flnm = ''.join(c for c in flnm if c not in rejected) Or just join digit characters. flnm = ''.join(c for c in flnm if c.isdigit()) Or chain a number of calls to string.replace. flnm = flnm.replace(' ','').replace('.','').replace(':','') Or use re.sub. import re flnm = re.sub('\D', '', flnm) Since strings are immutable, make sure you assign the result back to flnm. Edit: Even more ways to do it! Using reduce (from Ivan's answer): rejected = ' :.' flnm = reduce(lambda a, d: a.replace(d,''), rejected, flnm) Using translate (from oxtopus's answer): rejected = ' :.' flnm = flnm.translate(None, rejected) I prefer oxtopus's use of translate as it's the most straight forward. A: res = reduce( lambda a, d: a.replace(d,''),[':','.',' '],flnm)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create an IDT using LIDT I work on Intel-Atom 32bits (Assembly AT&T) How to create an IDT using LIDT I work on Intel-Atom 32bits (Assembly AT&T). I am using the MocroC OSII as an OS, i did this but it doesn,t work: Load_IDT: push %ebp //save the context to swith back mov %esp,%ebp movw $256*8, -6(%esp) //256 ISR possible movl $IDT, -4(%esp) //IDT is a table of 256*8bytes lidt -6(%esp) pop %ebp //Return to the calling function ret static void fill_interrupt(unsigned char num, unsigned int base, unsigned short sel, unsigned char flags) { unsigned short *Interrupt_Address; /*address = idt_ptr.base + num * 8 byte*/ Interrupt_Address = (unsigned short *)(idt_ptr.base + num*8); *(Interrupt_Address) = base&0xFFFF; *(Interrupt_Address+1) = sel; *(Interrupt_Address+1) = (flags>>4)&0xFF00; *(Interrupt_Address+1) = (base>>16)&0xFFFF; } /*Change the address of idt_entries table */ fill_interrupt(ISR_Nbr,(unsigned int) isr33, 0x08, 0x8E); A: Resolved :), as there is a BIOS, it already built the GDT/IDT.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby - Relationship of Class/Objects/Methods Pertaining to Ruby, can someone state the relationship between Class, Objects, and Methods in layman's terms? And maybe even give an analogy? New to OOP and trying to grasp the concept. A: note: OOP is independent of Ruby. Classes are like recipes. Objects are the actual food you prepare from a recipe. Methods are ... don't really fit in this metaphor. But they are the behaviors an object can perform. Some might say methods are the messages an object will respond to. A: A friend gave me this analogy: "It's like a watch. The Class is the watch casing, it encompasses the inner workings of the watch (Objects and Methods). The hands are the Objects, they perform the function of the watch based on the movement of the gears (Methods). The gears and springs underneath the face are the Methods; they are the heart of the watch that make up the function of the hands (Objects). Without the gears (Methods) the hands (Objects) have no function. Without either of those, there's no need for the watch casing (Class) to exist." A: Classes are your blueprints Methods are your tools (to build, to modify, to adjust) Objects are your buildings Remember that your objects are your nouns (e.g. a building) ... methods are you verbs (e.g. is built)!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I override the default session timeout with pyramid + pyramid-beaker + beaker I am using pyramid to create a web application. I am then using pyramid-beaker to interface beaker into pyramid's session management system. Two values affect the duration of a user's session. * *The session cookie timeout *The actual session's life time on either disk/memcache/rdbms/etc I currently have to cookie defaulted (via the standard beaker config) to delete when the browser closes. I have the session data set to clear out after 2 hours. This works prefectly. What I need to know is how to override the cookie's timeout and the session timeout to both be 30 days or some other arbirtrary value. A: Changing the timeout isn't supported by beaker. If you are trying to make a session stick around that long, you should probably just put it into a separate cookie. A common use-case is the "remember me" checkbox on login. This helps you track who the user is, but generally the actual session shouldn't be sticking around that long and gets recreated. A: I have a solution. Its old but works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Difference between feature detection and object detection I know that most common object detection involves Haar cascades and that there are many techniques for feature detection such as SIFT, SURF, STAR, ORB, etc... but if my end goal is to recognizes objects doesn't both ways end up giving me the same result? I understand using feature techniques on simple shapes and patterns but for complex objects these feature algorithms seem to work as well. I don't need to know the difference in how they function but whether or not having one of them is enough to exclude the other. If I use Haar cascading, do I need to bother with SIFT? Why bother? thanks EDIT: for my purposes I want to implement object recognition on a broad class of things. Meaning that any cups that are similarly shaped as cups will be picked up as part of class cups. But I also want to specify instances, meaning a NYC cup will be picked up as an instance NYC cup. A: Object detection usually consists of two steps: feature detection and classification. In the feature detection step, the relevant features of the object to be detected are gathered. These features are input to the second step, classification. (Even Haar cascading can be used for feature detection, to my knowledge.) Classification involves algorithms such as neural networks, K-nearest neighbor, and so on. The goal of classification is to find out whether the detected features correspond to features that the object to be detected would have. Classification generally belongs to the realm of machine learning. Face detection, for example, is an example of object detection. EDIT (Jul. 9, 2018): With the advent of deep learning, neural networks with multiple hidden layers have come into wide use, making it relatively easy to see the difference between feature detection and object detection. A deep learning neural network consists of two or more hidden layers, each of which is specialized for a specific part of the task at hand. For neural networks that detect objects from an image, the earlier layers arrange low-level features into a many-dimensional space (feature detection), and the later layers classify objects according to where those features are found in that many-dimensional space (object detection). A nice introduction to neural networks of this kind is found in the Wolfram Blog article "Launching the Wolfram Neural Net Repository". A: Normally objects are collections of features. A feature tends to be a very low-level primitive thing. An object implies moving the understanding of the scene to the next level up. A feature might be something like a corner, an edge etc. whereas an object might be something like a book, a box, a desk. These objects are all composed of multiple features, some of which may be visible in any given scene. A: Invariance, speed, storage; few reasons, I can think on top of my head. The other method to do would be to keep the complete image and then check whether the given image is similar to glass images you have in your database. But if you have a compressed representation of the glass, it will need lesser computation (thus faster), will need lesser storage and the features tells you the invariance across images. Both the methods you mentioned are essentially the same with slight differences. In case of Haar, you detect the Haar features then you boost them to increase the confidence. Boosting is nothing but a meta-classifier, which smartly chooses which all Harr features to be included in your final meta-classification, so that it can give a better estimate. The other method, also more or less does this, except that you have more "sophisticated" features. The main difference is that, you don't use boosting directly. You tend to use some sort of classification or clustering, like MoG (Mixture of Gaussian) or K-Mean or some other heuristic to cluster your data. Your clustering largely depends on your features and application. What will work in your case : that is a tough question. If I were you, I would play around with Haar and if it doesn't work, would try the other method (obs :>). Be aware that you might want to segment the image and give some sort of a boundary around for it to detect glasses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: validate period delimited numbers regex I have a tricky regex. * *numbers are is delimited by periods . *there can be a max of 4 periods. between each period there can be 0 to 4 numbers. valid expressions include .... ... .. . .1234.1234 ..1234.1234.1234 1234.1234.1234.1234.1234 (this is the max string) 1234.1234 1234....1234 1234.1234.1234 invalid strings include the following 12345 (too many digits example) ..1234...1234 (this is 5 periods) 1234.12345 (too many digits example) Thanks in advance A: I don't think it's particularly tricky... Just repeat a group of period+numbers: ^\d{0,4}(\.\d{0,4}){0,4}$ Edit: Works better with correct syntax. What's this for btw? Edit 2: Depending on your regex flavor you may need ^$. A: /^\d{0,4}(?!\d)(?:\.?\d{0,4}(?!\d)){0,4}$/ Tested in JS: var r = /^\d{0,4}(?!\d)(?:\.?\d{0,4}(?!\d)){0,4}$/; r.test('....'); // true r.test('...'); // true r.test('..'); // true r.test('.'); // true r.test('.1234.1234'); // true r.test('..1234.1234.1234'); // true r.test('1234.1234.1234.1234.1234'); // true r.test('1234.1234'); // true r.test('1234....1234'); // true r.test('1234.1234.1234'); // true r.test('12345'); // false r.test('..1234...1234'); // false r.test('1234.12345'); // false
{ "language": "en", "url": "https://stackoverflow.com/questions/7603679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get friends emails with facebook api I read lots of question about this issue. There is a way to get my friends emails, with Graph Api, FQL or something? I really need to import my Fb contacts into my App. But it seems there is not possible. Even setting a friend's email as public, I can't get it. A: Friend emails are not available, and probably never will be, via the Facebook Graph API or FQL. If you look at the documentation, it says "N/A" in the friend column for the email row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: call filter in Symfony with parameter Is possible call filter in Symfony in backend (admin generator) with parameters? In address URL is null. In session are parameters, but how can i this use for calling? For example http://www.myaddress.com/backend.php/users/filter?age=18 A: You need to read the manual - especially the links and routing chapter - this will help you determine how you create / manage urls for accessing data in your application : http://www.symfony-project.org/gentle-introduction/1_4/en/09-Links-and-the-Routing-System
{ "language": "en", "url": "https://stackoverflow.com/questions/7603689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MOV playback not working using UIImagePickerController with MPMoviePlayerController I have read similar threads regarding movie playback in a MPMoviePlayerController after selecting a video using UIImagePickerController including: MPMoviePlayerController do not play movie picked from UIImagePickerController * *Releasing the picker and/or the moviePlayer on playback complete or a combination of the two does not resolve my issue. Problem playing mov file in MPMoviePlayerController * *My movie is recorded via the iPhone real-time and will not have any codec issues - its a standard MOV My code is below - and believe me, I have tried every permutation I can fathom with this code. I have also tried to use MPMoviePlayerViewController, presenting it modally using the UIViewController MediaPlayer Additions - presentMoviePlayerViewControllerAnimated - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self.navigationController dismissModalViewControllerAnimated:YES]; if ( currentMediaType == kMediaTypeVideo ) { MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[info objectForKey:@"UIImagePickerControllerMediaURL"]]; moviePlayer.controlStyle = MPMovieControlStyleEmbedded; [moviePlayer.view setFrame:current_player_view.bounds]; [current_player_view addSubview:moviePlayer.view]; } } I have also tried adjusting how I provide the movie path to the MPMoviePlayerController - I recognize I can access the path like so: [[info objectForKey:@"UIImagePickerControllerMediaURL"] path]; ...and therefore can provide the NSURL with this code instead: NSString *chosenMoviePath = [[info objectForKey:@"UIImagePickerControllerMediaURL"] path]; MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:chosenMoviePath]]; However this does not resolve the issue either. There really shouldn't be any crazy extreme trick to recording a video and immediately playing said video in the movie player. Seriously. Its all on the device. Any help is extremely appreciated. I've spent much to much time on this already. Thanks in advance! J A: To resolve - I finally discovered if I don't animate the dismissModalViewController for the UIImagePickerController, then the playback displays for the video. The best I can conclude is that the animated dismissal has a delay which can cause other code to not execute immediately. So below works: - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self.navigationController dismissModalViewControllerAnimated:NO]; if ( currentMediaType == kMediaTypeVideo ) { MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[info objectForKey:@"UIImagePickerControllerMediaURL"]]; moviePlayer.controlStyle = MPMovieControlStyleEmbedded; [moviePlayer.view setFrame:current_player_view.bounds]; [current_player_view addSubview:moviePlayer.view]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python regex and splitting I have a string like this mystr = "K1_L1_L2 XX" I want to break it to the following format K1 L1 L2 XX where K1, L1, L2 can be anything but have this format of a char followed by a number. I am doing this in python using the following regex: a = "K1_L1_L2 XX" re.split("[\c\d\_]+",a) which gives me the following output ['K', 'L', 'L', ' ', '.', ''] but I want something like this ['K1', 'L1', 'L2', ' ', '.', ''] what is the possible workaround? A: There are problems with the code you have included in your example above. I would edit them but I'm not 100% sure what you are looking for. The following: import re a = "K1_L1_L2 XX" print re.split("[ _]", a) will print: ['K1', 'L1', 'L2', '', 'XX'] A: maybe re.split("([A-Za-z]\d)",a) ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Splitting C string in Python I would like to split a string similar to 'abc "defg hijk \\"l; mn\\" opqrs"; tuv' into (['abc', '"defg hijk \\"l; mn\\" opqrs"'], 33) i.e. I don't want to break on semicolon inside (nested) quotes. What's the easiest way, tokenize? It doesn't hurt if it's fast, but short is better. Edit: I forgot one more detail that makes it even more tricky. I need the position of the semicolon that is cutting off the string, or -1 if there is none. (I'm doing changes to legacy code that used to be recursive, but stackoverflowed when the string became very long.) A: It's unlikely there is an easy way to solve this without a proper parser. You could probably get away with a hand built parser that doesn't require tokenizing though. Something like the following should be a good guide: def parse(s): cur_s = [] strings = [] def flush_string(): strings.push(''.join(cur_s)) cur_s = [] def handle_special_cases(): # TODO: Fill this in for c in s: if c == ';': break elif c in ['\\' '"']: handle_special_cases() elif c == ' ': flush_string() else: cur_s.push(c) flush_string() return strings A: It's a stateful search, so simple stateless operations are not available. Here's a simple char-by-char stateful evaluator that might meet your "short" without resorting to full tokenization/parsing: #!/usr/bin/env python inp="""abc "defg hijk \\"l; mn\\" opqrs"; tuv'`""" def words_to_semi(inpstr): ret = [''] st8 = 1 # state: 1=reg, 2=in quotes, 3=escaped quote, 4=escaped reg, 0=end ops = { 1 : {' ': lambda c: (None,1), '"': lambda c: (c,2), ';': lambda c: ('',0), '\\': lambda c: (c,4), }, 2 : {'\\': lambda c: (c,3), '"': lambda c: (c,1), }, 3 : {None: lambda c: (c,2)}, 4 : {None: lambda c: (c,1)}, } pos = 0 for C in inpstr: oc,st8 = ops[st8].get(C, ops[st8].get(None, lambda c:(c,st8)))(C) if not st8: break if oc is None: ret.append('') else: ret[-1] += oc pos = pos + 1 return ret, pos print str(words_to_semi(inp)) Just modify the ops dict (and add new states) to handle other cases; everything else is generic code. A: Here's the brute-force method I went with. Brrr... def f(s): instr = False inescape = False a = '' rs = [] cut_index = -1 for idx,ch in enumerate(s): if instr: a += ch if inescape: inescape = False elif ch == '\\': inescape = True elif ch == '"': if a: rs += [a] a = '' instr = False elif ch == '"': if a: rs += [a] a = ch instr = True elif ch == ';': if a: rs += [a] cut_index = idx break elif ch == ' ' or ch == '\t' or ch == '\n': if a: rs += [a] a = '' else: a += ch return rs, cut_index f('abc "defg hijk \\"l; mn\\" opqrs"; tuv')
{ "language": "en", "url": "https://stackoverflow.com/questions/7603694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP - Passing a variable to a function without passing variables asked before it? Is it possible to pass a variable to function without passing the variables that come before it in the function definition? For example, if my function looks like this: function doThis( $v1, $v2, $v3 ) { echo $v1.$v2.$v3; } Can I then call the function with only some of those variables, like doThis("v1",null,"v3") or some other way? A: you can use predefined arguments: function doThis( $v1, $v2 = "hello", $v3 = 1 ) {} call to this function only with the first argument, the 2nd and 3rd will be "hello",1 by defualt: doThis(10); A: +1 on @Alon post You can also use an array .. $array['var1'] = null; $array['var2'] = "foo"; $array['var3'] = "bar"; doThis($array); function doThis($theArray){ var_dump($theArray); } This way, you can use empty values and N amout of variables. A: You can specify default values in the function definition like so: function doThis($a, $b=null, $c=null) { echo $a . $b . $c; } doThis("hello", " world"); // yields: hello world In this function, $a is a required parameter. The other two values are optional. To appease the commenter below, you can of course still call this function like so: doThis("hello", null, "world"); and of course, you do not have to provide defaults (but it is a good idea to do so) A: Yes, you can do doThis("v1",null,"v3"), if you prepare your function to handle that null argument. For example your example will work just fine. Or, if it makes sense you can change the order of the arguments so you can set defaults. A: The answer is: rework your workflow. I know you don't like that answer, but honestly, if you are passing more than 3 parameters or if sometimes you don't want to pass part of the beginning parameters, you probably want to rethink what you're doing. Function and method calls should be simple. You are probably doing too much in your function. General tips: * *Use classes if appropriate. This way you can avoid passing some information around because it's stored in the class and your methods have access to it. *Keep methods cohesive. That means your methods and functions should do one thing and do it well. *Put variables you want to pass only sometimes at the back. This allows you to simply not pass them if they have $var=null after it. You then check to see if $var===null before doing something with it. A: Much cleaner way is passing an array of variables, as demonstrated by @jflaflamme. Another way is allowing an arbitrary number of variables like this: function foo() { $arguments = func_get_args(); if(sizeof($arguments)) { echo implode('', $arguments); } } foo(1, 2, 3, $some_var); You can also loop trough the array you obtain via func_get_args, check them for their type (if it's a null, array, object - you name it) and then handle them in a way you deem appropriate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET OnClick not firing in Repeater.ItemTemplate that has a custom control Title is a bit of a mouthful, but I'm a bit stuck on this issue. I have a search result page with has a custom control that has a Repeater. The ItemTemplate in the repeater is a PlaceHolder so I can construct the Item in a particular format; more specifically, I have a string of 'diseases' that come in the form of Disease1|disease2|disease3 and need to be given links for each disease. Now for some code: The following is the SearchResultControl.ascx <asp:Panel ID="SearchResultPanel" runat="server" ScrollBars="Auto"> <asp:Repeater ID="Repeater1" runat="server" onitemcreated="Repeater1_ItemCreated" onitemcommand="Repeater1_ItemCommand"> <ItemTemplate> <asp:PlaceHolder ID="ItemTemplatePlaceHolder" runat="server"> </asp:PlaceHolder> </ItemTemplate> <SeparatorTemplate> <tr> <td colspan="6"><hr /></td> </tr> </SeparatorTemplate> </asp:Repeater> </asp:Panel> The code behind: SearchResultControl.ascx.cs protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e) { if (e.Item.DataItem != null) { PlaceHolder placeHolder = e.Item.FindControl("ItemTemplatePlaceHolder") as PlaceHolder; Control searchResultItem = Page.LoadControl("SearchResultItem.ascx"); DataRow row = (e.Item.DataItem as DataRowView).Row; if (row != null) { string diseaseState = row["DiseaseStates"] as string; searchResultItem.GetType().GetProperty("DiseaseStates").SetValue(searchResultItem, diseaseState, null); placeHolder.Controls.Add(searchResultItem); } } } (Full disclosure, I got this idea from this question) The SetValue calls the DiseaseStates property in SearchResultItem which in turn calls the following method to build the links, set the text, and the events: private void BuildDiseaseStateLabels(string diseaseStates) { PlaceHolder placeHolder = FindControl("DiseaseStatePlaceHolder") as PlaceHolder; string[] diseaseStateSplit = diseaseStates.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); int count = diseaseStateSplit.Length; foreach (string diseaseState in diseaseStateSplit) { LinkButton diseaseStateLink = new LinkButton(); diseaseStateLink.Text = diseaseState; //diseaseStateLink.Click += new EventHandler(OnDiseaseStateLinkClick); diseaseStateLink.CommandArgument = "<%# Eval(\"PatientID\")+ \";\" + Eval(\"PatientStatus\")+ \";\" + Eval(\"Age\")+ \";\" + Eval(\"DiseaseStates\")%>"; diseaseStateLink.CommandName = "OnDiseaseStateLinkClick"; //diseaseStateLink.Command += new CommandEventHandler(OnDiseaseStateLinkClick); placeHolder.Controls.Add(diseaseStateLink); if (count != 0) { Label splitLabel = new Label(); splitLabel.Text = "|"; placeHolder.Controls.Add(splitLabel); } } } This is the layout for the SearchResultItem <div id="SearchResultItemDiv" class="MainSearchResultItem"> <asp:PlaceHolder ID="DiseaseStatePlaceHolder" runat="server"> </asp:PlaceHolder> </div> Initially I tried setting the Click event, but that doesn't work at all. I then set the CommandArgument and CommandName but that didn't seem to do the trick. I figured the Command event might need to be set, but again, no luck. I should note that when a link is clicked the Repeater1_ItemCreated in SearchResultControl.ascx.cs is called. But since there is no data in e.Item.DataItem is null and I lose the results. In one of the questions regarding the same issue, it was suggested that the OnItemCommand be added, but even that doesn't get called. I also read A Stumper of an ASP.NET Question and A Stumper of an ASP.NET Question: SOLVED!, to no avail. What could I possibly be doing wrong? All of the correct event hookups seem there, I'm checking for IsPostBack and not doing DataBind() again. blaaargharaggh Help is always greatly appreciate. A: I believe you're running into this issue because the LinkButton controls are recreated too late in the page lifecycle. You have to remember that when the page is posted back, the control technically does not exist anymore, so the event handler cannot be fired. If you can recreate the LinkButton controls somewhere before the Page_Load event is reached, like OnInit for example, everything should work fine. For simple pages the above usually works very well, but there are circumstances where recreating controls during OnInit requires a lot of overhead, such as storing counters or arrays in ViewState so you can keep track of the controls that need to be recreated after postback. In these situations I would suggest taking a look at the DynamicControlsPlaceHolder by Denis Bauer. This control is capable of persisting dynamic controls without any addtional code required, which is pretty awesome. Here's a link to the latest version: http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx A: The problem might be that you're not doing the DataBind() again. Because you're building the buttons on the fly, when the page post backs, the buttons haven't been created and are unable to work out which click event it should be firing. Try getting rid of the IsPostBack check, so each time the page loads, you're re-build the repeater.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to retrieve dirs in a zipfile using python? How do I traverse the contents of a zip file in python without having to extract them? If extracting is the only way, is it efficient if I create a unique temp folder and extract them there then traverse and remove the temp folder afterwards? A: Use the namelist() method of the ZipFile class to get a list of all of the filenames in the archive without having to extract them. For example: import zipfile myzip = zipfile.ZipFile('myzip.zip', 'r') filenames = myzip.namelist() # Do something with filenames
{ "language": "en", "url": "https://stackoverflow.com/questions/7603709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing view from within didReceiveRemoteNotification Being still new to iPhone development, I am slowly getting there however sometimes the simple things seem to stump me. My application consists of 7 very different views. It is implemented as a window based app without a navigation controller. Navigation is managed by each view controller individually and I use a central data repository to make data available through the app. I use :- DetailView *viewDetail = [[DetailView alloc] initWithNibName:nil bundle:nil]; [self presentModalViewController:viewDetail animated:YES]; to change views. Obviously, in all cases, this is executed within the controller of the current view. HOWEVER, I have now added Push Notification to the app. Upon receipt of a Push, the userInfo data is made available within the main AppDelegate and didReceiveRemoteNotification is executed. I wish to force the application into the Detailview described above, passing it one of the values within userInfo. Of course, I get a nice SIGABRT as soon as it executes the second line. I assume this is because the currently active view is not self. How do I surrender the current view in favour of the DetailView from within the app delegate? The current view could be ANY of the 7 views, including DetailView, which I wil want to refresh with the new data. Thanks in advance Chris Hardaker A: This is a small side note, but the naming convention that you are using is non-standard. Rather than, DetailView *viewDetail = [[DetailView alloc] initWithNibName:nil bundle:nil]; conventionally, an iOS developer would expect to see the following: DetailViewController *viewDetail = [[DetailViewController alloc] initWithNibName:nil bundle:nil]; since viewDetail is a subclass of UIViewController rather than UIView. To answer you main question though, I would use NSNotificationCenter. Basically, this allows any class to post a notification, which more or less just throws out the fact that an event occurred to any class that happens to be listening for it. So in didReceiveRemoveNotification: you can call: [[NSNotificationCenter defaultCenter] postNotificationName:@"pushNotification" object:nil userInfo:userInfo]; When you allocate your view controllers, run this line: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushNotificationReceived:) name:@"pushNotification" object:nil]; You will need to put a method called pushNotificationReceived: (NSNotification*)aNotification in each of the view controllers to handle the notification. The userInfo dictionary that you passed will be a property of the notification. Now, when ever the @"pushNotification" notification is sent, your controllers will receive a notification and run the given selector. So you can dismiss the controller or show the detail view or whatever you want. When you dealloc your view controller, make sure to call [[NSNotificationCenter defaultCenter] removeObserver:self];
{ "language": "en", "url": "https://stackoverflow.com/questions/7603712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Define the prototype of a function with a std::vector as input parameter in an header I'm getting crazy since i'm not able to define the prototype of a function i'm actually using. What i'm doing is create an header file called func1.hwhere i define this prototype (that's because i need to invoke this function from some other function implemented elsewhere): void FileVector(std::vector<Files> &,const char*,bool); Where Filesis a struct defined in func1.cpp struct Files{ HANDLE h; WIN32_FIND_DATA info; } file; I have also another function that accept a std::vector<Files> & as input parameter but when i try to compile (using Eclipse C++) i'm getting those errors: /FileVector.h:11:22: error: variable or field 'FileVector' declared void ..\/FileVector.h:11:17: error: 'vector' is not a member of 'std' ..\/FileVector.h:11:29: error: 'Files' was not declared in this scope I've tryied to include several directive in the header file..for example declaring the struct in the header and including vector header do the trick but this way i got loads of "multiple definitions/first defined here" error. What can i do? EDIT Now my header looks like: #ifndef FILEVECTOR_H_ #define FILEVECTOR_H_ #include <vector> #include <windows.h> struct Files{ HANDLE h; WIN32_FIND_DATA info; }; void FileVector(std::vector<Files> &,const char*,bool); #endif /* FILEVECTOR_H_ */ At this point, i need to declare another prototype in another header: void ProcessInput(vector<Files>&); but i can't use the same trick as above cause i'll have to re-define the Files struct. How can i solve this? A: Make sure to include <vector> in your header file. You also mention that the definition of Files is within the cpp file, you should move it to the header as well. Also place proper header guards to avoid multiple definition errors: #ifndef MY_HEADER_FILE_GUARD #define MY_HEADER_FILE_GUARD ... your content here ... #endif /*MY_HEADER_FILE_GUARD*/ Update: Simply including filevector.h from your new header would do. However, it looks like Files should be defined in a header of its own and included from the two headers that make use of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Script to add hyperlink when pre-defined text is found? I'm using PHP to pull some data from an google calendar XML feed, and I'm wondering if there's any kind of script that will run after this and if it finds a certain phrase (not a URL), add a hyperlink to it? E.g. if it pulls "Bayerische Staatsoper" from the feed it will add a hyperlink for the Staatsoper website. Is this possible? Hope that makes sense. Thanks A: str_replace("Bayerische Staatsoper","<a href='#'>Bayerische Staatsoper</a>",$text); The above code searches for "Bayerische Staatsoper" in variable $text and replaces it with the link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why am I getting this error? Fatal error: Class 'TestCase' not found Even though I have got the TestCase class included? <?php require_once("PHPUnit/Autoload.php"); require_once("PHPUnit/Framework/TestCase.php"); require_once("PHPUnit/Framework/TestSuite.php"); class WidgetSession { public function __construct($one, $two){} public function login() {} public function isLoggedIn() {return null;} public function getUser(){ return new WidgetUser(); } } class WidgetUser{ public $first_name = ""; public $last_name = ""; public $email = ""; public function isSalesPerson() {return null;} public function isSalesManager() {return null;} } class TestWidgetSession extends TestCase { private $_session; function setUp(){ $dsn = array( 'phptype' => "pgsql", 'hostspec' => "localhost", 'database' => "widgetworld", 'username' => "wuser", 'password' => "foobar" ); $this->_session = new WidgetSession($dsn, true); } function testValidLogin(){ $this->_session->login("ed", "12345"); $this->assertEqual(true, $this->_session->isLoggedIn()); } function testInvalidLogin(){ $this->_session->login("ed", "54321"); //fail $this->assertEquals(false, $this->_session->isLoggedIn()); } function testUser(){ $user = $this->_session->getUser(); $this->assertEquals("Lecky Thompson", $user->last_name); $this->assertEquals("Ed", $user->first_name); $this->assertEquals("ed@lecky-thompson.com", $user->email); } function testAuthorization(){ $user = $this->_session->getUser(); $this->assertEquals("Sales Person", $user->role); $this->assertEquals(true, $user->isSalesPerson()); $this->assertEquals(false, $user->isSalesManager()); $this->assertEquals(false, $user->isAccountant()); } } $suite = new TestSuite; $suite->addTest(new TestWidgetSession("testValidLogin")); $suite->addTest(new TestWidgetSession("testInvalidLogin")); $suite->addTest(new TestWidgetSession("testUser")); $suite->addTest(new TestWidgetSession("testAuthorization")); $testRunner = new TestRunner(); $testRunner->run($suite); ?> A: require_once("PHPUnit/Framework/TestCase.php"); This file will most certainly not contain any definition of TestCase but PHPUnit_Framework_TestCase. Take care and use the right classname. I assume the same applies to: require_once("PHPUnit/Framework/TestSuite.php"); which is PHPUnit_Framework_TestSuite and not TestSuite. And you only need to require/include the autloader, that's enough for PHPUnit's classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Questions about Memory Management, Stack, and Heap Possible Duplicate: Does this type of memory get allocated on the heap or the stack? I have a few memory-related questions, I was hoping you guys would be able to answer. Consider this code, with Foo representing a large class with lots of methods and lots of primitive data members: class Foo { public: Foo() : // Initialize all data members ... { } // Lots of methods ... ~Foo() { /*Nothing needed here ... correct?*/ } private: int a; int b; char c; double d; // Lots of other primitive data members (no pointers) ... }; class Bar { public: void func() { foo = new Foo(); } // Assuming Bar::func() is always called before deletion ... ~Bar() { delete foo; } private: Foo* foo; }; int main() { Bar bar; bar.func(); Bar* barptr; barptr->func(); return 0; } My question is, when I call bar.func(), are all the data members of Foo allocated on the stack memory or on the heap memory (I know foo would be on the heap...I think!)? What about when I call barptr->func()? Is, for example, Foo::a on the stack or on the heap? Furthermore, do I need to explicitly delete anything in Foo::~Foo()? Foo only has primitive local data members, and none of the functions use new or malloc(). In the case that I have absolutely no idea what I'm talking about, I'd appreciate it if someone could explain where these data are stored. A: Everything allocated with new is on the heap, including all its members. The line foo = new Foo(); creates a Foo (including all its members) on the heap. Only named objects are on the stack. In your case bar (a Bar), and barptr (a pointer to a Bar). Foos destructor doesn't need to do anything, which is actually quite common, if you use RAII properly, like is the C++ way. In your main function, bar is a region on the stack that is a Bar, which allocates a Foo on the heap. If barptr; were actually initialized, barptr would be a region on the stack that is a pointer to a Bar somewhere (maybe stack maybe not). However, in every case, a Bars foo member will be allocated on the heap, since that's what Bars constructor tells it to do. In your main function, bar is a region on the stack that is a (pointer to a (large collection of primitives)), which allocates a (large collection of primitives) on the heap. If barptr; were actually initialized, barptr would be a region on the stack that is a pointer to a (pointer to a (large collection of primitives)) somewhere (maybe stack maybe not). However, in every case, the (large collection of primitives) will be allocated on the heap, since that's what the constructor tells it to do. Since I know someone will mention it, the heap/stack distinction is at the compiler's whim, and not standardized in any way. It is fully allowed to "cheat" and put things in other places if it feels like it. For instance, global objects are frequently on neither the stack nor the heap, but in another place. Also, that's how C# and java go so fast despite the frequent (apparent) use of memory management. The compiler frequently "cheats" and puts "dynamically scoped" objects on the stack. A: When you call new Foo(), you're creating a new Foo object on the heap. All the primitive data members in Foo are stored inside the Foo object. Therefore, they are also on the heap -- inside the Foo object. Your Foo destructor doesn't need to explicitly dispose of the primitive data members. Nor would it need to explicitly dispose of members of class type; their destructors would be called automatically after Foo's destructor. A class that has a bare pointer to something dynamically allocated typically does need an explicit statement in the destructor to dispose that something. You can avoid this by using smart pointers like std::auto_ptr or boost::shared_ptr.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SocketAsyncEventArgs.UserToken not being updated? I currently have a client-server application that involves a Silverlight client and a .NET server. The .NET portion uses the Tcp classes provided in System.Net.Sockets namespace whereas the Silverlight client uses raw sockets. I'm porting into this from code that currently uses the HttpListener classes because it doesn't suit my needs. The Http classes, though, have on the SL side the ability to use Begin* and End* style asynchronous methods that allow me to specify a handler once the operation has completed. I'm having trouble getting this to work with the new system. My current strategy is to include the handler as part of the UserToken. However, it seems that this token is not getting updated. Here is some redacted code. I am able to get the two sides to talk to each other, but it seems the correct UserToken is not being sent. public class ClientUserToken { public Handler Handler { get; set; } public string Test { get; set; } public ClientUserToken(Handler handler, string test) { Handler = handler; Test = test; } } public class SocketClient { private Socket _clientSocket; private string _ipAddress; private int _port; private void OpenSocket() { var endPoint = new DnsEndPoint(_ipAddress, _port); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.UserToken = new ClientUserToken(null, "foo"); args.RemoteEndPoint = endPoint; args.Completed += OnSocketCompleted; _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _clientSocket.ConnectAsync(args); } void OnSocketCompleted(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Connect: ProcessConnect(e); break; case SocketAsyncOperation.Receive: ProcessReceive(e); break; case SocketAsyncOperation.Send: ProcessSend(e); break; // this never gets called } } void ProcessConnect(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { byte[] response = new byte[1024]; e.SetBuffer(response, 0, response.Length); _clientSocket.ReceiveAsync(e); } } void ProcessReceive(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success && e.BytesTransferred > 0) { var userToken = e.UserToken as ClientUserToken; // this token is always the one set in ProcessConnect // process the data if (!_clientSocket.ReceiveAsync(e)) { ProcessReceive(e); } } } // this is never called, for some reason void ProcessSend(SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { var userToken = e.UserToken as ClientUserToken; if (!_clientSocket.ReceiveAsync(e)) { ProcessReceive(e); } } } // this is the public API that users use to actually send data across public void SendToServer(byte[] data, int len, Handler handler) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.UserToken = new ClientUserToken(handler, "bar"); args.SetBuffer(data, 0, len); if (!_clientSocket.SendAsync(args)) { ProcessReceive(args); } } } As the comments above suggest, in ProcessReceive, userToken.Test is always "foo" and userToken.Handler is always null. I have so far not been able to break into ProcessSend so I can't see what SocketAsyncEventArgs it actually sent. Anyone have a clue why this event isn't firing (Completed after a Send)? Am I screwing up my SendToServer function? I realize there may be other existing problems with synchronization and such, but I don't think that's the issue here. One thing I did try was setting up a ManualResetEvent to ensure that no one sends data to the server before the connection has been completed (ProcessConnect) but that did not solve the issue, either. Any help will be appreciated! EDIT: So the reason this is happening is because when I call ReceiveAsync in the ProcessConnect function, it is being used when the server is sending back the response for my data. Hence, UserToken "foo" is present in the handler. The next time the server sends data, the ReceiveAsync uses the args with the UserToken "bar". So it is kind of out of sync, for the duplex communication bit. I can't ensure that the SocketAsyncEventArgs that I sent from the client-side is the same one that is used on the response. It seems like the only solution is to have the SL client open two sockets--one for server-initiated data and the other for client-initiated requests. However, this means I'm not taking advantage of the duplex nature. A: This model won't work because I'm creating a new SocketAsyncEventArgs on each send, which means that the data can come back on any of these args. I've been moving towards a model with a pool of SocketAsyncEventArgs and each client can only have one request/response at a time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL query for checking event conflict Currently I making a school community site and I got a problem in a part were the administrator post a new event he/she wants check if the event start date and time has no conflict also end date and time before saving it on the database. I tried many queries still i fail to get the exact sql. I'm using MySQL Server 5 and PHP 5.3. Can any one help me on how to query on the table i mean the right sql string. Heres the table fields: * *event_id => int, *event_type => enum('school','department'), *event_title=> text, *event_details=> longtext, *event_start=> datetime, *event_end=> datetime, *event_added_by=> int, *event_modified_on=> datetime, Here is what i have right now: SELECT *, time(event_start) as start_time, time(event_end) as end_time FROM `tbl_events` WHERE ((date(event_start) between '2011-12-9' and '2011-12-15') AND (time(event_start) between '00:00:00' and '01:00:00')) OR ((date(event_end) between '2011-12-9' and '2011-12-15') AND A: You have four things to look for that indicate a conflict: * *an existing event starts before your event starts and ends after your event ends (your event is inside the existing event) *an existing event starts before your event starts and ends after your event starts (overlap the beginning of the new event) *an existing event starts before your event ends and ends after your event ends (overlap the end of the new event) *an existing event starts after your event starts and ends before your event ends (the existing event is inside the new event) By before and after, I mean at the same time or before/after (<= and >=). A: There are two checks to do that need to be combined into one condition: * *an (existing) event starts before your event ends and *it ends after your event starts. If the query with such a condition returns rows, there's a conflict. I'm assuming here that the end time is the time when the event ceases to be active (or functional or valid or whatever). That is, if an event's start time equals another event's end time, there's no conflict in there. However, if that should be considered a conflict in your case, replace the before and after above with before or when and after or when respectively. Here's how it might look in a query: … WHERE event_start < @new_event_end AND event_end > @new_event_start … Or, if no event_start should match another event's event_end: … WHERE event_start <= @new_event_end AND event_end >= @new_event_start … (That is, simply replace strict inequalities with non-strict ones.) A: This allows also for open ends (modeled by end = null): WHERE (event2.start < event1.end OR event1.end is null) AND (event2.end > event1.start OR event2.end is null) And take care whether using > or >= (respectively < or <=), this depends on your data and requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL select rows with max repetition betwen two dates I have three tables Books, Debit and Client. * *Books (Id, Title, ...) *Debit (BooksID, ClientId, BorrowingDate,....) *Client (Id, Name, ...) I need SQL query that will return a book that is most times rented out, between two dates. Dates will be passed as parameters to query. A: How about this? SELECT * FROM Books INNER JOIN Debit ON Books.Id = Debit.BooksID WHERE BorrowingDate >= @StartDate AND BorrowingDate <= @EndDate If you edit in an example of what you would like the output to look like I can redefine the above query to help you get what you want. And for the record, Adrian is right; it is generally better to make an attempt yourself and come to us with a problem, rather than asking SO to solve the problem for you. But hopefully what I have here will get you started. Welcome to SO! :) Edit It also just occurred to me that you might be looking for the book which was rented out most number of times between your two dates... If so, try this: SELECT TOP 1 Books.* FROM ( SELECT COUNT(*) AS DebitCount, BooksID FROM Debit WHERE BorrowingDate >= @StartDate AND BorrowingDate <= @EndDate GROUP BY BooksID ) Debits INNER JOIN Books ON Books.ID = Debits.BooksID ORDER BY DebitCount DESC Hope that helps! A: The query... SELECT TOP 1 * FROM ( SELECT BooksID, COUNT(*) AS C FROM Debit WHERE BorrowingDate BETWEEN @min_date and @max_date GROUP BY BooksID ) ORDER BY C DESC ...will yield one row containing the BooksID and number of rents of the book that has been rented most times between @min_date and @max_date. You can later easily JOIN with Books if you need more than just BooksID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to slip this multi-dimensional array? I have a nested array and I wanted to know if there is a way to slip it, so having the nested arrays as individual arrays Array ( [0] => Array ( [menu] => Array ( [pizza] => Array ( [Tomato & Cheese] => Array ( [small] => 5.50 [large] => 9.75 ) [Olives] => Array ( [small] => 6.85 [large] => 10.85 ) ) [Speciality Pizzas] => Array ( [Our Special] => Array ( [ingredients] => Array ( [0] => Tomatoes [1] => Olives [2] => Spinach [3] => Fresh Garlic [4] => Mozzarella & Feta Cheese ) --- theres more but you get the idea Now I want to may a new array with all the pizzas, but without knowing the name "pizza" at the moment I can do this: $array = array(json_decode($json, true)); $pizzas = (array)$array[0]['menu']['pizza'] But if the menu changes content (but not structure) and if the 'pizza' changes to 'salads' the above would fail. Is the a way to create the above pizzas array without the name Thanks A: $array = array(json_decode($json, true)); $menu = (array)$array[0]['menu']; foreach($menu as $item => $item_Data){ //$item might be pizza for example //$item_Data might be Olives or Our special. Now you have to consider what to do with this. Maybe next foreach loop ? } A: Right now your array has parallel sections for related data. How about if you did something like: $food_choices = array( 'pizza' => array( 'Tomato & Cheese' => array( 'type' => 'regular', 'prices' => array(...), 'ingredients' => array(...) ), 'Our Special' => array( 'type' => 'specialty', 'prices' => array(...), 'ingredients' => array(...) ), ), 'salads' => array( 'Caesar' => array(...); 'Tossed' => array(...); ) ) where all the information related to any one menu item as all in the same branch of the meu tree. Then to access any one pizza's information is as simple as: $data = $food_choices['pizza']['Tomato & Cheese']; echo 'The large of this pizza costs $', $data['prices']['large']; echo 'The small Caesar salad contains ', implode($food_choices['salad']['Caesar']['ingredients); A: A series of foreach loops might do, even though I don't know what you're doing. <?php $pizza = ''; foreach ($array as $food) { $pizza .= $food; if (is_array($food)) { foreach ($food as $option) { $pizza .= " > " . $option; if (is_array($option)) { foreach ($option as $value) { //etc } } } } } ?> A: To learn about the keys in an array, use the array_keys function (Demo): $array = array(array('menu' => array(/* ... */))); # your array print_r(array_keys($array[0])); # Array(menu)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What could be causing Javascript to stop working in IE in Strict mode I'm trying to debug my jQuery plugin and it worked fine in IE until I added <!doctype html>. It still works fine in all browsers except IE sigh (tested in 6,7,8). What sort of thing could be causing this? here is the page: http://liime.net/projects/liimeBar/demo.html A: Your condition in constructScrollers() window.innerHeight < $('body')[0].scrollHeight is false, bacause both values are the same in IE8. So no scrollers are created Do some research in jQuery that you find the proper function how to get the heights you want to test. You have much code in it, that could be better if you used more jQuery functions, not just the selectors. --edit try this instead $(window).height() < $('body').height() P.S.: By this script you can only make a scrollbar for the body, because you hard coded the body. try $(this) instead, which is the object you called your liimebar() function with and don't use ids on liimebar_buttons, ..bar etc, but classes, so you could possibly have more than on scrollbar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: OpenCV : How do I find the minimum element along a specific dimension? I'm a new user to OpenCV. I'm using version 2.3.2 (from the SVN repository). I have a specific 3-dimensional cv::Mat structure which is 288 x 384 x 10. This represents a 288 x 384 image and the other 10 channels represent a disparity value. I want to find the minimum element and its location. There is a minMaxElem function in OpenCV with it doesn't work with multi-dimensional arrays. Any idea how I can use the channel splitting functions in OpenCV to perform this? A: You can use minMaxIdx function to find minimum/maximum on multidimensional array: void minMaxIdx(InputArray src, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0, InputArray mask=noArray()); Non-zero minIdx and maxIdx should point to the arrays having enough length to store indexes for all dimensions (3 for 3-dimensional Mat). minVal and maxVal are used to return single minimum/maximum value. They can be 0 if you don't need the values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SSCrypto from Objective C to C# I am trying to encrypt below base64 string in objective c .. Now i need to decrypt the output of below code in C# ... Please advice simplest way as i don't want to install any libs at server. Please advice how can convert encripted string back to base64 using C# . Thanks My Objective c Code for encripting the base 64 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; SSCrypto *crypto; NSString *password =@"abcdefghijklmnoqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnoqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyzabcdefghijklmnopqrstuvwzyz"; NSData *seedData1 = [password dataUsingEncoding:NSUTF8StringEncoding]; crypto = [[SSCrypto alloc] initWithSymmetricKey:seedData1]; NSString *base64String = @"SUkqAAgAAAARAP4ABAABAAAAAAAAAAABAwABAAAAsAQAAAEBAwABAAAAEAIAAAIBAwABAAAAAQAAAAMBAwABAAAABAAAAAYBAwABAAAAAAAAAAoBAwABAAAAAQAAABEBBAABAAAACgEAABIBAwABAAAAAQAAABUBAwABAAAAAQAAABYBAwABAAAAEAIAABcBBAABAAAA3yUAABoBBQABAAAA2gAAABsBBQABAAAA4gAAACUBBAABAAAAAAAAACgBAwABAAAAAgAAADEBAgAgAAAA6gAAAAAAAADIAAAAAQAAAMgAAAABAAAAQ29tcHJlc3NlZCB3aXRoIFBBTklOSSBJbWFnZSsAAAAmoy1xRBcev/r/LSUkbRxE+cRxGpEdF0Rw2EcNhHDIBcufR2+R0XZJjI6OIj5HjCPRHR9F0R8wCmRwXI6I+eROjiNxpEdkdEdl2R8ujTMMuy+R0R8j5HZvNo2yOzcXyOiPkdFzLsjxHGRwbC5lwJQaQRDaCchYbAxEREREREREREREREREREREREREREREREREI0BuRww+RIyPFw2MSnIccp0yY58fgxZ5EcKaVhJdx//pL0OQwm5EA///WlgnWSAb/+q9KEgt4X+961qgtKkZJCMH/XlnojiSvNBUkmSCPZBiQlT//iR7pdK0tgnwzep3zv//DLtrqmuLDodf/X7w2lasnCq7CWPf/0l2a6sIIRSVjoLFf9/3sMJ+jrkIjeTonRHRtE6N5A86ohEQtF0d6Ijol0IiIiIiIiIiIi0IiIiIiOIiIiIiIiIiIiIiIiIiIiIgwjtb8tBIhXABABA=="; [crypto setClearTextWithString:base64String]; NSData *cipherText = [crypto encrypt:@"aes256"]; NSLog(@"Cipher text: '%@' using %@", [cipherText encodeBase64WithNewlines:NO], @"aes256"); NSLog(@" "); [ pool release]; Below is my C# code for Decryption public static string DecryptString(string base64StringToDecrypt, string passphrase) { //Set up the encryption objects using (AesCryptoServiceProvider acsp = GetProvider(Encoding.Default.GetBytes(passphrase))) { byte[] RawBytes = Convert.FromBase64String(base64StringToDecrypt); ICryptoTransform ictD = acsp.CreateDecryptor(); // TripleDES. //RawBytes now contains original byte array, still in Encrypted state //Decrypt into stream MemoryStream msD = new MemoryStream(RawBytes, 0, RawBytes.Length); CryptoStream csD = new CryptoStream(msD, ictD, CryptoStreamMode.Read); //csD now contains original byte array, fully decrypted //return the content of msD as a regular string return (new StreamReader(csD)).ReadToEnd(); } private static AesCryptoServiceProvider GetProvider(byte[] key) { AesCryptoServiceProvider result = new AesCryptoServiceProvider(); result.BlockSize = 128; result.KeySize = 128; result.Mode = CipherMode.CBC; result.Padding = PaddingMode.PKCS7; result.GenerateIV(); result.IV = new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; byte[] RealKey = GetKey(key, result); result.Key = RealKey; // result.IV = RealKey; return result; } private static byte[] GetKey(byte[] suggestedKey, SymmetricAlgorithm p) { byte[] kRaw = suggestedKey; List<byte> kList = new List<byte>(); for (int i = 0; i < p.LegalKeySizes[0].MinSize; i += 8) { kList.Add(kRaw[(i / 8) % kRaw.Length]); } byte[] k = kList.ToArray(); return k; } Please advice if anything is missing or if i have done something gross wrong .. I have lost more than 2 days in searching. A: You can do this easily with the AesManaged class. See: http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7603767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Specifying up directory in build.xml for ant in windows I have a build.xml file for ant, and I want to modify a directory from <condition property="flex_sdk" value="%cd%/SDK/flex_sdk/"> <os family="windows" /> </condition> to <condition property="flex_sdk" value="../SDK/flex_sdk/"> <os family="windows" /> </condition> The flex_sdk bin directory has .bat files so they are run using cmd /c. I get the error "'..' is not recognized as an internal or external command". Any help is greatly appreciated. Thanks. A: Maybe you could try this : <property name="bat.dir" location="${flex_sdk}"/> The location attribute if specified in a property resolves relative paths based on the ${basedir} which is the directory of your ant build.xml file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving a view from one gridview to another in Android I am trying to write an app that has 2 gridviews. The gridviews are side by side on the same screen. I populate the left gridview with the currently installed apps and use their icons so basically I have a gridview of ImageViews. The activity passes an arraylist of Drawables to an ImageAdapter. The imageAdapter extends the BaseAdapter and implements OnTouchListener. My getView() method is similar to the one found on the android developers site // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(6, 6, 6, 6); } else { imageView = (ImageView) convertView; } //imageView.setImageResource(mThumbIds[position]); imageView.setImageDrawable(mList.get(position)); imageView.setContentDescription(mNames.get(position)); imageView.setDrawingCacheEnabled(true); imageView.setOnTouchListener(this); return imageView; } And here is my onTouch. I have been following other examples but my scenario doesnt involve using AbsoluteLayout and it uses API level 8 so I cant implement an OnDragListener :( public boolean onTouch(View v, MotionEvent event) { LayoutParams par = (LayoutParams) v.getLayoutParams(); int x = (int) event.getX(); int y = (int) event.getY(); if (event.getAction() == MotionEvent.ACTION_DOWN) { Log.i("ACT DOWN", (String) v.getContentDescription()); status = START_DRAGGING; v.setLayoutParams(par); //image = new ImageView(mContext); //mLayout.addView(image, par); //Toast.makeText(AppMoverActivity.this, "" + v.getContentDescription(), Toast.LENGTH_SHORT).show(); } if (event.getAction() == MotionEvent.ACTION_UP) { status = STOP_DRAGGING; v.setLayoutParams(par); Log.i("ACT UP", "Stopped Dragging"); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (status == START_DRAGGING) { Log.i("ACT MOVE", "Moving"); //Implement ability to drag the view to other grid... } } return true; } Is there anyway I can make this work or do I have to change the way I am approaching this? Any help appreciated! A: This tutorial seems to describe what you want: http://blahti.wordpress.com/2011/10/03/drag-drop-for-android-gridview/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenCV static linking error I want to use OpenCV as a static library. After compiling the library as a static library now i'm testing with some examples to see all the dependencies. The dependencies added to compile are -staticpkg-config --libs opencv-lpthread -ljpeg -ltiff -lz -ljasper -lpng12 But obtain the following Error message: g++ -c -g -Wall -O2 `pkg-config --cflags opencv` formas.cpp g++ -g -Wall -O2 `pkg-config --cflags opencv` formas.o -o paint -static `pkg-config --libs opencv` -lpthread -ljpeg -ltiff -lz -ljasper -lpng12 /usr/local/lib/libopencv_core.a(system.o): In function `cv::tempfile(char const*)': system.cpp:(.text._ZN2cv8tempfileEPKc+0x3a): warning: the use of `tmpnam' is dangerous, better use `mkstemp' /usr/local/lib/libopencv_core.a(system.o): In function `cv::getTickCount()': system.cpp:(.text._ZN2cv12getTickCountEv+0x2a): undefined reference to `clock_gettime' /usr/local/lib/libopencv_highgui.a(grfmt_png.o): In function `cv::PngDecoder::readHeader()': grfmt_png.cpp:(.text._ZN2cv10PngDecoder10readHeaderEv+0xde): undefined reference to `png_set_longjmp_fn' /usr/local/lib/libopencv_highgui.a(grfmt_png.o): In function `cv::PngEncoder::write(cv::Mat const&, std::vector<int, std::allocator<int> > const&)': grfmt_png.cpp:(.text._ZN2cv10PngEncoder5writeERKNS_3MatERKSt6vectorIiSaIiEE+0x134): undefined reference to `png_set_longjmp_fn' /usr/local/lib/libopencv_highgui.a(grfmt_png.o): In function `cv::PngDecoder::readData(cv::Mat&)': grfmt_png.cpp:(.text._ZN2cv10PngDecoder8readDataERNS_3MatE+0x141): undefined reference to `png_set_longjmp_fn' collect2: ld returned 1 exit status make: *** [all] Error 1 I made something wrong or there an error in OpenCV library. OpenCV version: 2.3.1 (latest version) formas --> example which create an image an draw some figures and save into a file. So simple. Thanks in advance. A: It seems you have compiled OpenCV with libpng 1.4 or newer but trying to link with libpng 1.2 What cmake command have you used to configure OpenCV? Update: You need to add -lrt to the list of libraries you link for the clock_gettime function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing a helpbook outside of an application I am creating a Help Book for my application. What would help a lot is if I could take the *.help bundle and load it into the help view directly for testing without using the application's Help menu option first. Is this possible? A: There's no special way to do this other than to build and run your app, then request help. The only thing to test would be that the help index was created properly (by searching for keywords) anyway. The rest you can test in Safari. It'll look the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Possibility of Using Mono on Android for Android 1.5 I know that Mono on Android only officially supports Android 1.6 and above, but I was wondering if anyone had any experience or tips for trying to get it to work on Android 1.5? I've tried manually changing the manifest sdk version (even inside the sdk itself), but when I try to install the app, all I get is an unsupported SDK version. Note that I understand that officially Mono on Android does not support 1.6, but I'm looking for an [unsupported/experimental/hack] way to do it. I'd even settle for a generic apk sdk version change, but my google-fu could not find such a program (and who knows if it would even work with Mono). A: I think you can just set the Minimum Android to Target to 1.6, add an AndroidManifest.xml using the project properties, but then edit it manually in the Properties folder and change the minSdkVersion from 4 to 3. The Intellisense will still target 1.6, so you'll need to ensure you don't use any newer API. However, this is untested and unsupported. A: Answering my own question in case anyone else tries it. Mono on Android looks for a android.content.Context.getApplicationInfo, which was added in 1.6, so it seems that it's not possible to run Mono on Android on Android lower than 1.6.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: display a video from my webcam trying to implement circle detection I'm trying to display a video from my webcam (which was working grand) and now I'm trying to implement circle detection into this video stream. Unhandled exception at 0x001a1a4d in test.exe: 0xC0000005: Access violation reading location 0x00000004.) The error is linked to the line of code: cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 );. Can anyone help please? #include <stdio.h> #include "cv.h" #include "highgui.h" #include <iostream> #include <math.h> #include <string.h> #include <conio.h> using namespace std; IplImage* img = 0; CvMemStorage * cstorage; CvMemStorage * hstorage; void detectCircle( IplImage *frame ); int main( int argc, char **argv ) { CvCapture *capture = 0; IplImage *frame = 0; int key = 0; hstorage = cvCreateMemStorage( 0 ); cstorage = cvCreateMemStorage( 0 ); //CvVideoWriter *writer = 0; //int colour = 1; //int fps = 25; //int frameW = 640; //int frameH = 480; //writer = cvCreateVideoWriter("test.avi",CV_FOURCC('P', 'I', 'M', '1'),fps,cvSize(frameW,frameH),colour); //initialise camera capture = cvCaptureFromCAM( 0 ); //check if camera present if ( !capture ) { fprintf( stderr, "cannot open webcam\n"); return 1; } //create a window cvNamedWindow( "Snooker", CV_WINDOW_AUTOSIZE ); while(key !='q') { //get frame frame = cvQueryFrame(capture); //int nFrames = 50; //for (int i=0; i<nFrames;i++){ //cvGrabFrame(capture); //frame = cvRetrieveFrame(capture); //cvWriteFrame(writer, frame); //} //check for frame if( !frame ) break; detectCircle(frame); //display current frame //cvShowImage ("Snooker", frame ); //exit if Q pressed key = cvWaitKey( 20 ); } // free memory cvDestroyWindow( "Snooker" ); cvReleaseCapture( &capture ); cvReleaseMemStorage( &cstorage); cvReleaseMemStorage( &hstorage); //cvReleaseVideoWriter(&writer); return 0; } void detectCircle( IplImage * img ) { int px; int py; int edge_thresh = 1; IplImage *gray = cvCreateImage( cvSize(img->width,img->height), 8, 1); IplImage *edge = cvCreateImage( cvSize(img->width,img->height), 8, 1); cvCvtColor(img, gray, CV_BGR2GRAY); gray->origin = 1; // color threshold cvThreshold(gray,gray,100,255,CV_THRESH_BINARY); // smooths out image cvSmooth(gray, gray, CV_GAUSSIAN, 11, 11); // get edges cvCanny(gray, edge, (float)edge_thresh, (float)edge_thresh*3, 5); // detects circle CvSeq* circle = cvHoughCircles(gray, cstorage, CV_HOUGH_GRADIENT, 1, gray->height/50, 5, 35); // draws circle and its centerpoint float* p = (float*)cvGetSeqElem( circle, 0 ); cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 ); cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(200,0,0), 1, 8, 0 ); px=cvRound(p[0]); py=cvRound(p[1]); cvShowImage ("Snooker", img ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Two questions about CALayer * *with [myLayer setName:@"layer_1"] I set the name of a layer. But how can I get it from another method? Is there something like [self.view.layer.sublayers getLayerByName:@"layer_1"]? *how to animate a CALayer to move it to another position with a nice smooth effect? A: The name property is primarily intended for use by some layout managers, except layout managers don't exist on iOS, so all it's really useful for at this point is debugging. As for animation, if you're using a CALayer you created yourself, you'll get implicit animations when you change properties. You can set explicit animations using the CAAnimation subclasses, and you can also tweak some parameters of the implicit ones with CATransaction. If you're using a layer that's associated with a UIView, all implicit animations are disabled. You can still create explicit ones with the CAAnimation subclasses, or you can use the UIView animation methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use simple sqlalchemy calls while using thread/multiprocessing Problem I am writing a program that reads a set of documents from a corpus (each line is a document). Each document is processed using a function processdocument, assigned a unique ID, and then written to a database. Ideally, we want to do this using several processes. The logic is as follows: * *The main routine creates a new database and sets up some tables. *The main routine sets up a group of processes/threads that will run a worker function. *The main routine starts all the processes. *The main routine reads the corpus, adding documents to a queue. *Each process's worker function loops, reading a document from a queue, extracting the information from it using processdocument, and writes the information to a new entry in a table in the database. *The worker loops breaks once the queue is empty and an appropriate flag has been set by the main routine (once there are no more documents to add to the queue). Question I'm relatively new to sqlalchemy (and databases in general). I think the code used for setting up the database in the main routine works fine, from what I can tell. Where I'm stuck is I'm not sure exactly what to put into the worker functions for each process to write to the database without clashing with the others. There's nothing particularly complicated going on: each process gets a unique value to assign to an entry from a multiprocessing.Value object, protected by a Lock. I'm just not sure whether what I should be passing to the worker function (aside from the queue), if anything. Do I pass the sqlalchemy.Engine instance I created in the main routine? The Metadata instance? Do I create a new engine for each process? Is there some other canonical way of doing this? Is there something special I need to keep in mind? Additional Comments I'm well aware I could just not bother with the multiprocessing but and do this in a single process, but I will have to write code that has several processes reading for the database later on, so I might as well figure out how to do this now. Thanks in advance for your help! A: The MetaData and its collection of Table objects should be considered a fixed, immutable structure of your application, not unlike your function and class definitions. As you know with forking a child process, all of the module-level structures of your application remain present across process boundaries, and table defs are usually in this category. The Engine however refers to a pool of DBAPI connections which are usually TCP/IP connections and sometimes filehandles. The DBAPI connections themselves are generally not portable over a subprocess boundary, so you would want to either create a new Engine for each subprocess, or use a non-pooled Engine, which means you're using NullPool. You also should not be doing any kind of association of MetaData with Engine, that is "bound" metadata. This practice, while prominent on various outdated tutorials and blog posts, is really not a general purpose thing and I try to de-emphasize this way of working as much as possible. If you're using the ORM, a similar dichotomy of "program structures/active work" exists, where your mapped classes of course are shared between all subprocesses, but you definitely want Session objects to be local to a particular subprocess - these correspond to an actual DBAPI connection as well as plenty of other mutable state which is best kept local to an operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: State after login with JSF I am new to JSF and want to create the login part of an app. I have a login page where I validate logins against a database. That is fine, but I can not figure out the logic in the following part. A legal user should be redirected to her own profile page and non legal users to a common error page. How do I "transport" the identity from the login to the profile page. All the info I need for a profile page i can get from the database so I kind of want to transport a bean from the login to create a user dependent view. I have looked at tutorials online but could not find examples except for the even simpler example where there is no use of user identity and eg.password and username is simply matched against hard coded values. I think there is some underlying "idea" I don't get because this should ne simple, right ? A: Put it in a session scoped managed bean. Here's a basic kickoff example: @ManagedBean @SessionScoped public class ActiveUser { private User user = new User(); @EJB private UserService userService; public String login() { User found = userService.find(user); if (found == null) { setGlobalMessage("Invalid login, try again"); return null; } else { user = found; return "userprofile"; } } public void isLoggedIn() { return user.getId() != null; } // ... } You can intercept on its presence in a filter. See also * *Prevent accessing restricted page without login in Jsf2 *Is there any easy way to preprocess and redirect GET requests?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load .png image as ARGB_8888 bitmap Possible Duplicate: Android - Read PNG image without alpha and decode as ARGB_8888 In this tutorial I'm going through, a .png image is being loaded into a Bitmap object using BitmapFactory.Options.inPreferredConfig to set the Bitmap.Config to ARGB_8888 beforehand, but it doesn't appear to be working (tested the author's code - the image loads as an RGB_565 bitmap). BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; bitmapOrig = BitmapFactory.decodeResource(this.getResources(), R.drawable.sampleimage, options); What would be the correct way to do it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Different Links CSS Hover change a picture I would like a CSS hover affect for multiple links that affect the same image. If you look at this example site I have Repair, Sales, Upgrades and Data Recovery links. When you hover over any one of them I would like the image to their left to change. You can hover over the image currently there to see what I mean. website: http://ctuchicago.squarespace.com/ A: I would create a box that contains the image and all of the links. Then when the box is hovered over the image will change. This doesn't get you exactly what you want - which is only hovering over the link changes the image, but I think it is close enough and far easier. http://jsfiddle.net/mrtsherman/D5ZRs/ div:hover img { background: url('blah'); } <div> <img src="" /> <a href="">Repair</a> <a href="">Sales</a> </div> A: Put the image inside the a tag. Then use position: relative to position the image... for example a img{ position: relative; left: -50px; } A: Wrap the <p>, and <h3> tags inside the <a> tags. A: This seems to work... partially XD <div class="frontdiv fblankd"> <a href="/audio-video" id="hav" style="width: auto;"> <div style=" height: 80px; margin-left: 81px; background: white; color: black; "> <h3>AUDIO / VIDEO</h3> <p><a href="#music">Music Server</a>, <a href="#theatre">Home Theatre</a>, <a href="#zone">Zone Systems</a>, <a href="#remote">Universal Remote Control</a></p> </div> </a> </div> The basic idea is to have your content in the a tag (like ever body has been saying). What I've done with the styling is set the anchor to width:auto and wrapped the content in a div. this div I then gave a height of 80px, left margin of 81px, background of white and font color of black.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pipe output(stdout) from running process Win32Api I need to get (or pipe) the output from a process that is already running, using the windows api. Basically my application should allow the user to select a window to pipe the input from, and all input will be displayed in a console. I would also be looking on how to get a pipe on stderr later on. Important: I did not start the process using CreateProcess() or otherwise. The process is already running, and all I have is the handle to the process (returned from GetWindowThreadProcessId()). A: The cleanest way of doing this without causing any ill effects, such that may occur if you used the method Adam implied of swapping the existing stdout handle with your own, is to use hooking. If you inject a thread into the existing application and swap calls to WriteFile with an intercepted version that will first give you a copy of what's being written (filtered by handle, source, whatever) then pass it along to the real ::WriteFile with no harm done. Or you can intercept the call higher up by only swapping out printf or whichever call it is that the software is using (some experimentation needed, obviously). HOWEVER, Adam is spot-on when he says this isn't what you want to do. This is a last resort, so think very, very carefully before going down this line! A: Came across this article from MS while searching on the topic. http://support.microsoft.com/kb/190351 The concept of piping input and output on Unix is trivial, there seems no great reason for it to be so complex on Windows. - Karl A: Whatever you're trying to do, you're doing it wrong. If you're interacting with a program for which you have the source code, create a defined interface for your IPC: create a socket, a named pipe, windows messaging, shared memory segment, COM server, or whatever your preferred IPC mechanism is. Do not try to graft IPC onto a program that wasn't intending to do IPC. You have no control over how that process's stdout was set up, and it is not yours to mess with. It was created by its parent process and handed off to the child, and from there on out, it's in control of the child. You don't go in and change the carpets in somebody else's house. Do not even think of going into that process, trying to CloseHandle its stdout, and CreateFile a new stdout pointing to your pipe. That's a recipe for disaster and will result in quirky behavior and "impossible" crashes. Even if you could do what you wanted to do, what would happen if two programs did this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to make a standard Unix Filter using Ruby? I found this ruby problem on RubyQuiz, which states besides the problem itself, the following: "The script should be a standard Unix filter, reading from files specified on the command-line or STDIN and writing to STDOUT. Each line of input will contain one integer (between 1 and 3999) expressed as an Arabic or Roman numeral" I have no idea how to do a Unix Filter using Ruby.. to read files in this case, Could somebody please enlighten me on how to accomplish this task in the best way possible. Thanks as always! A: The best way to read files from STDIN is using ARGF, as explained in this answer: Best practices with STDIN in Ruby? You can write to STDOUT using puts or printf. For more detailed info about IO in Ruby, read the Ruby Doc: http://www.ruby-doc.org/core/classes/IO.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7603812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't connect to Derby database if derby.jar is in Eclipse workspace I've been trying to create a Derby DB via Eclipse Data Tools Platform and at the beginning I couldn't manage to get it to work.. no matter what I did, I always got the same error: Could not connect to New Derby. Error creating SQL Model Connection connection to New Derby. (Error: null) java.lang.NullPointerException Error creating JDBC Connection connection to New Derby. (Error: null) java.lang.NullPointerException While I was trying this the derby.jar file containing the driver was inside "workspace/myproject/lib" folder. Then I put the same exact file to my Desktop, set the driver to point to the new location of my derby.jar and all started to work automagically... I did some experiments and it happens that it works everywhere EXCEPT when I put inside my Eclipse workspace folder. Why? And most important: if I want to deploy my application on different machines do I need the derby.jar inside my project folder (and thus inside the .jar of my project)? Thanks in advance to everyone EDIT: I already added derby.jar to the project through Eclipse interface, here's how: A: You have to add the jar file using eclipse's interface. This website shows how: http://www.cs.duke.edu/courses/cps004g/fall05/assign/final/addlibrary.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7603813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete records based on dates I have a database "DB" and I want to delete records from table "MyRecords" which are of future ("RecordDates" which are more than today just to avoid date change on system) and less than x no. of days from today. That "x" may vary. Moreover, I want to execute same type of command with month and year also. I am using SQL Server and C#. A: To delete records which are in the future and less than n days in the future you could use T-SQL such as this: DELETE FROM DB.table WHERE (date > GETDATE() AND date < DATEADD(day, 5, GETDATE())); In this case n is 5. You can see all the arguments to DATEADD() at DATEADD (Transact-SQL) A: This query will delete all records that are later than today's date, but less than 30 days in the future. You could replace "30" with a variable so you could determine how many days in the future to delete. DELETE FROM Table WHERE TABDate > GETDATE() and TABDate < DATEADD(day, 30, GETDATE()) UPDATE To delete all records less than 30 days in the past, you would change the query to look like this: DELETE FROM Table WHERE TABDate > DATEADD(day, -30, GETDATE()) AND TABDate < GETDATE() Also note that all these examples are calling GETDATE() which also has a time component as well as a date, so care must be taken in that anytime you see a statement like < GETDATE() you are not just deleting records with a date before, say, 2011-09-29, you are deleting all records with a date before '2011-09-29 17:30'. So be aware of that if you table dates contain times as well. A: You can use the query DELETE FROM DB.table WHERE date > now() or WHERE date > unix_timestamp(), depending on how you are storing your dates. (i.e. date-time vs. timestamp).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NullPointerException in Thread's run method I would really appreciate help with my program. It is some sort of chat server with multiple clients. Here's the server code: package com.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static int PORT; private ServerSocket server; private Socket socket; public Server(int port) throws IOException { PORT = port; server = new ServerSocket(PORT); System.out.println("server started"); try { while (true) { socket = server.accept(); try { new ServeClient(socket); } catch (IOException e) { socket.close(); } } } finally { server.close(); } } public static void main(String[] args) throws IOException { int port = Integer.parseInt(args[0]); Server server = new Server(port); } } I start the server and then create a Client. The server receives connection socket from socket and creates a ServeClient Thread. Here's ServeClient code: package com.server; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.Enumeration; import java.util.Vector; import com.gui.WindowManager; public class ServeClient extends Thread { private final Socket socket; private BufferedReader in; private PrintWriter out; private String msg; public static final String ENDSTRING = "END"; public static Vector clients = new Vector(); public ServeClient(final Socket socket) throws IOException { this.socket = socket; System.out.println("socket " + socket); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())), true); start(); } public void run() { try { clients.add(this); while (true) { msg = in.readLine(); if (msg == ENDSTRING) break; broadcast(msg); } System.out.println("closing..."); } catch (IOException e) { System.err.println("IO EXCEPTION"); } finally { try { socket.close(); } catch (IOException e) { System.err.println("SOCKET NOT CLOSED"); } } } @SuppressWarnings("deprecation") public void broadcast(String msg) { synchronized (clients) { Enumeration<ServeClient> e = clients.elements(); while (e.hasMoreElements()) { ServeClient serveClient = e.nextElement(); try { synchronized (serveClient.out) { serveClient.out.println(msg); } } catch (Exception eee) { serveClient.stop(); } } } } } What i get is a NullPointerException when ServeClient invokes run() method server started socket Socket[addr=/127.0.0.1,port=51438,localport=8888] Exception in thread "Thread-0" java.lang.NullPointerException at com.server.ServeClient.run(ServeClient.java:33) line 33 is the line with first "try" statement in ServeClient run() method A: com.server.ServeClient.run(ServeClient.java:33) I don't believe that it's happening at the try. Open up an IDE, turn on debugging, and step through until you can see what's happening. That's the fastest way to figure out what you've missed. There's an object that you're assuming is fine that is not. Find it. Here's an example of how to do this properly: http://www.kodejava.org/examples/216.html A: Your problem is with the order in which static instance variables are initialised. Try doing something like: ... private static Vector clients = null; ... if (clients==null) { clients = new Vector(); // consider putting this in a synchronized block } before you add the client to the vector. A: Sorry for necroing such an old issue but it seemed like this problem wasn't resolved, so I'll give a bit of input from my end. I've had a similar problem and the compiler also kept telling me that the problem was at the start() method. However, when I commented out the thread part and just ran the code on the same thread as the UI, the compiler directed me to the real source of the problem: the code inside the thread. After making sure the code didn't give an error, I enclosed the code with the original thread code, and it stopped giving me the NullPointerException error. Hope this helps someone along the way. A: Remove the duplicate class declaration in JPanel. I was trying to run a timer thread that updated a clock in the main application window. I had created the JFrame with Eclipse/WindowBuilder and had followed a tutorial on how to make a timer. I had copied the declaration of the textfield into the class declaration to make it available for the entire class, but forgot to remove the Class Id in front of the widget definition. So it still initialized the local instance and not the global one. Thus when I accessed the global one it was still null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does regex [\0-\uffff] capture? As I am reading through someone else's JavaScript, I encountered this regex charset: [\0-\uffff] What exactly is captured by this? A: That logical group will match every Unicode character between null and 0xffff Nothing will actually be captured. For that you will have to use ( and ) A: The set of characters whose code is within 0 to 0xffff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }