text
stringlengths
8
267k
meta
dict
Q: Celery-Django: Unable to execute tasks asynchronously I'm trying to run some tasks in the background while users browse my site, but whenever I call a function using Celery it seems to be executed synchronously instead of asynchronously. e.g., when I call function.delay() the entire site hangs until function.delay() returns. Other methods of calling functions in a similar manner (apply_async, subtasks) exhibit the same problem. I'm guessing something in either Django or Celery is misconfigured, but I don't know what it is. Celery configuration in settings.py: import djcelery djcelery.setup_loader() CELERY_RESULT_BACKEND = "amqp" CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" BROKER_HOST = "localhost" BROKER_PORT = 5672 BROKER_USER = "test" BROKER_PASSWORD = "test" BROKER_VHOST = "testhost" TEST_RUNNER = "djcelery.contrib.test_runner.run_tests" CELERY_IMPORTS = ("myapp.tasks",) BROKER_BACKEND = "memory" CELERY_ALWAYS_EAGER = True Trying to start the Celery daemon with "./manage.py celeryd", I get the following output: [2011-09-23 09:25:38,026: WARNING/MainProcess] -------------- celery@iMac.local v2.2.7 ---- **** ----- --- * *** * -- [Configuration] -- * - **** --- . broker: memory://test@localhost:5672/testhost - ** ---------- . loader: djcelery.loaders.DjangoLoader - ** ---------- . logfile: [stderr]@WARNING - ** ---------- . concurrency: 4 - ** ---------- . events: OFF - *** --- * --- . beat: OFF -- ******* ---- --- ***** ----- [Queues] -------------- . celery: exchange:celery (direct) binding:celery [2011-09-23 09:25:38,035: WARNING/MainProcess] celery@iMac.local has started. A: Try removing CELERY_ALWAYS_EAGER = True You are explicitly asking celery to execute tasks synchronously. It'll always wait for the result. This setting is useful for writing unit tests etc. Read http://ask.github.com/celery/configuration.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7505846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trim/erase/removal links from string with regex i have a really simple question, that ... is giving me a hedache ... I just want to trim all links (www.link.com) (http://www.link.com) (http://link.com) ... wathever, from a given string with this regex: $regex = "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"; Just turn them in whitespace. This is my actual code that wont work ... <?php $string = 'ads dsa asd asd as da ds www.something.com adss dsad a sdas d'; $pattern = "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"; $replacement = ' nothing '; echo preg_replace($pattern, $replacement, $string); ?> it keep saying me that ( ! ) Warning: preg_replace() [function.preg-replace]: Unknown modifier ':' in C:\wamp\www\ceva.php on line 9 Call Stack # Time Memory Function Location 1 0.0005 363504 {main}( ) ..\ceva.php:0 2 0.0005 363952 preg_replace ( ) ..\ceva.php:9 Any help would be appreciated :D A: Patterns for regex's in php need to be surrounded by a delimiter to show where the pattern starts and stops and the modifiers (case insensitive, multiline...etc) start. Most commonly you will see the forward slash as the delimiter, but most any character will work. An example patter might be: /pattern[a-z]*/i. Notice the first character is a forward slash (/) and the pattern itself ends with the same character (/) and after that only modifiers are expected such as i for case insensitive..etc (see: pattern modifiers). Whatever the first character is, is the delimiter and the pattern part must end with the same character as the ending delimiter. What the error you are seeing means is that your first character, which is an open parenthesis, is the delimiter. After the next open parenthesis, everything after that should be a modifier. The error is saying that there is an invalid modifier after the ending delimiter. To fix this, you should be able to just put a delimiter around the regex and it should work. See Delimeters and for a general reference of php regular expressions. Edit: I was wondering why you were getting an error regarding the colon as the problem character. Apparently php also supports bracket style delimiters such as { and }. With the open parenthesis being the delimiter, the closing parenthesis is the ending delimiter. The following characters are expected to be delimiters and the pattern throws an error when the first character after the closing delimiter, the colon is reached because it is an invalid modifier. TIL. A: Looks like it's unhappy with the colons. Try backslash escaping the ones in your regex (so turn ":" into "\:". A: This is very very simple but may be enough, it just assumes there's a whitespace after the link <?php $string = 'here goes 1 http://google.com and 2 http://www.google.com and also 3 www.google.com?q=asd& and thats it'; $pattern = '/((http|ftp|https):\/\/(www\.)?|www\.)[^\s]*/'; $return = preg_replace($pattern, '<link>', $string); var_dump($return); ?> A: You forgot the delimiters around the regex: instead of : $pattern = "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"; try: $pattern = "/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&amp;\/~\+#]*[\w\-@?^=%&amp;\/~+#])?/"; or $pattern = "{(ftp|https?)://[-\w]+(\.[-\w]+)+([-\w.,@?^=%&;/~+#]*[-\w@?^=%&;/~+#])?}";
{ "language": "en", "url": "https://stackoverflow.com/questions/7505849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to force $.toggle() to consistently toggle already hidden children? I have an application where data sets can be filtered at various levels, and--for performance reasons--it would be nice to be able to toggle the respective display of nested divs independently. The issue arises in that toggle will change the display property back to its original state on a hidden child, but it will not change it to none if one of its ancestors is already hidden. To replicate: in this JSFiddle, * *Click the "toggle 3" button, and then the "toggle 2" button. *Clicking the "toggle 3" button and then the "toggle 2", you will find 3 restored (as expected). *Now click the "toggle 2" button, then the "toggle 3". *On clicking "toggle 2" again, 3 is still visible (???). A: toggle can take a boolean $(selector).toggle(false); http://api.jquery.com/toggle/ .toggle( showOrHide ) showOrHideA Boolean indicating whether to show or hide the elements. UPDATE You can achieve the functionality you want by creating a simple hidden css class calling toggleClass() rather than using toggle(). toggle() seems to skip its own functionality entirely if the element in question is not visible. http://jsfiddle.net/hunter/GufAW/3/ $("#toggle-1").click(function() { $("#1").toggleClass("hidden"); }); $("#toggle-2").click(function() { $("#2").toggleClass("hidden"); }); $("#toggle-3").click(function() { $("#3").toggleClass("hidden"); }); A: Try toggling the css display property directly: http://jsfiddle.net/GufAW/5/ $("#toggle-1").click(function() { $("#1").css("display", ($("#1").css("display")==="none") ? "block" : "none"); }); $("#toggle-2").click(function() { $("#2").css("display", ($("#2").css("display")==="none") ? "block" : "none"); }); $("#toggle-3").click(function() { $("#3").css("display", ($("#3").css("display")==="none") ? "block" : "none"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7505853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: custom nested routes with Kohana 3 I have a Articles model and a Category model, both with a url_slug variable (what I would like to show up in the url when looking for it. here is how I would like to have the URLs appear: //list all of the articles http://example.com/articles //list of all the articles in that category http://example.com/articles/:category_slug //a single article. http://example.com/articles/:category_slug/:article_slug How should I set up the articles controller and/or the routes in order to achieve this? A: You can use a route like this Route::set('articles', '/articles(/<category_filter>(/<article_id>))', array( 'controller' => 'Articles', 'action' => '(index)' )) ->defaults(array( 'controller' => 'Articles', 'action' => 'index', )); In your controller, you can access the filters/ids with $category = Request::current()->param('category_filter'); $article_id = Request::current()->param('article_id'); And filter your output accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Video playback gives black screen but with sound I'm stumped. I'm trying to play video with the Media Player but while the audio plays, all I get is a black window. I've seen other posts about this problem but I haven't been to find a solution. I have tried to follow their suggestions. The mediaplayer is prepared before playback. The surface holder was created and set to the media player's display before playback. Tested on a Samsung Galaxy Tab and a Samsung Galaxy S. I'm compiling against API level 7. The video itself can be played in device's video application from the sdcard, so it should be compatible. The surface view is not the same size as the video. So that might be an issue. Do I need to do something about that or is stretching handled automatically? Here's what I have in my initialization: RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height); lp.leftMargin = x; lp.topMargin = y; mSurfaceView = new SurfaceView(mActivity); mSurfaceView.requestFocus(); mSurfaceView.setZOrderOnTop(true); mSurfaceView.getHolder().addCallback(player); mSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mLayout.addView(mSurfaceView, lp); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(), assetDescriptor.getStartOffset(), assetDescriptor.getLength()); mMediaPlayer.setOnErrorListener(player); mMediaPlayer.setOnPreparedListener(player); mMediaPlayer.prepare(); and here are my callbacks: public void onPrepared(MediaPlayer mp) { mMediaPlayer.start(); } public void surfaceCreated (SurfaceHolder holder) { mMediaPlayer.setDisplay(holder); } What's frustrating is that a version of the code was working properly a while ago, but now it's not. A: I had a similar problem, and was related to the video format (codec MP4, WMV, AVI, etc). Try running the video on default player of the Android, see if that works. If not works, then it may be problem in video codec. Do not try to run the video on players like VLC or Player MX, they have embedded codec.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What versioning strategy to adopt for a project that is customized for different clients? I am curious about what source versioning strategy would others apply on a java project (web application) which is very probable to have customization for several customers. The project will have a standard version, but for some of its customers there will be some customizations to be done (on different branches). By reading this thread : What branching strategy should I use during the development/maintenance of a web application? I guess that the "Branch by release" would fit for the development of the standard version of the project. Now while working on a customer branch there are some improvements/bugfixes performed on the code on which other customer/standard version would benefit this would mean that for each of the branches there will be merges & tests to be performed in order to be keep everything up to date. As a constraint, for this project we are stuck with CVS as a source versioning system. For versioning of the artifacts which are built we'll use maven (dependy : artifactId, groupId, version, classifier - customer name - in order to clearly distinguish the artifacts). A: I would recommend creating a branch per customer AND a branch per feature and letting your trunk represent your "standard version". Any small bug fixes would be merged back to the trunk and subsequently propagated out to all branches. The same would hold true for new features, as you would merge them back to the trunk and kill the branch. All your customer branches would be long-living, and you would make your customer-specific customizations there and would release from those branches.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why the shape of cursor is wrong during my drag-drop operation I have some code to do drag-drop between items of two list boxes. which I got it to work finally. so it is doing the drag-drop But the shape of the cursor icon is Wrong. for example when I am doing the "drop" on the second list box the icon is still that Stop Circle or whatever its name is. not sure. but yea the icon of the cursor is wrong. Any thoughts how can I fix this? A: In the DragEnter event of the ListBox you can set the DragEventArgs.Effect to a DragDropEffects value: private void ListBox1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; } A: Not sure what control you are using, but aside from setting the correct DragDropEffect, if you are using the RichTextBox and have EnableAutoDragDrop = true, I noticed some issues where it wants to do a Move from some sources that don't allow it. Holding down [ctrl] switches the dragdrop mode to Copy and allows you to drop it in the target control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Getting raw HTML / adding Javascript to WebView pages I have a mobile flow for registration that I want to use in my app, and I do not have control of the source -- I am looking for a way to grab a few pieces of data when the user finishes registering, (confirmation number, etc.) that will be sent to my app (hopefully via Android's addJavascriptInterface) I am certain on one thing - the id of the element I need. The flow could change, and is already a few pages long, So I'm looking for a general solution. The basic Idea I'm hoping for is this: Inject a JavaScript snippet to each page during shouldOverrideUrlLoading, which will automatically call my JavaScript Interface and check for the value of the field with the id I'm looking for. (or just return the entire HTML, and I'll do it in Java) view.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { //inject javascript here to get value return false; }}); I've seen tutorials on using addJavascriptInterface, but they all seem to assume some control or understanding of the 'single' page that will be navigated to. Since I have a potentially lengthy flow (3+ pages) and no control over the source, I am interested in hearing any suggestions. A: Check URL of the current page and if it's the right one insert JavaScript in the curent page. With the help of Java-JS binding you could get some data out. See my previous answer: Determine element of url from webview shouldOverRideUrlLoading
{ "language": "en", "url": "https://stackoverflow.com/questions/7505868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to receive an uploaded file using node.js formidable library and save it to Amazon S3 using knox? I would like to upload a form from a web page and directly save the file to S3 without first saving it to disk. This node.js app will be deployed to Heroku, where there is no local disk to save the file to. The node-formidable library provides a great way to upload files and save them to disk. I am not sure how to turn off formidable (or connect-form) from saving file first. The Knox library on the other hand provides a way to read a file from the disk and save it on Amazon S3. 1) Is there a way to hook into formidable's events (on Data) to send the stream to Knox's events, so that I can directly save the uploaded file in my Amazon S3 bucket? 2) Are there any libraries or code snippets that can allow me to directly take the uploaded file and save it Amazon S3 using node.js? There is a similar question here but the answers there do not address NOT saving the file to disk. A: It looks like there is no good way to do it. One reason might be that the node-formidable library saves the uploaded file to disk. I could not find any options to do otherwise. The knox library takes the saved file on the disk and using your Amazon S3 credentials uploads it to Amazon. Since on Heroku I cannot save files locally, I ended up using transloadit service. Though their authentication docs have some learning curve, I found the service useful. For those who want to use transloadit using node.js, the following code sample may help (transloadit page had only Ruby and PHP examples) var crypto, signature; crypto = require('crypto'); signature = crypto.createHmac("sha1", 'auth secret'). update('some string'). digest("hex") console.log(signature); A: this is Andy, creator of AwsSum: * *https://github.com/appsattic/node-awssum/ I just released v0.2.0 of this library. It uploads the files that were created by Express' bodyParser() though as you say, this won't work on Heroku: * *https://github.com/appsattic/connect-stream-s3 However, I shall be looking at adding the ability to stream from formidable directly to S3 in the next (v0.3.0) version. For the moment though, take a look and see if it can help. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7505871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: $.ajax sends null parameters to wcf in IE I have the interface below that defines my WCF services. Sometimes the 'parameters' parameter has been null when this is called. Other times it is not. [ServiceContract] public interface IContactRelationshipManager { [OperationContract] [WebInvoke( Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] void SaveActivityLogEntry(SaveActivityLogEntryParameters parameters); } Here is my behaviors section in the app.config (I'm running this as a windows service) <behaviors> <endpointBehaviors> <behavior name="jsonBehavior"> <webHttp /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="ContactRelationshipManagerBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> Here is my javascript call: $.ajax( { type: "POST", cache: false, contentType: "application/json", url: serviceCallUrl, data: JSON.stringify(params), success: callbackHandler }); The result of JSON.stringify(params) is "{"parameters":{"ContactEmailAddress":"blah@gmail.com","LiasonsForContact":[25],"ActivityLogEntry":{"Date":"/Date(1316634966273)/","LiasonFK":25,"TypeFK":1,"MethodFK":3,"Description":"tt","ContactFK":32}}}" Is there anything that I'm doing wrong here in practice? This works fine all the time in chrome and firefox. I also just tested this with Fiddler while debugging the service and the parameter came back null with Fiddler closed and NOT null when Fiddler is open. A: I ended up playing with a bunch of different techniques to get it to work including taking a stream as my function parameter and serializing it inside the function with JSON.NET. That didn't work either. I finally found this question which led me to believe that it was an NTLM problem. My website uses windows authentication in IIS7 and it calls a WCF service hosted as a windows service. On the server side I changed the security on my webHttpBinding to be as such: <binding name="webBinding"> <security mode="TransportCredentialOnly"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> </security> </binding> After doing this everything works fine in Internet Explorer A: Can you use Fiddler, for example, to sniff what's actually being sent? I normally pass a data object directly to $.ajax and let it handle serializing the object. I have a guess that the stringified JSON is being encoded inappropriately. A: I actually have not had any problems, you have all the required configurations except your missing a few properties in your ajax call. I don't know if this might help. contentType: "application/json; charset=utf-8" dataType: "json" processData: false
{ "language": "en", "url": "https://stackoverflow.com/questions/7505884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loop through fields in jQuery to look for required fields I'm used to working with jQuery and check every field individually. But now I've many different forms on a website and I'd like to write one function that would loop through all fields who have a class name "required". If one of the field has the class required and is empty, append a class "error" to that field. How would I go about doing that ? Thanks in advance! A: Like this: function markEmptyRequiredFields (form) { $('.required', form).val(function(index, value) { if (value == "") { $(this).addClass("error"); } } } Usage: markEmptyRequiredFields($("#myformId")); A: In your submit handler: $('.required').each(function() { var $this = $(this); if(!$this.val()) $this.addClass('error'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7505886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using unordered map find function If I want the unordered map find function to return a bool value, how would I go about doing that? Here's my code right now. bool NS_SymbolTable::SymbolTable::Contains(std::string lexeme) { SymbolTable *tempSymbolTable = this; std::unordered_map<std::string, Identifier*>::iterator it = tempSymbolTable->hashtable.find(lexeme); return std::boolalpha; } What else do I neeed to do ? Is it possible to return a bool? There is little to no documentation on this that I have found. This is where I got an example from http://msdn.microsoft.com/en-us/library/bb982431.aspx A: tempSymbolTable->hashtable.find(lexeme) will return tempSymbolTable->hashtable.end() if it fails, so you can convert this result to a bool very simply: return tempSymbolTable->hashtable.find(lexeme) != tempSymbolTable->hashtable.end(); Also, assigning this to a temporary variable and working through that is unnecessary. Your function can be reduced to: bool NS_SymbolTable::SymbolTable::Contains(std::string lexeme) { return hashtable.find(lexeme) != hashtable.end(); } A: bool NS_SymbolTable::SymbolTable::Contains(std::string lexeme) { SymbolTable *tempSymbolTable = this; return tempSymbolTable->hashtable.end() != tempSymbolTable->hashtable.find(lexeme); } A: You need to test the return value of find against tempSymbolTable->hastable.end(), if they are equal then it did not find your element. The reason find works like this is because in its current form it is more general than something that returns only a bool. A: For documentation look std::unordered_map::find. There it says: Return value iterator to an elements with key key. If no such element is found, past-the-end (see end()) iterator is returned. To get boolean value indicating whether an element is present, use bool contained = it != tempSymbolTable->hashtable.end(); A: std::unordered_map::find(), like the rest of the standard containers' find functions, returns end() on failure. Try this: bool NS_SymbolTable::SymbolTable::Contains(std::string lexeme) { SymbolTable *tempSymbolTable = this; std::unordered_map<std::string, Identifier*>::iterator it = tempSymbolTable->hashtable.find(lexeme); return it != tempSymbolTable->hashtable.end(); } Reference: * *MSDN unordered_map::find *MSDN unordered_map::equal_range EDIT: change sense of return value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery json select - setting a select option to a whole json element, not just a value from it i'm going through a json javascript object to create the options for a select. it works ok if i use 1 element, like so (this is in my 'success' from the ajax call.... getting the data from php)... var my_json = JSON.parse(data); for (var a=0; a < my_json.length; a++) { $('#my_list') .append($('<option', { value: my_json[a].SOMEFIELD } ) .text(my_json[a].SOMEOTHERFIELD)); } That works fine, but instead of setting the value to just 1 field, i want to set: value: my_json[a] and pass 6 or 7 fields as the option value... - problem is, in my onclick function for the select, i can get the val from the select and see it's an object, but trying to get any field out of it seems to be undefined.... passed_data = $('#my_list').val(); var passed_id = passed_data[0].ID; and tried... var passed_id - passed_data[ID]; etc... they're undefined.... i can see "passed_data" is an object, but can't seem to get any fields out of it... A: If I got what you are trying to say, you need one select to have multiple values in the value? If this is the case I would suggest to add custom attributes to each of your select items, and then just read them. Something like the following: $("#SelectBox").append($("<option />").val("OriginalValue").text("RandomText").attr("CustomAttribute","CustomAttributesValue")); To retrieve the custom attributes you can do it like this: $("#SelectBox").change(function() { alert($(this).find("option:selected").attr("CustomAttribute")); }); This will return the CustomAttribute for each Select Item. Hopefully this helps and it is what you are asking. If not, could you clarify the question? Thanks EDIT: Doing this may break the page's DOCTYPE which means the page's XML is not correct. You could ammend it and add your custom attributes. Your page will render all the time (don't take me wrong) but it is not valid. Check this out if you care about the XML being correct A: thanks guys. i ended up setting the value of the option to a (my counter variable in the for loop). then i made the var my_json global. that way, in my onchange function for the select, i just do: var passed_element_number = ($'#my_select_list').val(); var passed_id = my_json[passed_element_number].ID; var passed_otherfield = my_json[passed_element_number].OTHERFIELD; i'm not sure why it wasn't letting me set the who json object as the value for the select option and then get the fields out 1 by 1 (probably my error, or maybe it's not possible), but this works ok.... A: It's pretty mmuch unreadable, please edit and click on the "code" button. Anyway, from what i've read, i dont know if it will solve your problem, but using $.each is better i believe : var my_json = JSON.parse(data); $.each(my_json, function(){ $('#my_list').append($(this).SOMETHING); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7505893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setup Shards: Should I install MongoDB on the following servers Following the Oreily Scaling MongoDB book (i.e. Page 27), I saw the following command: Once you’re connected, you can add a shard. There are two ways to add a shard, depending on whether the shard is a single server or a replica set. Let’s say we have a single server, sf-02, that we’ve been using for data. We can make it the first shard by running the addShard command: > db.runCommand({"addShard" : "sf-02:27017"}) { "shardAdded" : "shard0000", "ok" : 1 } Question 1>: What should be done on the servers of sf-02? Should I also install MongoDB on it? If any, which package? For example, if we had a replica set creatively named replica set “rs” with members rs1-a, rs1-b, and rs1-c, we could say: > db.runCommand({"addShard" : "rs/rs1-a,rs1-c"}) { "shardAdded" : "rs", "ok" : 1 } Question 2>: where is "rs" located? Question 3>: Does rs1-a, rs1-c share the same machine? A: reply 1: you should run mongod with the --shardsvr option to start it as a shard server. each shard server has to know that it is will receive a connection from a mongos (the shard router). reply 2: 'rs' is the name of a replica set, a set is just a group of machine (usually 3). so it is not located on a single machine, it is an abstract entity which represent the group of machine in the set. reply 3: no. for testing purpose you can run replica set on the same machine, but the purpose of a replica set is failover. in production you should use different machine for every member of the set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Value From Dynamic Control in Page Asp.Net I have a dynamically created bill of material with each line item being a dynamic user_control. the user_control has a textbox for quantity entry. When I click the submit button i'd like to get all the quantities from each textbox but the controls have all disappeard on the page load and the page shows zero controls. I know you can turn on autopostback for the textbox then catch each individual text_changed_event but that doesn't seem efficient. I'd like to just loop through all of them when user clicks submit button, then take them back to the same bill of material page. A: First of all the reason why controls disappear on postback is that they were added to your page dynamically and when postback occurred the information about the dynamic controls were lost and page had no information about these dynamic controls. Now about getting the values from controls inside dynamic user controls, you have use the FindControl method or have to iterate through the Controls collection of user control to get the reference to TextBoxes. An idea about how to do this: //1. Using ID of user control //inside button_click method protected void btnSubmit_Click(...) { TextBox txt1 = idOfUserControl.FindControl(textBoxId); } //2. Using type of user control //inside button_click method protected void btnSubmit_Click(...) { foreach(Control c in Page.Controls) if(c is YourUserControlClass) { YourUserControlClass control = (YourUserControlClass)c; TextBox txt1 = c.FindControl(textBoxId); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django tutorial. 404 on Generic Views Update: Using Django 1.2.1 and Python 2.5.2 as offered by Dreamhost. I'm having issues with the last part of the Django tutorial where the urls.py is changed to use generic views. After I change the code I get 404's on the pages and even the index stops working. I have gone over all of my templates to see if that was the issue but I removed any instance of poll and replaced it with object. I have also attached the template for the index/object_list. I am running this on Dreamhost and the static urls I set with views worked fine. urls.py from brsplash.models import Poll from django.conf.urls.defaults import * from django.contrib import admin from django.views.generic import * admin.autodiscover() info_dict = { 'queryset': Poll.objects.all(), } urlpatterns = patterns('', (r'^$', 'django.views.generic.list_detail.object_list', info_dict), (r'^(?P<object_id>\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict), url(r'^(?P<object_id>\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='brsplash/results.html'), 'poll_results'), (r'^(?P<poll_id>\d+)/vote/$', 'brsplash.views.vote'), ) urlpatterns += patterns('', (r'^admin/', include(admin.site.urls)), poll_list.html {% if object_list %} <ul> {% for object in object_list %} <li><a href="{{ object.id }}/">{{ object.question }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available</p> {% endif %} A: Django 1.3 introduced class-based generic views which will replace this function-based approach (see the note at the top of the documentation page) so perhaps it's best to use them instead. With the class-based approach, your new detail-page url would look something like this: from brsplash.models import Poll ... from django.views.generic import ListView urlpatterns = {'', url(r'^$', ListView.as_view(model=Poll)), ... } This approach can be found in part 4 of the tutorial. N.B.: I tend not to pass the template_name argument to as_view because, as stated in the docs: ListView generic view uses a default template called <app name>/<model name>_list.html A: You can upgrade to Django 1.3 on Dreamhost: blog.oscarcp.com/?p=167 – jturnbull Sep 22 at 9:54 This fixed my issue with the urls.py issue I was having. Once I upgraded to 1.3.1 and changed the code to reflect it, my pages came back.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concatenating string content VALUES of multiple arraylists . Strange problem I have many Arraylists having String objects , and I have a requirement to concatenate there values. Eg: ArrayList finalList = new ArrayList(); ArrayList catMe = new ArrayList(); ArrayList x = new ArrayList(); x.add("Green"); x.add("Red"); ArrayList y = new ArrayList(); y.add(" Apple"); //...... catMe.add(x); catMe.add(y); concatContents(catMe); // Here i need to do // some concatenation magic. so when finalList is printed: finalList.get(0) // should show > "Green Apple" finalList.get(1) // should show > "Red Apple" I know it looks easy if there are only two list X and Y... but I need it for n dimensions. Say if there is 3rd list ArrayList z= new ArrayList(); z.add(" USA"); z.add(" Canada"); catMe.add(z); concatContents(catMe); Now finalList should show Green Apple USA Green Apple Canada Red Apple USA Red Apple Canada Do i need recursion? Unable to think how to implement though! Do any java master there have a solution? A: something like this should work. (I did not actually compile this, wrote it as sorta pseudo code for simplicity. take care of generics and proper types list List>) List<ArrayList> lists; // add all your lists to this list ArrayList<String> final_list; // your final list of concatenations for (int i=0; i<list1.size(); i++) { String temp = "" for (ArrayList current_list : lists) { temp += " " +current_list.get(i); } final_list.add(temp); } EDIT -- okay so the code above was bit stupid, i had not understood the question correctly. Now as others have posted the recursive solutions, I thought would pay off by posting a non recursive working solution. So here is the one that works exactly as expected public static void main(String[] args) { ArrayList<String> finalList = new ArrayList<String>(); ArrayList<String> x = new ArrayList<String>(); x.add("Green"); x.add("Red"); ArrayList<String> y = new ArrayList<String>(); y.add(" Apple"); ArrayList<String> z = new ArrayList<String>(); z.add(" USA"); z.add(" Canada"); finalList = concat(x, y, z); System.out.println(finalList); } static ArrayList<String> concat(ArrayList<String>... lists) { ArrayList<String> result = new ArrayList<String>(); for (ArrayList<String> list : lists) { result = multiply(result, list); } return result; } static ArrayList<String> multiply(ArrayList<String> list1, ArrayList<String> list2) { if (list2.isEmpty()) { return list1; } if (list1.isEmpty()) { return list2; } ArrayList<String> result = new ArrayList<String>(); for (String item2 : list2) { for (String item1 : list1) { result.add(item1 + item2); } } return result; } A: Here's a recursive answer. Just cooked it up, so no guarantees on quality... :) public ArrayList<String> concatLists(ArrayList<ArrayList<String>> list) { ArrayList<String> catStrs = new ArrayList<String>(); int len = list.size(); if (len == 1) { catStrs.addAll(list.get(0)); return catStrs; } ArrayList<String> myStrs = list.get(0); ArrayList<ArrayList<String>> strs = new ArrayList<ArrayList<String>>(); strs.addAll(list.subList(1, len)); ArrayList<String> retStrs = concatLists(strs); for (String str : myStrs) { for (String retStr : retStrs) { catStrs.add(str+retStr); } } return catStrs; } A: Quick and dirty solution: public class Lists { public static void main(String[] args) { List<List<String>> finalList = new ArrayList<List<String>>(); List<String> x = new ArrayList<String>(); x.add("Green"); x.add("Red"); x.add("Purple"); List<String> y = new ArrayList<String>(); y.add("Apple"); List<String> z = new ArrayList<String>(); z.add("USA"); z.add("UK"); z.add("France"); finalList.add(x); finalList.add(y); finalList.add(z); for (String s: concat(finalList)) { System.out.println(s); } } private static List<String> concat(List<List<String>> inputList) { if (inputList.size() == 1) { return inputList.get(0); } else { List<String> newList = new ArrayList<String>(); List<String> prefixes = inputList.get(0); for (String prefix : prefixes) { for (String concat : concat(inputList.subList(1,inputList.size()))) { newList.add(prefix + " " + concat); } } return newList; } } } gives: Green Apple USA Green Apple UK Green Apple France Red Apple USA Red Apple UK Red Apple France Purple Apple USA Purple Apple UK Purple Apple France A: Here is my simple implementation: List<ArrayList<String>> lists= new ArrayList<ArrayList<String>>(); ArrayList<String> final_list=new ArrayList<String>();; int i=0; while(true){ StringBuilder temp = new StringBuilder(); for(ArrayList<String> currentList:lists){ if(i<currentList.size()){ temp.append(currentList.get(i)); } } String row = temp.toString(); if(row.length()==0){ break; } else{ final_list.add(row); i++; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run all migrations in reverse in rails 3.1 I want to run rake db:migrate:down on all of my migrations in rails 3.1. Some other questions suggest doing rake db:migrate:down VERSION=0, but that gives me this error: No migration with version number 0 A: Use rake db:migrate VERSION=0
{ "language": "en", "url": "https://stackoverflow.com/questions/7505913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making a WPF DataGrid look like a ListView I have a project where there is an existing DataGrid. I have a DataSet properly bound to it and can populate columns with data for the field in the DataSet they represent. Now I am in a situation where over time some of these descriptor fields are empty, so if I explicitly show columns and then populate the user ends up seeing a sparsely populated ugly DataGrid. Is there some way that I can remove dividers/columns and merge descript fields. For example, if User A only has his/her email field filled out, User B only has the name field filled out and User C only had phone number field filled out I would like to display something that looks like a simple list: userA@intertubez.com Useri S. Bee (555) 555-1234 Is this possible? Is this done in the XAML or the codebehind? A: It is possible that you can solve it like this: bind your DataSet to the ListBox and work with a DataTemplate. :) MSDN DataTemplate Overview Or you could convert your rows to string and then you get a List and then bind that to the ListBox. I think the first solution is better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to do a GET with multiple times the same parameters using httpbuilder and groovy? I am using Groovy 1.8 and HttpBuilder 0.5.1 to talk to a REST webinterface. I have this working: def JSONArray tasks = httpBuilder.get( path: 'workspaces/'+LP_WORKSPACE_ID+'/tasks', query: [filter:'is_done is false'] ); def JSONArray tasks = httpBuilder.get( path: 'workspaces/'+LP_WORKSPACE_ID+'/tasks', query: [filter:'external_reference contains /'] ); I need to combine those 2 into 1. I got this documentation on how it should look: /api/workspaces/:workspace_id/tasks?filter[]=is_done is false&filter[]=external_reference starts with / How do I combine 2 times the same query variable (filter) in the same GET ? I tried this: def JSONArray tasks = liquidPlanner.get( path: 'workspaces/'+LP_WORKSPACE_ID+'/tasks', query: ['filter[]':'external_reference contains /', 'filter[]':'is_done is false'] ); but that does not work. regards, Wim A: Try the following: def JSONArray tasks = liquidPlanner.get( path: 'workspaces/'+LP_WORKSPACE_ID+'/tasks', query: ['filter[]':['external_reference contains /', 'is_done is false']] );
{ "language": "en", "url": "https://stackoverflow.com/questions/7505923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActiveRecord::Base establish connection to Redis How do I use the activerecord gem with Redis? I see all these examples with models and Redis but I keep getting a "not connected" error when I try to use them.. A: ActiveRecord does not know how to speak to Redis, only to SQL databases. To use redis here is a list of gems you can use: If you want to use redis directly (I think you should): redis-rb If you really want an ORM: redis-objects
{ "language": "en", "url": "https://stackoverflow.com/questions/7505925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Geolocation distance SQL from a cities table So I have this function to calculate nearest cities based on latitude, longitude and radius parameters. DELIMITER $$ DROP PROCEDURE IF EXISTS `world_db`.`geolocate_close_cities`$$ CREATE PROCEDURE `geolocate_close_cities`(IN p_latitude DECIMAL(8,2), p_longitude DECIMAL(8,2), IN p_radius INTEGER(5)) BEGIN SELECT id, country_id, longitude, latitude, city, truncate((degrees(acos( sin(radians(latitude)) * sin(radians(p_latitude)) + cos(radians(latitude)) * cos(radians(p_latitude)) * cos(radians(p_longitude - longitude) ) ) ) * 69.09*1.6),1) as distance FROM cities HAVING distance < p_radius ORDER BY distance desc; END$$ DELIMITER ; Here's the structure of my cities table: > +------------+-------------+------+-----+---------+----------------+ | > Field | Type | Null | Key | Default | Extra | > +------------+-------------+------+-----+---------+----------------+ | > id | int(11) | NO | PRI | NULL | auto_increment | | > country_id | smallint(6) | NO | | NULL | | | > region_id | smallint(6) | NO | | NULL | | | > city | varchar(45) | NO | | NULL | | | > latitude | float | NO | | NULL | | | > longitude | float | NO | | NULL | | | > timezone | varchar(10) | NO | | NULL | | | > dma_id | smallint(6) | YES | | NULL | | | > code | varchar(4) | YES | | NULL | | > +------------+-------------+------+-----+---------+----------------+ It works very well. What i'd lke to do (pseudcode) is something like: SELECT * FROM cities WHERE DISTANCE(SELECT id FROM cities WHERE id={cityId}, {km)) and it'll return me the closest cities. Any ideas of how I can do this? At the moment, I just call the function, and then iterate through the ids into an array and then perform a WHEREIN in the city table which obviously isn't very efficient. Any help is MUCH appreciated. Thanks. A: If you can limit the maximum distance between your cities and your local position, take advantage of the fact that one minute of latitude (north - south) is one nautical mile. Put an index on your latitude table. Make yourself a haversine(lat1, lat2, long1, long2, unit) stored function from the haversine formula shown in your question. See below Then do this, given mylatitude, mylongitude, and mykm. SELECT * from cities a where :mylatitude >= a.latitude - :mykm/111.12 and :mylatitude <= a.latitude + :mykm/111.12 and haversine(:mylatitude,a.latitude,:mylongitude,a.longitude, 'KM') <= :mykm order by haversine(:mylatitude,a.latitude,:mylongitude,a.longitude, 'KM') This will use a latitude bounding box to crudely rule out cities that are too far away from your point. Your DBMS will use an index range scan on your latitude index to quickly pick out the rows in your cities table that are worth considering. Then it will run your haversine function, the one with all the sine and cosine maths, only on those rows. I suggest latitude because the on-the-ground distance of longitude varies with latitude. Note this is crude. It's fine for a store-finder, but don't use it if you're a civil engineer -- the earth has an elliptical shape and the this assumes it's circular. (Sorry about the 111.12 magic number. That's the number of km in a degree of latitude, that is in sixty nautical miles.) See here for a workable distance function. Why does this MySQL stored function give different results than to doing the calculation in the query?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .htaccess mobile cookie set I just created a mobile site and realized that I wanted the users to be able to view the full desktop site. I know there is a way to check if there is a cookie with the .htaccess file, I'm wondering if there's a way to set a cookie as well. My code: #redirect RewriteCond %{HTTP_HOST} !^m\.stage.sunjournal\.com$ RewriteCond %{HTTP_USER_AGENT} "android|iPhone|blackberry|ipad|iemobile|operamobile|palmos|webos|googlebot-mobile" [NC] RewriteRule ^(.*)$ http://m.stage.sunjournal.com/$1 [L,R=302] Is there a way to set a cookie and check, so my users can access the full site from their mobile devices? A: Sure you can -- use [CO] flag to set the cookie. For example: RewriteRule ^(.*)$ http://m.stage.sunjournal.com/$1 [L,R=302,CO=mobile:yes:m.stage.sunjournal.com:0:/] Obviously, you need to adjust it to whatever cookie name/value/etc you are using. Documentation: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_co
{ "language": "en", "url": "https://stackoverflow.com/questions/7505939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Object not in the right state; which exception is appropriate? Say I have a class Rocket(object): def __init__(self): self.ready = False def prepare_for_takeoff(self): self.ready = True def takeoff(self): if not self.ready: raise NotReadyException("not ready!") print("Liftoff!") Now, which of the standard exceptions would be most appropriate to derive NotReadyException from? Would it be ValueError, since self has the wrong state/value? A: Now, which of the standard exceptions would be most appropriate to derive NotReadyException from? Exception Don't mess with anything else. http://code.google.com/p/soc/wiki/PythonStyleGuide#Exceptions What are your use cases for exception handling? If you derived your exception from, say ValueError, would you ever write a handler that used except ValueError: to catch both exceptions and handle them in exactly the same way? Unlikely. ValueError is a catch-all when more specific exceptions aren't appropriate. Your exception is very specific. When you have an application-specific exception like this, the odds of it sharing any useful semantics with a built-in exception are low. The odds of actually combining the new one and an existing exception into a single handler are very, very low. About the only time you'll ever combine an application-specific exception with generic exceptions is to use except Exception: in some catch-all logger. A: I'd just derive it from Exception. Programmers who catch ValueError might be quite surprised that they catch your NotReadyException as well. If you will be defining a lot of similar types of state-related exceptions, and it would be convenient to be able to catch 'em all, you might define a StateError exception and then derive NotReadyException from that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Code First Fluent API - Rename AutoGenerated ForeignKeyID Db Column That Is Not In The Model I've followed a tutorial for Code First TPT Inheritance: http://weblogs.asp.net/manavi/archive/2010/12/28/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt.aspx The User model contains a uni-directional navigation to BillingDetail. CodeFirst names the column "BillingDetail_BillingDetailId" I would like to rename the column "BillingDetailId" using the Fluent API. How is this done? Here is the User model. public class User { public int UserId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual BillingDetail BillingDetail { get; set; } } Thanks A: You would need to a BillingDetailId property on the User object and then via the fluent API you can protected override void OnModelCreating(DbModelBuilder builder) { builder.Entity<User>() .Property(u => u.BillingDetailId) .HasColumnName("BillingDetailId "); } A: Because You have "BillingDetail " as an Attributes...what ever you extract from this Attribute will have the ColumnName of "BillingDetailId" protected override void OnModelCreating(DbModelBuilder builder) { builder.Entity<User>().Property(u => u.BillingDetail).HasColumnName("BillingDetailId"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7505942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: StringIndexOutOfBoundsException I am having a few problems in getting a method to work properly in Java. In the program I have created an array consisting of many different words of different length. The method I'm working on is supposed to read user input for wordlength, letter, and position, and Java will then print out any words matching these three parameters (for instance, if the user types wordlength 4, letter A and position 2, and words with length 4 containing the letter A at position 2 will be printed out). Anyhow, the method I have created looks like this: public static void inputMethod(int length, char letter, int position){ for (int index = 0; index < wordTable.length; index++) { if (length == wordTable[index].length() && letter == wordTable[index].charAt(position) ) System.out.println(wordTable[index]); } This method works fine for for some inputs, but for other inputs I get an error message such as this: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(Unknown Source) at Wordarray.inputMethod(Wordarray.java:153) at Wordarray.main(Wordarray.java:61) If anyone could explain to me how I can fix this, I would greatly appreciate it! Like I said, I only get this message for certain inputs. For other inputs the program works just like it is supposed to. A: Well, obviously position is bigger than the length of the string that is found at wordTable[index] (or negative). You'll need to check against the length of the string too. A: If you have replaced for (int index = 0; index < wordTable.length; index++) { with for (int index = 0; index < length; index++) { that is most likely not what you really want. The better approach would be like this: public static void inputMethod(int length, char letter, int position) { // check if input is valid if(position < length) for (int index = 0; index < wordTable.length; index++) { if (length == wordTable[index].length() && letter == wordTable[index].charAt(position) ) System.out.println(wordTable[index]); } A: If the given position is greater or equal than the length of the current word, this can happen. Also worth a look: Is the position for the first character 0 or 1? A: Is this your actual code? You are using three different variables: indexs, indeks and index in your for-loop. I'm surprised this even compiled. Don't retype your code, cut and paste the actual code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: recursion - all permuations of a string Possible Duplicate: Are there any better methods to do permutation of string? I know recursion and can write programs like fibonacci number, tree traversals so I think I know it but when it comes to this question specifically I feel bad Please guide me with how to calculate all possible permutations of a string A: Here is good examples of different permutation algorithms, including recursive one: http://www.bearcave.com/random_hacks/permute.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7505950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Help joining MySQL (tag) tables in Codeigniter? Hello everyone I need some help retrieving tags that belong to a specific post. I am working with Codeigniter and MySQL. My tables look like this. post id, title, description, user_id tag id, tag post_tag id,post_id,tag_id The following is what I have in my controller: $this->db->select('*'); $this->db->from('post'); $this->db->join('post_tag', 'post.id = post_tag.post_id'); $this->db->join('tag','post_tag.tag_id = tag.id'); $this->db->group_by('post.id'); When I open the page in my browser only 1 tag is returned. Thank in advance, I tried searching for this before I asked but I didn't know what to search for. :-/ UPDATE: I commented $this->db->group_by('post.id'); and now my post duplicates depending on the number of tags. My post had 3 tags so i get 3 copies of my post but each has a different tag in the tag field. :-/ Thanks again. A: The problem is that you are grouping by the post id (which is correct), so you will only get one result with one tag joined. You can use GROUP_CONCAT to concatenate the results into one column in each row. Something like $this->db->select('post.*, GROUP_CONCAT(post_tag) as all_tags'); This is untested, and will only handle the post tags, not the tags itself, but you should be able to get something going. I'd write the basic SQL first and then break it down into the CI functions. Also, I'd remove the second join to begin with to make it simpler. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7505954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recover Xcode project from iphone? My computer recently crashed and I lost my entire Xcode project. However, the project is till sitting on my iphone, is there any way i can recover it? A: I'm sorry but I think this is no way to recover your project from iPhone, as it contains already compiled version. A: Unfortunately this is a painful lesson about version control and backups There is no way to get the Xcode project back from the compiled app. A: if you can access your iPhone and could get to the folder where the app was installed then you will fnd couple of files you might be able to use. Esp *.png files. There are also some *nib files - but I don't know if/how they can be loaded back into xCode somehow. You will also get the *strings files back. But possibly most important in this folder there are also *h files of your project. So I guess that will save you already couple of hours - all you need is to get to your iPhones app folder. I use iPhone Explorer, but anything else should work too. ps don't know how it can be done on a non-jailbroken phone though good luck! use TimeMachine in the future - its simple and doesn't burdon your MAC during development...
{ "language": "en", "url": "https://stackoverflow.com/questions/7505959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Using JdbcTemplate with a "Non-Spring-Bean" JNDI DataSource Page 342 of spring-framework-reference.pdf (bundled with spring-framework-3.1.0.M2) states, "The JdbcTemplate can be used within a DAO implementation through direct instantiation with a DataSource reference." However, it goes on to say, "The DataSource should always be configured as a bean in the Spring IoC container." Does anyone know why the DataSource shouldn't be provided to a JdbcTemplate from a plain-old JNDI lookup outside of the Spring container, e.g. How to programatically use Spring's JdbcTemplate? A: "The DataSource should always be configured as a bean in the Spring IoC container." It appears that this note is intended to clarify the preceding statement: "The JdbcTemplate can be used within a DAO implementation through direct instantiation with a DataSource reference, or be configured in a Spring IoC container and given to DAOs as a bean reference." I believe the information these statements are trying to convey is that when you're configuring a DAO in Spring, you can either: * *inject the DataSource directly into the DAO and create the JdbcTemplate in code yourself, or *you can make the JdbcTemplate a Spring bean as well, inject the DataSource into the JdbcTemplate, and inject the JdbcTemplate into the DAO. The note, then, means that if Spring is managing the DAO and its dependencies, the DataSource must be a Spring bean in either case, as it needs to be injected either into the DataSource for use in constructing the JdbcTemplate (case 1) or into the JdbcTemplate itself (case 2). I wouldn't take it to mean that a DataSource used in a JdbcTemplate must always be managed by Spring and only Spring. The note does give that impression. It's probably worth filing a bug against.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multilingual Application Encoding I'm working on an application using the CakePHP framework and in the past I ran into a few encounters with encoding. To avoid these issues in my application, I started doing some research. But I'm still a little confused about the how and why. My application will need to support all languages, yes even languages such as Chineese. Most of the data will be stored into a MySQL database, and that's where confusion starts. What should I use as collation? Based on what I've read the past few days, I come to the conclusion the best choice for collation would be utf8_unicode_ci. Is this correct? Now onto the PHP, what would I set as encoding? UTF-8? I need to completely be sure not a single character shows up the way it shouldn't. Content will be submitted through forms, so the output has to be the same as the input. I hope anyone can give me an answer to my questions and help clarify it to me, thanks in advance. A: You need UTF-8 encoding to store you data. But as for collation, it is used to sort strings. Unfortunatelly, there exists no universal collation, and such universal collation can not exists, because collations are contradictory. To make a point on example, in Czech 'ch' goes after 'h', opposite to most other Latin script languages. A: Yes, utf8_unicode_ci is a sane choice when you don't know in advance the language. As for PHP I'll just link to some answers I wrote in the past: How to best configure PHP to handle a UTF-8 website Croatian diacritic signs in MySQL db (utf-8) Am I correctly supporting UTF-8 in my PHP apps? One additional advice would be to make sure your text editor saves all files as UTF-8 (NO BOM, if you have this option). In short, keep everything utf-8 from the very beginning and you should be safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring 3 flawed? I have a Spring 2.5.x application which I'm migrating to Spring 3 and just bumped into a little problem. I have an handler mapping like so: <bean id="handlerMappings1" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="interceptor1" /> <ref bean="interceptor2" /> .... <ref bean="interceptorN" /> </list> </property> <property name="urlMap"> <map> <entry key="/url1.html" value-ref="controller1" /> <entry key="/url2.html" value-ref="controller2" /> .... <entry key="/url100.html" value-ref="controller100" /> </map> </property> </bean> and another one like this: <bean id="handlerMappings2" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="urlMap"> <map> <entry key="/urlA.html" value-ref="controllerA" /> <entry key="/urlB.html" value-ref="controllerB" /> .... <entry key="/urlN.html" value-ref="controllerN" /> </map> </property> </bean> I'm slowly replacing both with @RequestMapping annotations with a <context:component-scan> (which basically registers a DefaultAnnotationHandlerMapping). In Spring 3 I saw the <mvc:interceptors> tag which can be used to add interceptors to certain URLs but you can specify only one interceptor, at least that's what I see from the schema. From what I can figure, I have to register one of these for each interceptor which will duplicate all my URLs for as many times as I have interceptors (and I don't even know in what order they will run). On the other hand I can't add the iterceptors on the DefaultAnnotationHandlerMapping because they will run for all my controllers annotated with @RequestMapping and I don't want that. So how can I specify interceptors is Spring 3 for some URLs, without repeating the URL's and keeping the URL to controller mapping based on the @RequestMapping annotation? A: One option would be to create a custom interceptor which can delegate to a collection of injected interceptors. A: You could have a look at the SelectedAnnotationHandlerMapping and the IgnoreSelectedAnnotationHandlerMapping classes from the springplugins project. The sources are some years old but the idea still stands. There is a presentation on the creator's blog here: Spring Framework Annotation-based Controller Interceptor Configuration. Make sure you also read the comments to the blog post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Spellcheck Data in SQL Server We have a large database with hundreds of tables that have lookup text stored in them with spelling errors from when the application was originally written offshore. Is there a way to run a spellcheck on the data in sql server so we can find all of these errors quickly? A: One thought - You could write a CLR function to access the spell checker included with Microsoft Word. See: Walkthrough: Accessing the Spelling Checker in Word for a starting point. A: * *Export your data to Excel. *Distribute the sheets to multiple people to break up the work load *Have them run spell check to identify the misspelled words. *Gather up the bad records and create update statements from the db. *Don't offshore applications where English spelling is important. EDIT: I should have pointed out, you might use the spell check to identify the issues but you want human eyes on the actual data as well as suggested fixes. Thus, being able to spread the work around to run the spell check is important. There won't be any fully automated solution that will catch everything, or worse it will catch too much and muck the data up worse. A: Just stumbled across this one. Another way to do this is using Microsoft Access, using ODBC, link to the tables on SQL side, then open the table in access and run the spellcheck in Access, you can update the corrections on the fly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Question about Finite State Automata I want to construct a deterministic finite automata that accepts the following language: {w ∈ {a,b}* : each a in w is immediately preceded by a b} So far I've got >⨀ ---b---> O ---a---> O. '>' = initial state ⨀ = final state A: A good way to think about FAs is by trying to think about how many different situations you can be in, in terms of how you are going to get to a string in the language. Let's start with a few small strings and see what I mean. Say you start with the empty string. What can you append to this to get a string in the language? Well, the empty string is in the language, so we can append the empty string (i.e., nothing) and also have a string in the language. Additionally, we can append any string in the language we are going for to the empty string, and we will get a string in the language (trivially). We will need at least one state to remember the empty string (and strings like it - strings to which we can append the empty string or any other string in the language and still have a string in the language); this will be the start/initial state, and since the empty string is in the language (we check this easily), we know the start/initial state will be accepting. Now let's consider the string a. This is an example of a string not in the language, and there's nothing we can add to the end of this string to cause it to be in the language; we've already violated the condition that all a's in the string are preceded by b's. The set of strings we can add to this to get a string in the language is the empty set, and therefore, we will need a state distinct from the one we've already identified to remember this string and strings like it - strings to which we cannot add anything to get a string in the language. To recap, we have identified two states: an accepting start/initial state, and what we call a "dead" state - a state that is not accepting and which does not ever lead to an accepting state. Let's try the string b. This string is in the language, and so we can add the empty string to it. We can also trivially add any other string in the language to the end of this string, and get another string in the language. However, we can also add an a followed by any string in the language, and get another string in the language. For instance, we can add the string a followed by bbabb to get babbabb, which is also in the language. The set of strings which we can add is therefore a set we haven't seen before, and we will need a new state to represent this string - the string b - and strings like it. It will be accepting, since the string b is a string in the language. You should try the strings aa, ab, ba, and bb. You should find that the strings aa and ab are both already covered by our dead state (we can't add any strings to the end of these to get anything in our language), and that the string ba is covered by the start/initial state (we can only add to this strings already in the language to get other strings in the language), and that bb corresponds to the third state we identified (adding any string, or a single a followed by any string, will result in a string also in the language). Since we have exhausted all strings of length 2 and not added any new states, we know that these are all the states that we need in the FA; we could add others, but they'd be unnecessary. To get the transitions, all we need to do is to make sure that all the states lead to the correct place. In other words, since the string a is formed by adding the character a to the end of the empty string, we need a transition from the start/initial state (corresponding to the empty string) to the dead state (corresponding to the string a) which occurs when the FA reads the symbol a. Similarly, we need a transition from the start/initial state to the third state on the symbol b. The other transitions are found similarly: on either an a or a b, the dead state transitions to itself, and the third state loops on b and transitions to the start/initial state on an a. Once each state has a transition for each symbol in the alphabet, you have a complete (and correct) FA. Moreoever, by constructing it in this fashion, you guarantee that you have a minimal FA... which is a nice way to solve problems requesting one, instead of coming up with an arbitrary one and minimizing it post-hoc. A: State 1 (accepting, initial state): * *On input 'a', go to state 3 (permanently rejecting the string) *On input 'b', go to state 2 State 2 (accepting): * *On input 'a', go to state 1 *On input 'b', go to state 2 State 3 (not accepting) * *On input 'a' or 'b', stay in state 3 Conceptually, State 1 represents "a valid string whose final letter is not b", State 2 represents "a valid string whose final letter is b", and State 3 represents "a string that is not valid" In graphed form:
{ "language": "en", "url": "https://stackoverflow.com/questions/7505976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails: Use library of models I have some experience with asp.net. When the business logic gets complicated, you want to keep the repositories and other business class separated from the main ui project. You don't want to change the ui project if you need to change the business logic. In .net I would create a library project and push the business logic in there, this way I can change the library without affecting the ui project. Where should I put my business logic? If I keep it with my models, it seems to get very messy very fast because there are a lot of classes. How do you structure rails application that require many classes with business logic ? A: The common wisdom when developing rails application is to put classes and modules that are not directly related to the views, models or controllers in the lib directory. Note that rails 3 doesn't autoload it by default, you will have to put the following in config/application.rb: config.autoload_paths += %W(#{config.root}/lib) Creating a gem could be another option if you want to share your business logic between multiple apps, but it is more involved than simply putting everything into lib. This answer would be a good start if you'd like to know more about that. A: Have you considered using a Rails::Engine? This will give you a way to isolate a set of related models, controllers, views, routes, helpers, migrations and tests. Rails::Engines may also be configured as a gem so using the engine in multiple projects becomes a possibility. If you want to use your engine across multiple projects gem versions might come in handy. http://edgeapi.rubyonrails.org/classes/Rails/Engine.html I suggest having a look at Devise to see just how much one can do with a Rails::Engine. https://github.com/plataformatec/devise If you only want to isolate smaller pieces of business logic then ActiveSupport::Concern might be a little bit more appropriate. http://api.rubyonrails.org/classes/ActiveSupport/Concern.html Finally, something that I've never used but looks interesting is Modularity. The example from the documentation looks somewhat similar in principal to ActiveSupport::Concern. class User < ActiveRecord::Base does "user/authentication" does "user/address" end https://github.com/makandra/modularity I will be keeping track of different answers because I'm trying to solve the same problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Timing GET requests to a specific site I am trying to write a firefox plug in to record the time taken to serve all GET requests to a specific website. eg google and log this data to file.In other words I would like to use each GET request as an event to trigure a timer. Could anyone point me in the right direction? A: You need to listen to the http-on-modify-request and http-on-examine-response notifications. These notify you when a request is about to be sent and when a response has been received. See https://developer.mozilla.org/en/Setting_HTTP_request_headers for an example using http-on-modify-request, you would record the timestamp instead of setting a header. In addition, I guess that you will want to get the tab that the request belongs to. And finally, you match http-on-examine-response to preceding http-on-modify-request notifications by comparing their channel objects: How to map response to request when using "http-on-modify-request" and "http-on-examine-response"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7505987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Importing from a relative path in Python I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them Proj/ Client/ Client.py Server/ Server.py Common/ __init__.py Common.py How do I import Common.py from Server.py and Client.py? A: The default import method is already "relative", from the PYTHONPATH. The PYTHONPATH is by default, to some system libraries along with the folder of the original source file. If you run with -m to run a module, the current directory gets added to the PYTHONPATH. So if the entry point of your program is inside of Proj, then using import Common.Common should work inside both Server.py and Client.py. Don't do a relative import. It won't work how you want it to. A: EDIT Nov 2014 (3 years later): Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me: from ..Common import Common As a caveat, this will only work if you run your python as a module, from outside of the package. For example: python -m Proj Original hacky way This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users. You can add Common/ to your sys.path (the list of paths python looks at to import things): import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common')) import Common os.path.dirname(__file__) just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module. A: A simple answer for novice in Python world Create a simple example Assume we run ls -R in the current working directory and this is the result: ./second_karma: enemy.py import.py __init__.py math ./second_karma/math: fibonacci.py __init__.py And we run this command $ python3 second-karma/import.py init.py is an empty file but it should exists. Now let's see what is inside the second-karma/import.py: from .math.fibonacci import Fibonacci fib = Fibonacci() print(fib.get_fibonacci(15)) And what is inside the second_karma/math/fibonacci.py: from ..enemy import Enemy class Fibonacci: enemy: Enemy def __init__(self): self.enemy = Enemy(150,900) print("Class instantiated") def get_fibonacci(self, which_index: int) -> int: print(self.enemy.get_hp()) return 4 Now the last file is second_karma/enemy.py: class Enemy: hp: int = 100 attack_low: int = 180 attack_high: int = 360 def __init__( self, attack_low: int, attack_high: int) -> None: self.attack_low = attack_low self.attack_high = attack_high def getAttackPower( self) -> {"attack_low": int, "attack_high": int}: return { "attack_low": self.attack_low, "attack_high": self.attack_high } def get_hp(self) -> int: return self.hp Now a simple answer why it was not working: * *Python has a concept of packages, which is basically a folder containing one or more modules, and zero-or-more packages. *When we launch python, there are two ways of doing it: * *Asking python to execute a specific module (python3 path/to/file.py). *Asking python to execute a package. *The issue is that import.py makes reference to importing .math * *The .math in this context means "go find a module/package in the current package with the name math" *Trouble: * *When I execute as $ python3 second-karma/import.py I am executing a module, not a package. thus python has no idea what . means in this context *Fix: python3 -m second_karma.import *Now import.py is of parent package second_karma, and thus your relative import will work. Important note: Those __init__.py are necessary and if you have not them you must create them first. An example in github * *Read README.md for a better comprehension *Go back and forth between commits to observe the problem even more deeply. *https://github.com/kasir-barati/my-python-journey/tree/main/second_karma A: Funny enough, a same problem I just met, and I get this work in following way: combining with linux command ln , we can make thing a lot simper: 1. cd Proj/Client 2. ln -s ../Common ./ 3. cd Proj/Server 4. ln -s ../Common ./ And, now if you want to import some_stuff from file: Proj/Common/Common.py into your file: Proj/Client/Client.py, just like this: # in Proj/Client/Client.py from Common.Common import some_stuff And, the same applies to Proj/Server, Also works for setup.py process, a same question discussed here, hope it helps ! A: Don't do relative import. From PEP8: Relative imports for intra-package imports are highly discouraged. Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code. Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details. A: Doing a relative import is absolulutely OK! Here's what little 'ol me does: #first change the cwd to the script path scriptPath = os.path.realpath(os.path.dirname(sys.argv[0])) os.chdir(scriptPath) #append the relative location you want to import from sys.path.append("../common") #import your module stored in '../common' import common.py A: Approch used by me is similar to Gary Beardsley mentioned above with small change. Filename: Server.py import os, sys script_path = os.path.realpath(os.path.dirname(__name__)) os.chdir(script_path) sys.path.append("..") # above mentioned steps will make 1 level up module available for import # here Client, Server and Common all 3 can be imported. # below mentioned import will be relative to root project from Common import Common from Client import Client
{ "language": "en", "url": "https://stackoverflow.com/questions/7505988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "153" }
Q: Arduino Map equivalent function in Java Is there a function similar to the Map function in Arduino for Java? I need to map a range of values to another range of values, so I was wondering if there was something similar to it in Java, I've been searching but I only get the Java's Map function. A: The code of map() from Arduino's library is this: long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } This will work in Java just the same - no real magic. But standard Java has nothing predefined like this. A: Uh, Java doesn't have a 'Map' function, it has a Map type in the Collections (java.util), with multiple implementations. But this is just a storage mechanism, basically resulting in key=>value pairs. Based on my reading of the Arduino docs you linked, you'd need to implement your own method to map the value appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Can you add an After Validation javascript callback for Contact Form 7? After the form is submitted if the user failed to enter the required fields I want to add additional javascript goodies, but can't figure out where to add my own custom callback after the form has been validated/posted. Is this possible without hacking the module? Thanks, Greg A: This plugin seems to use JavaScript validation, so you could add your own custom JavaScript validation by hooking into the submit event (for example). Since this is JavaScript, you won't be hacking the module. I suggest using Firebug, or some other DOM inspector, to determine the best place to bind your events. Also, check out the plugin docs. There is also a forum which may provide more specific help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a regular expression that replaces all matches in a string through ruby's gsub? I wonder why my regular expression will not work, I require to achieve the following behavior: "aoaoaoaoaoao".gsub!(/o/, 'e') The above will correctly give me: aeaeaeaeaeae Now, The real thing looks like this: "Today I ate a ((noun)), and it tasted ((adjective))".gsub!(/\(\(.*\)\)/, "word") And its result is: "Today I ate a word", But I had hoped It'd return to me: "Today I ate a word, and it tasted word" It's obvious there's problem with my regular expression, (right?) because it'll only replace once. Could you guys please tell me how to make it replace all matches? (like in my first example) Thank very much! A: You need the following regex: /\(\(.*?\)\)/ .*? consumes as little characters as possible to obtain a match. So the problem was not that the regex replaced once but that it matched too large a part of the string - from the first (( to the last )).
{ "language": "en", "url": "https://stackoverflow.com/questions/7505998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: php/xpath query: how to get content of div, that may have nested divs? im trying to make a function that returns the inner HTML of a div with a spesific classname. i searched around and people seem to say xpath query is the way to go. this is what i got: function getDivContent($html, $classname) { $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $result = $xpath->query('//div[class="'.$classname.'"]'); return $result; } but it only returns: object(DOMNodeList)#3 (0) { } anyone can spot the error? EDIT: The solution: function nodeContent($n, $outer=false) { $d = new DOMDocument('1.0'); $b = $d->importNode($n->cloneNode(true),true); $d->appendChild($b); $h = $d->saveHTML(); // remove outter tags if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4)); return $h; } function getDivContentByClass($html, $class) { $query = "//div[@class='$class']"; $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $result = $xpath->query($query); $data = nodeContent($result->item(0)); return $data; } A: xpath's query function returns a NODEList, which is essentially an array of the results, even if there's only a single matching node. return $result->item(0); will return the first matching node only. To get the content, you can use $result->item(0)->nodeValue, which acts equivalently to .innerHTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7505999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transferring program from XCode to the iPad I'm watching training videos on how to write code in XCode, but all the examples are for the simulator. Right now I'm taking it on faith that I'll one day eventually transfer the bits over to my iPad, but I'd like to ask: How can I transfer the program to my iPad? A: During development, use the Organizer that comes with XCode. This question has also been answered - no surprise - on SO. A: First you have to sign up for an Apple Developer account for $99, and then once you do that, you can register your devices so that you can transfer over your iOS apps to your iOS devices (iPad, iPhone, iPod Touch) with XCode. This is pretty much necessary once you get your apps completed, as the simulator and real iOS devices can handle apps differently and are needed for testing. A: You must register in the Apple Developer Program first (check http://developer.apple.com/devcenter/ios/index.action ) - it's about $100 per year. Then follow the instructions there to create certificates, provisioning profiles, add devices and so on. They have all the info needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sencha touch panel won't scroll after applying template I have a panel set to layout: 'fit' like all my searching suggested the problem lies. After a JSONP request and applying a template, I can't scroll all the way to the bottom of the list. I filled the html: '<div>text</div>...<div>bottom</div>' and commented out the JSONP request. This works fine. I left that there, then applied the template again, still no go. My template new Ext.XTemplate([ '<tpl for=".">', '<div>', '<a href="product.html#{productid}" >', '<h3>{title}</h3>', '<img src="{img}" />', '<p>Manufacturer: {realvendor}<br/>', 'Product#: {partnumber}<br/>', 'Manufacturer#: {vendornumber}<br/>', 'List Price: {msrp}<br/>', 'Description: {text}<br/>', '</p>', '</a>', '<a href="price_av.html#{productid}" title="Price/Availablity" >Check Price</a>', '</div>', '</tpl>' A: After much fun in console and profiles, I tracked down the problem. It wasn't setting the height of my panel on panel.update(), but it was setting the height of the container div. App.views.home.setHeight(App.views.home.el.up('div').dom.style.height) I have a panel home in App.views which is where the template is applied. After I update the panel, I set the height to the parent object's height. Works now. A: You also need to have your panel set to vertical scroll new Ext.Panel({ // bla bla bla... scroll: 'vertical' });
{ "language": "en", "url": "https://stackoverflow.com/questions/7506017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Migration from Bugtracker to Atlassian JIRA (Html tags) I am trying to migrate some bugtracker data to jira using C# and te soap client interface. So far so good with the implementation but i need to parse some html information to wiki confluence(I guess that is what jira uses). I do understand that wiki does not support break lines but on the following example. how do I parse this text to a proper wiki style. ( <h1>This is a text</h1><p> Hello World Luis Mayorga </p><br /> ). Unless there is a library or external code that i can use on this C# migration tool. content = content.Replace("<br />", "\\"); content = Regex.Replace(content, "<p>(.*?)</p>", "$1"); content = Regex.Replace(content, "<h1>(.*?)</h1>", "h1. $1"); Any Help
{ "language": "en", "url": "https://stackoverflow.com/questions/7506018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to add child elements using xmlgen I'm experimenting using the xmlgen library to generate some relatively simple xmd documents; however, I'm finding the syntax difficult to get working. This simple example works: people = [("Stefan", "32"), ("Judith", "4")] genXml''' :: [(String, String)] -> Xml Doc genXml''' people = doc defaultDocInfo $ xelem "SERVICES" $ xattr "transaction" "SHARE" outputXml :: IO () outputXml = BSL.putStrLn (xrender $ genXml''' people) But when I try to add a child element like this: genXml''' :: [(String, String)] -> Xml Doc genXml''' people = doc defaultDocInfo $ xelem "SERVICES" $ xattr "transaction" "SHARE" $ xelem "SERVICE" I get the following compile errors: Couldn't match type Xml' with(->) (c0 -> Xml Elem)' The function xattr' is applied to two arguments, but its type[Char] -> Text.XML.Generator.MkAttrRes [Char] [Char]' has only one In the expression: xattr "transaction" "SHARE" In the second argument of ($)', namely xattr "transaction" "SHARE" $ xelem "SERVICE"' I've tried putting <> or <#> at the end of the xelem "SERVICES" $ xattr "transaction" "SHARE" $ line, but that doesn't solve the problem. Any hints as to what I'm doing wrong? Thanks. A: Judging from the docs of xmlgen, genXml''' :: [(String, String)] -> Xml Doc genXml''' people = doc defaultDocInfo $ xelem "SERVICES" (xattr "transaction" "SHARE" <#> xelemEmpty "SERVICE") ought to work. Your code tries to add "SERVICE" to the "transaction" attribute, which does not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: API Facebook:invite multiple users to a event I'm tried invite multiple users to a event. reading the documentation facebook, I found this: http://developers.facebook.com/docs/reference/api/event/#invited I wrote the following code(that does not works): $facebook = new Facebook(array( 'appId' => '', 'secret' => '', 'cookie' => true, )); if ($user = $facebook->getUser()) { $friends = $facebook -> api('/me/friends'); $e_id = ""; //the event id $friends = $friends['data']; $e_details = $facebook -> api("/{$e_id}"); //information about the event for($ids = null,$i = 0,$len = count($friends); $i < $len; $i++) { $friend = $friends[$i]; $ids .= $friend['id'].','; } $data = $facebook -> api("/{$e_id}/invited?users={$ids}", 'POST'); $logoutUrl = $facebook->getLogoutUrl(); } else { $loginUrl = $facebook->getLoginUrl(array('scope' => 'create_event')); } I'm getting the fowllowing error: Uncaught OAuthException: (#200) Permissions error thrown in what's the permission that he is saying? of according to the documentation only one permission is necessary, which I set. Can someone point out my error? Any help is appreciated. Thanks in advance. A: so first try and store the ids in an array not sure if the trailing comma is messing with it. Also remove your self if it is in the list. you can also test the call at http://developers.facebook.com/tools/explorer/?method=GET&path=me%2Fgroups to see if there is anything else to test for. Maybe add a test to double check if the user has the create_event permission as well. if ($user = $facebook->getUser()) { $friends = $facebook -> api('/me/friends'); $e_id = ""; //the event id $friends = $friends['data']; $e_details = $facebook -> api("/{$e_id}"); //information about the event for($ids = null,$i = 0,$len = count($friends); $i < $len; $i++) { $friend = $friends[$i]; if($user != $friend['id']){ $ids[] = $friend['id']; } } $data = $facebook -> api("/{$e_id}/invited", 'POST', array("users"=>implode(",", $ids))); $logoutUrl = $facebook->getLogoutUrl(); } else { $loginUrl = $facebook->getLoginUrl(array('scope' => 'create_event')); } A: Mauvaise gestion des virgule je pense, là $ids se termine par une virgule, essaye plutôt comme ça : for($ids = null,$i = 0,$len = count($friends); $i < $len; $i++) { $friend = $friends[$i]; if ($ids)$ids.=','; $ids .= $friend['id']; } Et il faut limiter les invitations à 100 par "boucle" si on croit la FAQ de google sur les nouvelles limitations d'invitations
{ "language": "en", "url": "https://stackoverflow.com/questions/7506020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java, Parse JSON Objects that I know are null I have an array of JSON objects. To parse these arrays and store the simply data type values, I have to make assumptions of the key names and store them accordingly. I also know that sometimes the key's values will be null. example {["promotion":null]} how would I parse this? If I try to access a key whose value is null, I get a JSONException. Now this makes sense, but even if I do if(myJSObject.getString("promotion")!=null) then I will still get JSON exception when it checks how would I do a conditional check in my code for null objects so that I can avoid the JSON exception A: Use JSONObject.optString(String key) or optString(String key, String default). Edit: ... or isNull(String key), of course :) A: I think you'll need to format the JSON differently; for an array of promotions {promotions:[{promotion:null}, {promotion:5000}]} for a single promotion {promotion:null} edit: depending on which json api you're using, there might be a null check. Google's gson library has an .isJsonNull() method A: Uh...I don't think that is a properly formatted JSON string. [] indicates an array, which doesn't have any kind of key=>value pairing like an object does. What I think you want would be {"promotion":null}, which then your code snippet likely would work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: A simple Javascript write method Okay, this may be a silly question but I'm still on my path to learning OO javascript like a pro, so please don't laugh if this question is a little dumb... okay, say I have a very simple object like this var myObject = { write:function(){ return 'this is a string'; } } now if add the following outside my object (please note I have the appropriate Div in my webpage): document.getElementById('myDiv').innerHTML = myObject.write(); the innerHTML of my div is filled with the string 'this is a string', however if I just add the following to my script (outside the object): myObject.write() nothing is returned? Can some one tell me why and how I could write to the page ( not using document.write(myObject.write()) ) to output the string to the page. If this can't be done please let me know why... sorry if this is a really simple / stupid question but I am learning. Here's the full thing to help... <html> <head> </head> <body> <div id='myDiv'></div> <script type="text/javascript"> var myObject = { write:function(){ return 'this is a string 2'; } } //document.getElementById('myDiv').innerHTML = myObject.write(); myObject.write(); </script> </body> </html> A: Calling myObject.write() returns the value. Since you're not catching and processing the return value, nothing happens. Another method to write content to your document: <body> <script>document.write(myObject.write())</script> ...</body> <!--document.write ONLY works as desired when the document loads. When you call document.write() after the document has finished initiating, nothing will happen, or the page unloads--> A: var myObject = { obj: (function(){ return document.getElementById('myDiv');})(), //^^set object to write to write:function(str){ this.obj.innerHTML += str; //^^add the string to this object } } myObject.write('hello there'); Demo: http://jsfiddle.net/maniator/k3Ma5/
{ "language": "en", "url": "https://stackoverflow.com/questions/7506031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initializing a variable in MIPS What's the difference between the following two ways of initializing a variable? addi $a0, $0, 7 li $a0, 7 A: None really, li is generally implemented in hardware as an addi. A: ADDI is preferred because it's one instruction while LI is a pseudo-instruction and expands into 2 real instructions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CouchDB - Top N documents for each group I'm evaluating CouchDB at the moment, by walking along a couple of common use-cases we will encounter in our webproject. One of these use-cases is the following: Consider a system containing (contrived example): * *articles *questions *topics articles and questions can be assigned to multiple topics. A topic has it's own page (think of http://www.quora.com topics). Is it possible with 1 query from couchdb to get BOTH: * *the latest N articles on topic X *AND the latest N (or M?) questions on topic X In more generic terms: I'm looking for a way to do a group by type (where, in this case, type = 'article' or 'question' ) and for each group return the top n documents given a certain sort (in this case sort is reverse chronological) constrained to a specific filter (in this case the topic 'X') From what I've read, it's often not that big a deal to do multiple couchdb-queries in parallel, from a performance standpoint, but I'm just curious if this (for us often used ) use-case can be done in a single request. Thanks for any insight A: No. CouchDB views are 1-dimensional. For a given topic, the most recent articles AND the most recent questions is a two-dimensional query and thus not possible in one HTTP request. Thoughts on a workaround CouchDB is architected for, and encourages concurrent queries. In production, I would make two queries from my other answer concurrently. (In Javascript, this is very easy, but any asynchronous or threaded programming language can do it.) The response time to receive both results will only be the response time of the longer result (i.e. the one that finishes first was "free"). You can even walk the rows of both responses to merge their timelines in O(1) space and O(n) time—not too bad! The only thing that CouchDB does not guarantee is that both queries represent snapshots of the exact same database state. You mention Quora and that is a perfect example of modern database requirements. In theory, you have no idea how much database state has changed between these two queries. You have no idea, generally, if one view makes any sense compared to the other. In practice, the answer is obvious: Who cares? Queries separated by mere milliseconds will, in reality, make perfect sense together. That is why CouchDB is well-suited for web-applications despite having a severely restricted feature set. Alternative solution: GeoCouch The GeoCouch extension is actually a general-purpose 2-dimensional bounding box query engine. Besides, obviously, geospatial data, it can be used, for example, to query logs stored as a timestamp x severity 2-space. However it is currently still a separate project from CouchDB so I would be reluctant to call it a "CouchDB query." A: It is possible with 1 query from CouchDB to get both. Both queries use a map/reduce query, although you do not need the reduce function. You need the view rows to have [$type, $topic, $timestamp] pairs for keys: ["article" , "money", "2011-09-21T20:50:29.819Z"] ["article" , "shoes", "2011-09-21T20:30:29.819Z"] ["article" , "shoes", "2011-09-21T20:50:29.819Z"] ["question", "grits", "2011-01-13T20:30:18.123Z"] ["question", "money", "2011-09-20T20:30:18.123Z"] This function might do that: function(doc) { // _design/my_app/_view/topic_parts var key; if(doc.type && doc.parent_topic && doc.created_at) { // Looks good, emit it into the view. key = [doc.type, doc.parent_topic, doc.created_at]; emit(key, doc); } } To find the latest N rows (whether articles or questions), you basically need rows matching [$type, $topic, *] in descending order. For example, for the latest N articles on topic X, that breaks down like this. (Note that null is the smallest value in CouchDB and the object {} is the largest.) * *descending=true to get reverse chronological order. (Note "descending" conceptually means couch is scanning from the "bottom" to the "top" of the rows. So startkey and endkey are reversed.) *startkey=["articles","X",{}], so this is articles about X starting from the end of time *endkey=["articles","X",null], this is the same articles about X ending with the beginning of time *limit=N, to trim the results down The query would thus look like this (remember to encode the URL if necessary). GET /db/_design/my_app/_view/topic_parts?descending=true&startkey=["articles","X",{}]&endkey=["articles","X",null]&limit=N
{ "language": "en", "url": "https://stackoverflow.com/questions/7506045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to return zero value with count() How can I return rows where count(a.thread_id) = 0? SELECT current_date AS "Import Date", b.container_id AS "ID", b.name AS "Container Name", b.creation_ts AS "Container Creation Date", COUNT(a.thread_id) AS "Total Number of Un-Replied-To Threads", round(Avg(current_date - ( 99 ) - a.creation_ts :: DATE)) AS "Average Age", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) = 1 ) THEN 1 ELSE 0 END) AS "1 Day", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) = 2 ) THEN 1 ELSE 0 END) AS "2 Day", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) = 3 ) THEN 1 ELSE 0 END) AS "3 Day", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) BETWEEN 4 AND 6 ) THEN 1 ELSE 0 END) AS "4-6 Days", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) BETWEEN 7 AND 10 ) THEN 1 ELSE 0 END) AS "7-10 Days", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) BETWEEN 11 AND 15 ) THEN 1 ELSE 0 END) AS "11-15 Days", SUM(CASE WHEN ( ( current_date - ( 99 ) - a.creation_ts :: DATE ) > 15 ) THEN 1 ELSE 0 END) AS "15+ Days" FROM jivedw_message a, jivedw_container b WHERE a.thread_id IN (SELECT a.thread_id FROM jivedw_message a GROUP BY a.thread_id HAVING COUNT(a.message_id) = 1) AND a.thread_id NOT IN (SELECT a.thread_id FROM jivedw_message a INNER JOIN jivedw_object ON ( jivedw_object.object_id = a.thread_id ) INNER JOIN jivedw_activity_agg_user_day ON ( jivedw_activity_agg_user_day.direct_dw_object_id = jivedw_object.dw_object_id ) WHERE jivedw_activity_agg_user_day.direct_object_type = '1' AND jivedw_activity_agg_user_day.activity_type IN (30, 70) ) AND ( a.container_id = b.container_id ) AND ( b.creation_ts > '2009-11-19' :: DATE ) GROUP BY b.container_id, b.name, b.creation_ts ORDER BY b.name; A: Hit up google and look up "Having". In this case, having count(a.thread_id) = 0
{ "language": "en", "url": "https://stackoverflow.com/questions/7506066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way of storing user notifications? Say on a link-sharing site people can share links and post comments. Users following a link need to be notified when comments are posted there. Users following a category need to be notified when links are shared in that category. What would be the best way to store these notifications? I could store them individually, in which case fetching them would be simple, but every time a link is posted I'd have to add a notification for each of, say, 10,000 people following that category. I could also just calculate the notifications each time, in which case I would count the number of new comments since the last time a user logged in and display that. However, then I wouldn't be able to save old notifications. What are my options? Okay, here's my database schema: comments - id - user - link - content links - id - user - content subscriptions - id - user - link Every time a new comment is made on a link, all users who are subscribed to that link should have a "notification" that they will receive on their next login. A: Notifications are usually a highly read object, so you want to be able to get the list of currently unread notifications very quickly, not try and calculate on the fly. Also, trying to compare against login times does not make for a good user experience. If the user doesn't notice them initially, or refreshes the page, or clicks on one to view its details all the notifications are gone. With that in mind, I would suggest having a user_notification table with a read/unread column in it. While it's good to know where in your program scalablity could be an issue, it won't be until you're well underway (millions of records). You can index the user column to increase speed, and if you ever do have the need, you can partition by user to help scale across drives/servers. It's up to you to decide if you want to have notifications be in a separate table, or just part of the users_notifications table and that would be another area to optimize around. A: Just keep track of the last time they viewed the notifications. Then any posts they subscribe to that were created after that time will be in the notifications for next time they view notifications.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I support XML with or without namespace, with my WCF HTTP REST service I have a series of objects that look like this: namespace MyNamespace { [DataContract(Namespace="")] public class MyClass1 { [DataMember] public string MyProperty {get;set;} } } I have a method which exposes the WebInvoke that looks like this (very simplified as this actually does nothing right now, but still works for this test) [WebInvoke(UriTemplate = "", Method="POST")] public MyNamespace.MyClass1 GetItem(MyClass1 postedItem) { return postedItem; } I would really like to be able to accept XML that looks like this: <MyClass1> <MyProperty>1</MyProperty> </MyClass1> or this: <MyClass1 xmlns:"http://schemas.datacontract.org/2004/07/MyNamespace"> <MyProperty>1</MyProperty> </MyClass1> But so far my research seems to indicate this is not possible. My only idea right now is to use a IDispatchMessageInspector and consume the message, remove the xmlns namespace, and then allow WCF to continue processing the message. I have not had a lot of luck with this however, because once I consume the message it is no longer available for WCF to consume and deserialize. Is there an easier way? Is there a better way? A: You can use the dispatcher, but once you consume the message, you'll need to recreate it before returning from the method. The code below shows an example of it. public class StackOverflow_7506072 { [DataContract(Name = "MyClass1", Namespace = "")] public class MyClass1 { [DataMember] public string MyProperty { get; set; } } [ServiceContract] public class Service { [WebInvoke(UriTemplate = "", Method = "POST")] public MyClass1 GetItem(MyClass1 postedItem) { return postedItem; } } public class MyInspector : IEndpointBehavior, IDispatchMessageInspector { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this); } public void Validate(ServiceEndpoint endpoint) { } public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { MemoryStream ms = new MemoryStream(); XmlWriter w = XmlWriter.Create(ms); request.WriteMessage(w); w.Flush(); ms.Position = 0; XElement element = XElement.Load(ms); if (element.Name.NamespaceName == "http://schemas.datacontract.org/2004/07/MyNamespace") { element.Name = XName.Get(element.Name.LocalName, ""); foreach (XElement child in element.Descendants()) { if (child.Name.NamespaceName == "http://schemas.datacontract.org/2004/07/MyNamespace") { child.Name = XName.Get(child.Name.LocalName, ""); } } element.Attribute("xmlns").Remove(); } XmlReader r = element.CreateReader(); Message newRequest = Message.CreateMessage(r, int.MaxValue, request.Version); newRequest.Properties.CopyProperties(request.Properties); request = newRequest; return null; } public void BeforeSendReply(ref Message reply, object correlationState) { } } public static void Test() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), ""); endpoint.Behaviors.Add(new WebHttpBehavior()); endpoint.Behaviors.Add(new MyInspector()); host.Open(); Console.WriteLine("Host opened"); WebClient c = new WebClient(); c.Headers[HttpRequestHeader.ContentType] = "text/xml"; string xml = "<MyClass1><MyProperty>123</MyProperty></MyClass1>"; Console.WriteLine(c.UploadString(baseAddress + "/", xml)); c = new WebClient(); c.Headers[HttpRequestHeader.ContentType] = "text/xml"; xml = "<MyClass1 xmlns=\"http://schemas.datacontract.org/2004/07/MyNamespace\"><MyProperty>123</MyProperty></MyClass1>"; Console.WriteLine(c.UploadString(baseAddress + "/", xml)); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); } } A: This is a horrible idea. You're treating XML as though the standard doesn't matter. The element MyClass1 in the "http://schemas.datacontract.org/2004/07/MyNamespace" namespace is not the same as the element MyClass in the default namespace. A: You could also use WcfRestContrib to inject a custom XmlSerializer which supports this behavior. An example which uses an XmlSerializer that always omits namespaces entirely is here. You'll need to work out how to update the XmlSerializer to optionally support namespaces for deserialization. A: If you set Namespace for service to Empty, you do not need to pass xmlns. But you need root xml tag matching to method name i.e. <GetItem> <MyClass1> <MyProperty>1</MyProperty> </MyClass1> </GetItem>
{ "language": "en", "url": "https://stackoverflow.com/questions/7506072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to put the character & into an xml in android correctly I have a string that says "the following characters are invalid: "! @ # $ % ^ \& * ( ) / \ or space" and i don't know how to put the & symbol into an xml file without causing an error? I know you are suppose to do something along the lines of \& but I'm not sure exactly what it is? A: & would be &amp;. Wikipedia has a list of XML and HTML character entity references. A: in the context of an XML & is &amp; < is &lt; > is &gt; A: If \& doesn't work, try the XML entity &amp;. A: It's very simple. Use &amp;
{ "language": "en", "url": "https://stackoverflow.com/questions/7506074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do I reference dlls when "added as link" in project? I have two dll files in the project tree(not the references). They are added as link, they are assemblies of other project in solution. I'm trying to set their Build Action to Embedded Resource, so I can import them to .exe file. I can't write using statement, so I can't reference them in current project. How can that be done? A: You need to add a hard reference to the assemblies and set their Copy Local to False, then extract the assemblies from your embedded resources to the application directory before they are invoked. You can't reference a linked (shortcut) like you want. Key Points (in this example) and the Blog Article with Example Code * *EmbeddedReferenceApplication hard references EmbeddedReference.dll *EmbeddedReference reference property Copy Local is set to False *Linked assembly (Add as Link) is set as Embedded Resource Here is a working example. (EmbeddedReferenceApplication.exe | Console Application) using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Windows.Forms; using System.Reflection; using EmbeddedReference; // Hard reference with Copy Local = False namespace EmbeddedReferenceApplication { class Program { static void Main(string[] args) { AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve; MyMain(); } private static void MyMain() { EmbeddedReference.MessageHelper.ShowMessage(); } private static Assembly AppDomain_AssemblyResolve(object sender, ResolveEventArgs args) { string manifestResourceName = "EmbeddedReferenceApplication.EmbeddedReference.dll"; // You can also do Assembly.GetExecutingAssembly().GetManifestResourceNames(); string path = Path.Combine(Application.StartupPath, manifestResourceName.Replace("EmbeddedReferenceApplication.", "")); ExtractEmbeddedAssembly(manifestResourceName, path); Assembly resolvedAssembly = Assembly.LoadFile(path); return resolvedAssembly; } private static void ExtractEmbeddedAssembly(string manifestResourceName, string path) { Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream(manifestResourceName)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); using (FileStream fstream = new FileStream(path, FileMode.Create)) { fstream.Write(buffer, 0, buffer.Length); } } } } } In EmbeddedReference.dll using System; using System.Collections.Generic; using System.Text; namespace EmbeddedReference { public static class MessageHelper { public static void ShowMessage() { Console.WriteLine("Hello World!"); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Inheritance in C++ I was messing around with inheritance in C++ and wanted to know if anyone had any insight on the way it functions. Code below #include <iostream> using namespace std; class AA { int aa; public: AA() {cout<<"AA born"<<endl;} ~AA(){cout<<"AA killed"<<endl;} virtual void print(){ cout<<"I am AA"<<endl;} }; class BB : public AA{ int bb; public: BB() {cout<<"BB born"<<endl;} ~BB() {cout<<"BB killed"<<endl;} void print() {cout<<"I am BB"<<endl;} }; class CC: public BB{ int cc; public: CC() {cout<<"CC born"<<endl;} ~CC(){cout<<"CC killed"<<endl;} void print() {cout<<"I am CC"<<endl;} }; int main() { AA a; BB b; CC c; a.print(); b.print(); c.print(); return 0; } so I understand that when you inherit something you inherit constructors and destructors. So when I do , "BB b" it prints "AA born". So the question I have * *Is an instance of AA created *If yes, what is it called and how can I reference it? *If no, why is the constructor being called A: Inheritance implements the "IS-A" relationship. Every BB is therefore also an AA. You can see this in a number of ways, the easiest to demonstrate is: BB b; AA *aptr = &b; Here your BB instance b is being pointed at by a pointer which only thinks of itself as pointing to an AA. If BB didn't inherit from AA then that wouldn't be legal. The interesting thing is that when you call: aptr->print(); It still prints "I am BB", despite the fact that the pointer you used is of type AA *. This happens because the print() method is virtual (i.e. polymorphic) and you're using a pointer. (The same would also happen with a reference too, but the type must be one of those for this behaviour to happen) A: * *Is an instance of A created Sort of. The BB b; code will allocate a BB instance. Part of that object is an AA. * *If yes, what is it called and how can I reference it? Assuming the BB b; variable declaration, your part-of-BB AA instance is called b. If you want to call specific methods in AA that are hidden by BB methods, such as .print(), you need to invoke them like so: BB b; b.AA::print(); A: BB is an instance of AA. You don't need to access anything special, because you already have that type. When BB inherits from AA, here's how it's constructed. * *Call AA constructor *Initialize member fields *Call BB constructor When destruction happens, this happens in reverse. * *Call BB destructor *Destroy member fields (specific to BB) *Call AA destructor Oh, and you have at least one virtual function inside of AA. That means you need to make AA's destructor virtual (or bad things will happen). A: A class that derives from a base class contains that base class as a subclass, so an instance of the derived class contains a base subobject. The subobject is constructed first. The constructor that is used for that is yours to determine: If you don't say anything, the default constructor is used; otherwise, the constructor that you specify in the base initializer list is called. Example: struct Base { Base() { } // default constructor Base(int, double) { } // some other constructor char q; }; struct A : Base { }; struct B : Base { B() : A(12, 1.5) { } }; Both A and B contain Base as a subclass. When you say A a;, the subobject's default constructor is called. When you say B b, the subobjects other constructor is called, because you said so. As a consequence, if the base class has no accessible default constructor, then you must specify an accessible constructor explicitly. You can reference members of the subobject by qualifying the name: a.Base::q or b.Base::q. If the name is unambiguous, that's the same as just a.q and b.q. However, when you deal with overridden or hidden member functions (and maybe multiple virtual inheritance), being able to specify the subobject explicitly may be useful or even necessary. A: In object-oriented languages, there are two main ways of creating objects that inherit from another one: concatenation and delegation. The first one is the most popular, the second is used in prototype-based languages. Concatenation means that when B inherits from A, there are two parts in the object: in the first part of the object (of length equal to the size of A), the attributes (member variables/fields in C++) of A live. In the other part, there lives whatever attributes B adds to the object. Constructors for each involved class (A and B) are executed so all parts (all attributes) are initialized correctly. Though the object is managed as a single unit, you can point it with a pointer of class A. In that case, the pointer only lets you see the first part, the part pertaining to class A (i.e. its attributes), but not the attributes from B, since the pointer can only see from the beginning to beginning + size of class A. Say class A contains an integer x: class A { public: int x; }; and B contains an integer y: class B: public A { public: int y; } obB; This means that an object of class B will have a length of 8 bytes (for 32 bits), the length of x plus the length of y, while the length of A is of only 4 bytes, the length of x. A pointer of class A to objB: A * ptrA = &objB; will only see x, cout << ptrA->x << endl; cout << ptrA->y << endl; // ERROR while a pointer to B: B * ptrB = &objB; will be able to access both, x and y: cout << ptrB->x << ',' << ptrB->y << endl; In order to completely understand this, you need to know that ptrB->y is roughly translated into *( ( (int *) ptrB ) + 1 ), but that's another story. Hope this helps. A: Inheritance in c++ means the ability of objects in one class to inherit properties of another class which implements the reusablity concept. This means that it is not necessary to create a new methods and just override the existing one, if required. Saves a lot of work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Build jung for eclipse I'm trying to build a project for eclipse using maven. The project is jung.(http://jung.sourceforge.net/) According to their documentation,i need to 1.download the archive with the .jar files 2.extract it to a folder 3.Cd to the folder and run mvn eclipse:eclipse If i understand everything correctly,after that it should create a project for eclipse and i can link to the project via the varialbe M2_REPO in my own project and use the libraries in my code. But,the problem is that the maven says [INFO] Building Maven Stub Project (No POM) 1. (or [INFO] Cannot execute mojo: eclipse. It requires a project with an existing pomxml, but the build is not using one.for maven 2) I don't thing it is logically correct,because it requires the project itself before creating the project. After some googling i figured out that i need some project with a pom.xml file. Moreover,i can create such project using maven by typing mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false Ok,it creates the project,but what is next? How to bind the jung libraries to the project? I had made some tries (like moving the jars and the xml file to each other,an executing the maven commands,but i have got no good results). So,can somebody clearly describe the steps i should follow after getting the error "NO POM.XML" file? My final goal is an eclipse project that uses jung libraries. Thank you! A: It sounds like you are downloading the pre-built version, intended for people who just want to make use of the library. Hence it doesn't have a pom.xml file which is required for Maven to build the project, and may not even have the source code. If you want to build it yourself, then follow the instructions at http://sourceforge.net/apps/trac/jung/wiki/JUNGManual#Appendix:HowtoBuildJUNG remembering to use the second option given to check the code out of CVS ("If you are a user, do this:"). Or you could check it out of CVS from within Eclipse, in which case you wouldn't need to do the 'mvn eclipse:eclipse' part. If you are using Eclipse with a Maven project, then I would recommend installing the M2E plugin for Eclipse, available from the Eclipse marketplace. You can then enable the project as a Maven project and it makes it much easier to work with. I've just built it myself according to the instructions (although not set it up in Eclipse) and they worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get full belongs_to object in json render? Basically, I have an object that belongs_to :companies, and has the :company_id attribute. When I render json: @coupons, is it possible for the JSON to contain an attribute of its owner rather than the company_id? A: If you need to keep your json as compact as possible, it's best to use custom model methods to return only the data you need. I ended up adding a custom as_json method to the parent model and using the methods option to return subsets of the related object's data. Using include will include a full json serialization of the related model. def as_json(options={}) super( :only => [:id, :name], :methods => [ :organization_type_name, ] ) end def organization_type_name self.organization_type.name end A: You might be able to do something like render :json => @coupons.to_json(:include => :company), at least it seems to have worked with my initial testing in rails 2.3.8. Answer edited to use :include => :company rather than :include => :companies A: First of all your conventions are wrong. Its should be // In coupon.rb belongs_to :company And while rendering the object do this render json: @coupon.as_json(include: :company)
{ "language": "en", "url": "https://stackoverflow.com/questions/7506089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: javascript OOP get from parent object How can I access the parent attribute of a child object like this? var foo = function foo(input){ this.input = input; }; function bar(input){ return new foo(input); } foo.prototype = { baz : { qux : function(){ alert(this.parent.input ); } }, corge : function(){ alert(this.input ); } } bar('test').corge(); //alerts 'test' bar('test').baz.qux(); //errors 'this.parent is undefined' A: How can I access this.obj for a child object like this? You can't. There is one baz regardless of how many new foo there are, so there is no way to map from this which typically points to the singleton foo.prototype.baz to a specific instance of foo. It looks like you probably meant to create a baz per instance of foo. Try this function foo(input) { this.baz = { parent: this, qux: quxMethod }; this.input = input; } foo.prototype.corge = function () { alert(this.input); }; function quxMethod() { alert(this.parent.input); } A: Try defining baz like so: baz : (function(){ var parent = this; return { qux : function(){ alert(parent.obj); } } })() Update: I believe this will do what you want it to do: Demo: http://jsfiddle.net/maniator/rKcwP/ Code: var foo = function foo(input) { this.input = input; }; function bar(input) { return new foo(input); } foo.prototype = { baz: function() { var parent = this; return { qux: function() { alert(parent.input); } } }, corge: function() { alert(this.input); } } bar('test').corge(); //alerts 'test' bar('test').baz().qux(); //alerts 'test'
{ "language": "en", "url": "https://stackoverflow.com/questions/7506092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via" - Help? I am looked all over the internet and all over stack overflow to fix this problem and nothing has worked I hope someone has an idea what I am missing. I am trying to connect to an https: service but I am getting this error "The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via" This is my config: <system.serviceModel> <client> <endpoint address="https://authenicate.example.com/service/authenticate" behaviorConfiguration="Project" binding="basicHttpBinding" bindingConfiguration="SSLBinding" contract="Example.Test.Authentication" name="InternalAuthenticate" /> </client> <bindings> <basicHttpBinding> <binding name="SSLBinding" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="Transport" /> <readerQuotas maxDepth="32" maxStringContentLength="2048000" maxArrayLength="2147483647" maxBytesPerRead="4096" maxNameTableCharCount="2147483647" /> </binding> </basicHttpBinding> </bindings> <services /> <behaviors> <endpointBehaviors> <behavior name="Project"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="DispatcherBehavior"> <serviceMetadata httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> Any Ideas? A: You can use Mex binding instead for HTTPS. As mentioned in the comments there are alternatives that don't require the use of Mex binding. Take a look at this example. A: Or use a custom binding. <customBinding> <binding name="CustomHttpBinding"> <security allowInsecureTransport="True"> </security> <httpTransport /> </binding> </customBinding> I've had to do this to get arround some problems using WCF and a load balancer
{ "language": "en", "url": "https://stackoverflow.com/questions/7506093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How does this CGPDFDictionaryGetString translate into Monotouch? I have a piece of ObjC code from the great VFR PDF Viewer on GIT. It is using CGPDFDictionaryGetString to get a pointer to a string from a PDF annotation. Then it uses some byte pointer conversion to get the final string. In Monotouch there is no CGPDFDictionary.GetString() but only a .GetName() - this is the only method that returns a string, so I assumed that must be the correct method but it does not work. I can retrieve arrays, dictionaries, floats and integers just fine - only the strings don't seem to work. See the small code examples below. CGPDFStringRef uriString = NULL; // This returns TRUE in the ObjC version and uriString is a valid pointer to a string. if (CGPDFDictionaryGetString(actionDictionary, "URI", &uriString) == true) { // Do some pointer magic - how to do this in MT? Do I have to at all? const char *uri = (const char *)CGPDFStringGetBytePtr(uriString); // *uri now contains a URL, I can see it in the debugger. } I translated it like that: string sUri = null; // This returns FALSE. Hence my sUri is NULL. Seems like GetName() is not the analogy to CGPDFDictionaryGetString. if(oActionDic.GetName("URI", out sUri)) { // I never get here. } EDIT: Looking at the Mono sources I can see this in the Master branch: // TODO: GetString -> returns a CGPDFString Switching to branch 4.2 reveals that it seems to be there. So I copied the code from there but have two issues: * *I get an error about the "unsafe" keyword. It tells me to add the "unsafe" command line option. What is that and is it a good idea to add it? Where? *It seems to run anyway but the app hangs when getting the CGPDFString. [DllImport (Constants.CoreGraphicsLibrary)] public extern static IntPtr CGPDFStringGetLength (IntPtr pdfStr); [DllImport (Constants.CoreGraphicsLibrary)] public extern static IntPtr CGPDFStringGetBytePtr (IntPtr pdfStr); public static string PdfStringToString (IntPtr pdfString) { if (pdfString == IntPtr.Zero) return null; int n = (int)CGPDFStringGetLength (pdfString); unsafe { return new String ((char *)CGPDFStringGetBytePtr (pdfString), 0, n); } } [DllImport (Constants.CoreGraphicsLibrary)] extern static bool CGPDFDictionaryGetString (IntPtr handle, string key, out IntPtr result); public static bool GetStringFromPdfDictionary (CGPDFDictionary oPdfDic, string key, out string result) { if (key == null) throw new ArgumentNullException ("key"); IntPtr res; if (CGPDFDictionaryGetString (oPdfDic.Handle, key, out res)) { result = PdfStringToString (res); return true; } result = null; return false; } A: If you use the unsafe keyword in your source then you need to enable unsafe when building your assembly. In MonoDevelop you can do this by: * *Right-click on the project; *Select Options menu; *Select General icon; *Click the Allow 'unsafe' code checkbox *Click Ok button *Then rebuild. Note: Your previous build should not have worked without this. Source code between master and monotouch-4.2 should be identical in this case. I'll check but it's likely that you were looking at a specific revision in GIT (the was pushed before the code was updated). I'll check to be sure and edit the post. UPDATE : This is the link to master (i.e. latest code available) and it shows: public bool GetString (string key, out string result) to be available. However it does depend on unsafe code (inside PdfStringToString) which you should not have been able to compile without allowing unsafe code in the assembly where you copy/pasted this code. UPDATE2 : The value returned is UTF8 encoded so the string created from it needs to be decoded properly (another System.String constructor allows this). The above link to master should already point to the fixed version. A: I'm not a big fan of using unsafe blocks, and worked out a way to implement this method without using one. Initially I did try the unsafe style, however as the string is stored in UTF8 it needs to be converted. private bool PDFDictionaryGetString (IntPtr handle, string key, out string result) { IntPtr stringPtr; result = null; if (CGPDFDictionaryGetString(handle, "URI", out stringPtr)) { if (stringPtr == IntPtr.Zero) return false; // Get length of PDF String uint n = (uint) CGPDFStringGetLength (stringPtr); // Get the pointer of the string var ptr = CGPDFStringGetBytePtr (stringPtr); // Get the bytes var data = NSData.FromBytes(ptr, n); // Convert to UTF8 var value = NSString.FromData(data, NSStringEncoding.UTF8); result = value.ToString(); return true; } return false; } There's a full blog post here and working sample including complete source here featuring multipage swipe navigation and clickable links.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery UI Resizable: set size programmatically? For example, user inputs width and height values to tell the widget to resize to that dimension. How to implement this? A: var w = prompt('width?')*1; var h = prompt('height?')*1; $('#resizable').css('width', w ); $('#resizable').css('height', h ); You don't need to use jqueryui's resizable in order to resize it in script. The jQuery .css() method applies for any DOM element. You can also animate({width: 500},1000). A: I use for this following code: function resize(target, new_width, new_height){ var $wrapper = $(target).resizable('widget'), $element = $wrapper.find('.ui-resizable'), dx = $element.width() - new_width, dy = $element.height() - new_height; $element.width( new_width ); $wrapper.width( $wrapper.width() - dx ); $element.height( new_height ); $wrapper.height( $wrapper.height() - dy ); } A: You can extend original Resizable widget like follow: (function( $ ) { $.widget( "custom.mysizable", $.ui.resizable, { options: { x: 0, y: 0 }, _create: function() { $.ui.resizable.prototype._create.call(this); this.options['x'] = $(this.element).width(); this.options['y'] = $(this.element).height(); }, _resize: function(x, y) { if( x != null ){ $(this.element).width( x ); } if( y != null ){ $(this.element).height( y ); } this._proportionallyResize(); }, _setOption: function( key, value ) { this.options[ key ] = value; this._update(); }, _update: function() { this._resize( this.options['x'], this.options['y'] ); }, _destroy: function() { $.ui.resizable.prototype._destroy.call(this); } }); })( jQuery ); To use it $('#myElement').mysizable('option', 'y', 100); $('#myElement').mysizable('option', 'x', 100);
{ "language": "en", "url": "https://stackoverflow.com/questions/7506104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android Detect which way user swipes finger over picture How can i detect which way i user swipes the picture if they swipe it right then (DO SOMETHING) if they swipe it left then (DO SOMETHING) A: you can get the array of screen touch locations from event.getX(x) (for example event.getX(0) means latest motion event and getX(1) means previous to latest). In this you can apply a formula to detect in which side are you swiping. For Right.. { if(event.getX(0)- event.getX(1) > 0) // You swiped to right } and similarly for left (i.e. xxxxxx < 0).
{ "language": "en", "url": "https://stackoverflow.com/questions/7506115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does linq not work off of a IList? Want to see if collection of type T contains a particular entry I have a list of IList<Products> And I want to see if the collection contains the product where product.Key == "ABC" A: You want to use the Any method: bool b = list.Any(x => x.Key == "ABC"); A: It does, it's generally called LINQ to Objects when used that way. If you don't have it, you would need: using System.Linq; at the top of the file to get access to the extension methods. A: Yes Linq works on IList as well? What's the problem with you're code?
{ "language": "en", "url": "https://stackoverflow.com/questions/7506116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: RabbitMQ / ActiveMQ or Redis for over 250,000 msg/s Eventhough redis and message queueing software are usually used for different purposes, I would like to ask pros and cons of using redis for the following use case: * *group of event collectors write incoming messages as key/value . consumers fetch and delete processed keys *load starting from 100k msg/s and going beyond 250k in short period of time (like months) target is to achieve million msg/s *persistency is not strictly required. it is ok to lose non-journaled messages during failure *performance is very important (so, the number of systems required to handle load) *messages does not have to be processed in the order they arrive do you know such use cases where redis chosen over traditional message queueing software ? or would you consider something else ? note: I have also seen this but did not help: Real-time application newbie - Node.JS + Redis or RabbitMQ -> client/server how? thanks A: Given your requirements I would try Redis. It will perform better than other solutions and give you much finer grained control over the persistence characteristics. Depending on the language you're using you may be able to use a sharded Redis cluster (you need Redis bindings that support consistent hashing -- not all do). This will let you scale out to the volume you indicated. I've seen 10k/sec on my laptop in some basic tests. You'll probably want to use the list operations in Redis (LPUSH for writes, BRPOP for reads) if you want queue semantics. I have a former client that deployed Redis in production as a message queue last spring and they've been very happy with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Validation (HTML5): Attribute 'X' is not a valid attribute of element 'Y' I quite often do this: <input type="text" id="whatever" quantity="2" price="15" /> which causes VS2010 to issue the above warning -- I can live with the warnings because the inherent value in being able to hang data on form fields (which allows me later to pick them up for use in code e.g. $('#whatever').attr('price'), or simply document.getElementById('whatever').price) makes the nuisance warnings worth bearing. However, I was wondering what the canonical approach to this problem is... anyone? TIA - ekkis A: You should replace quantity="2" price="15" with data-quantity="2" data-price="15" -- which has the added bonus of making the values accessible through jQuery's .data() method: alert( $('#whatever').data('price') ); // displays 15 http://blog.jquery.com/2011/05/03/jquery-16-released/ A: If you're using jQuery, you can store those variables in the object itself with .data(): $('#whatever').data('quantity', 2); But I suggest splitting up your <input /> into multiple <input />s if you absolutely need to keep the information in the HTML file: <input type="hidden" id="whatever-quantity" value="2" /> <input type="hidden" id="whatever-price" value="15" /> But for complete HTML5 awesomeness, just prepend data- to your attributes: <input type="text" id="whatever" data-quantity="2" data-price="15" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7506120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read a Version 2 Sqlite database from .Net? Seems that System.Data.SQLite supports only version 3. What to use to read version 2? I don't want to use the sqlite3.dll directly because it only supports 32 bit. A: From SQLite docs: Format 2 adds the ability of rows within the same table to have a varying number of columns, in order to support the ALTER TABLE ... ADD COLUMN functionality. Support for reading and writing format 2 was added in SQLite version 3.1.3 on 2005-02-19. Latest version of SQLite for .NET is actually here (not at phxsoftware.com anymore). They distribute x86 and x64 bit versions. The latest release supports SQLite 3.7.7.1 so it should be able to read V2 file. Take a look at this answer for some details. A: Did you check out http://sqlite.phxsoftware.com/? Their latest version has a x64 ADO.NET provider for SQLite 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with setTimeout and reloading iframes I'm trying to change the src of an iframe every 2 seconds with different page but I failed miserably so far. Can anyone tell me what's wrong with this code? It only loads the last file, 5.html and not the other ones, 1.html 2.html 3.html and 4.html function reloadiframe(nbr) { setTimeout(function () { document.getElementById("iframe").src = nbr + ".html"; }, 2000); } function reload() { for (i=1;i<=5;i++) { reloadiframe(i); } } A: setTimeout does not wait. The timeouts all fire at pretty much exactly the same time, since they are all started at pretty much exactly the same time. Just a small change will fix the problem: function reloadiframe(nbr) { setTimeout(function () { document.getElementById("iframe").src = nbr + ".html"; }, 2000*i); // <== right here } function reload() { for (i=1;i<=5;i++) { reloadiframe(i); } } A: You're now delaying the reload for two seconds. Page 1, 2, 3 and 4 actually get loaded, but are quickly overwritten by frame 5. Either use setTimeout in reloadiframe to delay the next reload, use setInterval to periodically reload the iframe or increase the timeout: function reloadiframe(nbr) { document.getElementById("iframe").src = nbr + ".html"; if (n <= 5) { setTimeout(function () { reloadiframe(nbr + 1); }, 2000); } } function reload() { setTimeout(function () { reloadiframe(i); }, 2000); } Alternative using setInterval: var timer, nbr; function reloadiframe() { document.getElementById("iframe").src = nbr + ".html"; if (nbr > 5) { clearInterval(timer); } } function reload() { nbr = 1; timer = setInterval(reloadiframe, 2000); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it true that MongoDB has one global read/write lock? I am reading this article - http://wiki.postgresql.org/images/7/7f/Adam-lowry-postgresopen2011.pdf and I noticed that an ugly part of mongoDB is the global lock. Is it true that MongoDB has a global lock for read/write operations? what about the latest versions? Is there a plan to change that? A: yes. it's true: http://www.mongodb.org/display/DOCS/How+does+concurrency+work but they are working on it, if you look at the change log of the 2.0, they started to deal with it: http://blog.mongodb.org/post/10126837729/mongodb-2-0-released The read/write lock is currently global, but collection-level locking is coming soon
{ "language": "en", "url": "https://stackoverflow.com/questions/7506124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: iPhone: How can a child tell his parent to do something OK, I have a RootViewController.m and defined a method in there: -(void)doSomethingParent { NSLog(@"Parent is doing something after child has asked"); } I then added a childViewController.view like so: if (self.child == nil) { ChildViewController *cvc = [[ChildViewController alloc] initWithNibName:nil bundle:nil]; self.child = cvc; [cvc release]; } [self.view insertSubview: child.view atIndex:0]; Now, I thought it would be very useful indeed if I could call my doSomethingParent method from the child. So I thought I would do it like this: @implementation ChildViewController @class RootViewController; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [super doSomethingParent]; } But xCode tells me that "-doSomethingParent" not found... but I put @class in there?! Shouldn't it find it? I don't want to import the whole thing as I thought @class would be sufficient to let the child know that the parent has a method called doSomethingParent... I'd be very grateful for any suggestions. Thanks in advance! A: Set rootViewController object as the delegate of an object of childViewController type. And use that delegate from ChildViewController to pass messages to RootViewController. Inside RootViewController, when you create your ChildViewController object do: childViewController.delegate = self; And in ChildViewController, when you want to pass a message then pass it to RootViewController as: [delegate doSomething]; In your ChildViewController.h interface, declare an ivar: id delegate; Then use @property (in .h) and @synthesize (in .m) for getter and setter. Then do the above. A: super is a reference to it's superclass, not the parent view controller. You will have to keep a reference to RootViewController and pass the message to it... ...Or code a protocol and set your RootViewController as delegate of the child, so the child would be able to pass messages to RootViewController. I prefer the second way. A: Easy way (perhaps not the best way): self.child = cvc; cvc.myParent = self; // give the child a reference to its parent
{ "language": "en", "url": "https://stackoverflow.com/questions/7506125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: problems using cron to run a pymongo script I'm running a simple python script sending data to a mongodb #!/usr/bin/env python import sys import time from datetime import datetime import pymongo from pymongo import Connection today = { 'date and time' : datetime.today() } connection = Connection() db = connection.tests collection = db.times collection.insert(today) And I'm trying to use cron to schedule this every minute. I've used crontab to set this * * * * * /Users/MyUser/XX/YY/ZZ/timetest.py And I can execute this perfectly using python timetest.py from the correct directory; however the program is still not running on its own. I feel like I'm very close to getting it to work, can anyone help me with this? A: It is likely that the cron environment does not match your user's environment. In cron you can either set the path variable in crontab like PATH=$PATH:/usr/bin * * * * * /Users/MyUser/XX/YY/ZZ/timetest.py or you can just explicitly call the python binary on your script * * * * * /usr/bin/python /Users/MyUser/XX/YY/ZZ/timetest.py or you can set the shebang line in your script to reference the python binary explicitly (this may not be desirable if you ever use virtualenv) #!/usr/bin/python ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7506129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress - How to tell if im on the main page Just wondering how to tell if this is on the main page if (mainpage??) // do A: Use this function: http://codex.wordpress.org/Function_Reference/is_home
{ "language": "en", "url": "https://stackoverflow.com/questions/7506131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Password protect entire site depending on domain? I have a development and production site that are both public on the Internet. I want to make the development server locked down. I was told to use .htpasswd to put a password on the root web directory on the development server to restrict public access. The problem is, my current workflow syncs everything between the production and development servers. Files, server settings, etc. I do this to ensure that the production server behaves as expected. So the problem is if I set up .htpasswd on the dev, after syncing, the production server will be password protected as well. So I was wondering if there is a way to make .htpasswd domain specific or if there is a better way of doing this all together? A: You sync everything between development and production? That is definitely not best practice (do you have change approval processes?). On topic, what are you using to sync? Just put an exclusion in to avoid copying the .htpassword files over. Or alternatively, create separate virtual hosts for your development and production and secure the development virtual host, while leaving the production untouched.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Valgrind errors when linked with -static -- Why? I have a test driver linked to a library I wrote. The library uses autotools so it produces both an archive (.a file) and a dynamic library (.so). When I link my driver with 'g++ -static', presumably linking to the .a, valgrind lights up complaining repeatedly 'Conditional jump or move depends on uninitialised value(s)'. The first failure occurs before main in __pthread_initialize_minimal. When I link without -static, presumably linking with the .so, I don't get any valgrind complaints. Does anyone know why? Does valgrind just not work with -static? UPDATE: I can't post even a pared down version of my driver because it links to a very large library that I couldn't possible pare down, but I notice that simplest of all programs int main() { return 0; } gives an error when linked with -static and run from valgrind: ==15449== Use of uninitialised value of size 8 ==15449== at 0x40B0F3: exit (in /home/jdgordo/src/t) I should have included that I'm running on 64-bit Redhat 5.5. A: Does valgrind just not work with -static? It does. The problem is not in Valgrind, it's in glibc, which is not Valgrind clean. The glibc developers refused to fix these problems (because the problems are of a "don't care" nature, and fixing them costs (a few) cycles). When you link dynamically, these errors come from libc.so.6, and can be easily suppressed, which is what Valgrind does by default. But when you link statically, these errors come from your executable (which now includes code from libc.a), and so the default Valgrind suppressions don't suppress them. You could write new suppressions (see Valgrind --gen-suppressions=yes documentation). Or you could install and use glibc-audit. A: If the library causes problems in valgrind, you can only ignore those problems by writing suppression files. One of problems I encountered is alocating something on the heap, like this : // library int * some = new int; // main links the library int main() { } This example would report an error about leak. EDIT : if you have the library's source, you can fix the error (use of uninitialized variable), and recompile it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: how to implement constraints on a web application workflow based on rules We have the following problem in our web application. There is a workflow for creating an order on the application : * *entering informations about the customer (one web form) *entering informations about the device (another web form) and some constraints on each form in order to advance to the next step : * *the customer has a series of attributes (first name, last name, street, telephone number) which need to be specified *when the customer wants to be notified by sms then a valid mobile phone number needs to be introduced *for the device (for a which a payment type (Card/Cash/Cheque) retrieved dy there is a certain amount of money to be accepted by the customer in order to create the order Currently these constraints are implemented directly in the source code of the application, and this is making the application harder to maintain (some of the rules change from a version of the application to the next). What would be a good approach to externalize these checks from the code when creating the order? A rule-engine like Drools could be a good solution, but I'd like to give the possibility to the administrator of the site, via a visual editor to define the validation rules. Can anybody recommend me a solution which exists already for this situation? A: to some extent spring-webflow can help you. otherwise there are various workflow/bpm kind of solutions available (i had worked on Savvion BPM once), then I think jboss drools is there. A: You could create a separate process for validating information from the user. we have created a servlet that all request come through (You could use JSP's if you wanted). When a request comes in we can get the request parameters and pass them to the validation classes along with what type of form the user filled out. The validation classes would do the required validation and then pass back true or false along with the names of any fields that failed. When the servlet starts up it would go to a database or XML file and retrieve the required fields for each form and store it in it's cache. The fields in the database or XML file would have the same name as the fields in the HTML form. If you wanted to add/remove a field that is required you would just need to add/remove the field in the HTML form and add/remove the field from the database or XML file. No code changes would be needed. Since the validation data is stored in cache the database or XML file would only be read once when the server is started. If performance is not an issue you could read from the database or XML file every time. You could also validate that the data was valid (ex. last name has valid characters) by also storing regular expressions along with the form field names. This way you could change how a field is validated by just changing the expression in the database or XML file. No code changes no major retesting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gnuplot how to make x-axis 1,3,5 ... instead of 1,2,3,4, I have a text file with a single column of data generated from a C program that I am plotting via gnuplot. Without generating an additional column for the index from the C program, i.e without changing the data from, say: "stat".txt" 23423 43543 45562 32423 to 1 23423 3 43543 5 45562 7 32423 can I make gnuplot change the x axis numbering from 1,2,3,4,... to 1,3,5,7... When I plot "stat.txt" the corresponding x value to each row entry is by default 1,2,3,4... Presently, I did add an additional column for the index and used the command plot "stat.txt" using 1:2 but I am curious to know. A: Column 0 in gnuplot is the record number. plot "stat.txt" using (2*$0-1):1 will give you 1,3,5 for the x values on the plot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression on voxel space Is there a way to loosely describe an object (via pattern matching finite automata, for example) in 3d voxel grid in the same way we can loosely describe patterns in one-dimensional string with regexp? Let's say I want to describe a cuboid of "A" type voxels with lower facet composed of "B" or "C" type voxels with height 3 and width 5, and match this description to voxel field to find examples of pattern. I can do some search for exact models (kind-of-like-Boyer-Moore-in-3D) but I need to specify variable dimensions for some objects (like variable length for aforementioned cuboid). A: Regular expressions are a compact way to express the syntax of a limited (and still infinite) set of languages. With regular expressions you don't need to tell where to look for the next symbol, since it is known that you are working on a string and iterating over its characters taking them as the symbols of the language... but in 3D you will need to tell what way to go. You can think about it as a 3D Turing machine, that is a Turing machine that has an internal state and can read symbols from a 3D "tape", since we are only verifying let's ignore writing to the tape. Then, this Turing machine will walk the 3D "tape" aka the 3D voxel grid and read voxels as symbols, after reading each symbol the internal state of the Turing machine will change according to certain laws. Once the execution is over the final state of the machine tell you if it were a match or not. Now these laws in a Von Newman Architecture are an interpretation of the data from tape as instruction, but we want a Harvard architecture, that is that the instructions are separated from the data. Now what you want is a way to describe those instructions for the Turing machine. [You can think of this as the turtle of Logo but in 3D]. Following the spirit of the regular expressions we would prefer a language that resembles the actual structure. If we make it text based it will be a descriptive language (because an imperative one is no better than your favorite Turing complete one), it will have to say for example (in English): There is a voxel type A and then moving (x1, y1, z1) from that there is a voxel of type B or C and then moving (x2, y2, z3) from that there is a voxel type D This describes what the Turing machine is looking for, with a backtracking algorithm that test all potential matches it will work as expected. Please note that I don't know the set of possible values of the voxels. That is, I don’t know the alphabet. So I've just said type A, type B, type C and type D as examples, one of those may be the representation of no voxel, and the others may be colors or whatever you are using. There can be as many types of voxels as needed. If the type of the voxel is complex the description of it got to be inserted there. I've been thinking of practical use this kind of language and one problem that arises very quickly is rotations, I have to decide that three voxels type A over the X axis is considered the same a three voxels type A over the Z axis, the better is to allow to describe that in the language. Now it is very similar to describe a path if the voxels are nodes, I've done a language to describe 2D paths as part of a private project (to store them in a database, go figure...), it is very simple, it reserve a character for every direction and uses a number for the steps, for example: "2d5l1u". Doing the same for 3D and adding a way to group and match will do. To solve the rotation problem it will be necessary to expand the direction to allow disjunctions to express alternative configurations for the match. This will become clearer on some example of how it may work that I've thought of (I've not worked a formal syntax in EBNF or similar): Matching a line of three voxels type A over the X axis: (A1X){3} Here I intercalate matching "A" with movement "1X", use parenthesis "(" and ")" for grouping and the curly brackets "{" and "}" to quantify. This unrolls to this: A1XA1XA1X The last "1X" doesn't affect the result, so it may as well be: A1XA1XA And it clearly says: Match a type A voxel, move 1 over the X and match a type A voxel, move 1 over the X and match a type A voxel. Matching a line of three voxels type A over the X axis or the Z axis: (A1X){3}|(A1Z){3} Alternative: (A1[X|Z]){3} Here I use brackets "[" and "]" to make a 'class', the location of it tells it is about the direction and it only includes the possible axis, do not confuse with: [(A1X)|(A1Z)]{3} This will match three voxels type A but they may not be on the same axis, they only got to be contiguous and share either the X axis or the Z axis with it neighbor. Matching a 3x3 set of voxels type a over the plane X, Y: (((A1X){3})1Y){3} This matches a line over the X axis and the moves 1 over the Y axis to match another and so on. It implies that after grouping a repetition "([(A1X)]{16})" we backtrack to where the match begun to execute the following move "1Y". To unroll it would be: (A1XA1XA1X)1Y(A1XA1XA1X)1Y(A1XA1XA1X)1Y Look the remaining parenthesis, those means to backtrack to where the match begun. So the program will check what is inside of the group and when it is done it will go back where it was before entering the group and continue executing after it. Matching a pair of voxels type A separated by a voxel of ignored type (over any axis): A1(X|Y|Z).1(X|Y|Z)A1(X|Y|Z) Influenced by regular expressions we use the dot "." to represent any type of voxel. I still don't decide if it is better to use negative values than to use other letters for other axis, also I consider that the number 1 could be optional. Also other parts of the syntax of regular expressions such as "+", "*", and "?" got to be though out more carefully. It may be good to enforce "{" and "}" for any quantification until proven that there is no ambiguity. As you may have notice it will not be a problem to add another direction of movement or entirely another axis, so this port very well to say four dimensions, as in: (A1[X|Y|Z|W]){3} It may also be good to use the dot "." to represent any direction: (A1.){3} There is a problem with assuming any direction when not specified and that is that this language is defined to identify what is a direction and distinguish them from voxel types based on the location inside of the expression. So "(A1B1){3}" will not map to "(A1.B1.){3}" because it will take "B" as the direction to move, it may be possible to infer the meaning by the trailing number at the end, but I don't know if it will be unambigous. Lastly this will match any valid tetris piece in the plane X, Y made of voxels type A: (A1[X|Y]){4} If we assume that the world is only bidimensional and that we allow to ignore the number one, it reduces to this: (A.){4} And I'm happy with that. Nevertheless, you should consider a more complex, less compact and more readable notation for complex structures. And that is my theory for generalizing regular expressions to two, three or more dimensions. EDIT: If the type of voxel is complex or causes ambiguity I propose to write it with angular brackets "<" and ">", so for example you can use the hex value of the raw voxel data: (<0088FF>.){4} A: I don't know much about 3D or voxels, but if you can transform your 3D space into a one-dimensional representation using a markup, then you can use a regex on it. Simplified example: For a cube with a blue face, red face, green face, and 3 others we don't care about: <object> <cube> <faces> <face orientation="up" color="blue"> <border neighborOrient="west"> <border neighborOrient="south"> <face orientation="west" color="red"> <face orientation="south" color="green"> ... </faces> </cube> </object> Your regex could look for faces within the same cube which share a border. Regexes work best with text, so your first step should be to find a way to "flatten" down to text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jquery UI's css file I have started to read through the documentation on the jquery UI plugin (themeroller). Since these plugins are further and further abstracting web design, I wanted to make sure that I understand basically what jquery is doing behind the scene. I am now using the Dialoge box example and I found that it used the following css code: .ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -khtml-border-top-left-radius: 4px; border-top-left-radius: 4px; } I do not recognize the -moz, -webkit etc css styles. Can someone explain to me what all of these styles are? I tried googleing them and came up blank. A: These are for backwards compatibility with older browsers back in the old days (not long ago) when browsers could not understand the border-radius css property. These specific terms enables the corresponding browser to understand and apply the style after all. Basically: this is for older browsers A: They are vendor specific css settings. Typically when css rules have not been fully adopted by all browsers, manufacturers add support for the styles by prefixing their name before the style. -ms- Microsoft mso- Microsoft Office -moz- Mozilla Foundation (Gecko-based browsers) -o- Opera Software -atsc- Advanced Television Standards Committee -wap- The WAP Forum -webkit- Safari (and other WebKit-based browsers) -khtml- Konqueror browser http://reference.sitepoint.com/css/vendorspecific A: All these things basically set the same style but for different browsers. A: Browsers have been implementing their own extensions to CSS since before HTML5 (or more accurately CSS3, in this case) became popular but they often implemented in slightly different ways. To avoid conflicting with other browsers Firefox prefixes their "proprietary" extensions with -moz, Webkit with -webkit and so on. Here is the MDN documentation. You can't google for it exactly because it is prefixed with a hyphen and that will exclude results. moz-border-radius-topleft will be more helpful. A: The implementation of this properties is different for each browsers. Prefixing the name of this properties makes the style compatible with Firefox (-moz), chrome (-webkit) etc... http://www.css3.info/preview/rounded-border/
{ "language": "en", "url": "https://stackoverflow.com/questions/7506149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Timer problem with GDI+ I am currently stuck at a really strange problem with GDI and timers. First the Code: class Graph : UserControl { private System.Threading.Timer timer; private int refreshRate = 25; //Hz (redrawings per second) private float offsetX = 0; //X offset for moving graph public Graph() { timer = new System.Threading.Timer(timerTick); } private void timerTick(object data) { offsetX -= 1 / refreshRate; this.Invalidate(); } public void timerStart() { timer.Change(0, 1000 / refreshRate); } private void onPaint(object sender, PaintEventArgs e) { //350 lines of code for drawing the graph //Here the offsetX will be used to move the graph } } I am trying here to move a painted graph in a specific time to 1 "graph unit" to the left. So i use a timer which will change the offset in little steps, so it will be a smooth moving (thats the refreshRate for). At the first view this code worked, but later i found following problem: If i am using a refreshRate of 1 (1Hz) it will just fine move my graph in 1 step 1 (graph unit) to the left. If i am increasing the refreshRate my movement will slow done. At 20 FPS its slighly slow, at 200 FPS its really slow.. So here is what i tried: * *I used Refresh or Update instead of Invalidate *I used a normal Thread (with Sleep) instead of the timer Both code changes didnt changed the result.. Beside the movement with the timer I also can move the graph with my mouse and if the timer is running i can still smoothly move the graph with my mouse. So its not a peformance problem.. I thought of a problem in the painting queue, because I am refreshing faster than the painting is done? (But why can I sill move the graph smoothly with my mouse?!) So i need a little help here. Thanks A: At 20 FPS its slighly slow, at 200 FPS its really slow.. There is a fundamental problem here; to get a refresh rate of 200fps you would need to repaint every 5ms. This will never happen. No matter what you set your timer's interval to it's resolution is limited to about 10-15ms. So your best possible frame rate is about 66-100fps, and that's assuming that your drawing code takes zero time, which of course it does not. On top of that, you are using a System.Threading.Timer which does not perform it's callbacks on the UI thread, so calling Invalidate() from there is probably not even safe. You don't typically use a System.Threading.Timer for UI code. You may want to try something like the so called Multi-Media Timer shown here, which uses the CPU's high performance timer and gives a resolution of about 1ms. A: You may try to change the problem slightly. Since you do not know how long your painting will take, you cannot make an assumption about that. What you do know, is the amount of time you want the transition to happen, let's say 30 seconds, something like this: private MAX_TRANSITION_TIME = 30; //seconds At this point you can also track the amount of time it has elapsed since the start of your operation, by recording when your operation has started, let's say private DateTime _startMoment; Now what you can do is to make sure you have the right routine at hand and you calculate your position based on the difference between the startMoment and now var elapsedTime = DateTime.Now.Subtract(_startMoment).Milliseconds; var elapsedPercent = elapsedTime / MAX_TRANSITION_TIME * 1000.0 ; From now on what you can do is to paint accordingly to your percent of time elapsed. So after your OnPaint is done you should be able to refresh it. If you use one UI timer, you can do this: private void onPaint(object sender, PaintEventArgs e) { Timer1.Enabled = false; //350 lines of (adjusted)code go here If (ElapsedPercent<1) { Timer1.Enabled=True; } else { // you may need to perform the last draw setting the ElapsedPercent // to 1. This is because it is very unlikely that your // last call will happen at the very last millisecond } } Where Timer1 has to be the Timer control. In the Interval event you just write _startMoment = DateTime.Now(); this.Invalidate(); Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7506161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rules engine for .NET We have a business requirement to let power users edit rules for insurance rates and enrollments. We need a web ui that lets them say "this product is only for people <55 unless they are from Texas and own a poodle" or whatever. Edit for clarification: Insurance is insane. The rules differ from product to product, state to state and change constantly. We looked at a couple of rules engines but the commercial ones are 100K+ and the open source ones don't seem um, finished. Windows Workflow works if we create the rules ahead of time, but building them at runtime seems to require bypassing code access security. That's scary. Are we nuts to reinvent this wheel? Is there a better alternative for .net? A: 100K isn't chump change, but a decent programmer for a year will almost certainly cost more than that - do you have a cheaper programmer that can do it faster than a year? will it be just as good (for your needs) or better? A: This is not quite my field, I came by this question by accident, so I may be off, but I'd take a look at Wolfram Mathematica. It is a technical computing environment and multi-paradigm (proprietary) programming language, supporting many programming styles (including rule-based and functional programming). It has a very general rule engine at its core. Despite the name and reputation as mathematical software (which it is), it is a general-purpose programming language, very high-level. A subset of it can be compiled to C. It can load external dlls dynamically, and it transparently inter-operates with both Java and .Net platforms. It has a web version - webMathematica (which is based on Java however, jsp+Tomcat, but no one stops you from interfacing it with your .Net - based web layer directly, just some more work). The additional benefit is that, if you ever need any mathematical computations, analysis, plots, statistics, it's all there, and state of the art. I'd think it should be much faster to develop the functionality you need in Mathematica than in many other languages / solutions (I program professionally in Mathematica, C, Java and Javascript, so can at least compare these languages). The full commercial license should be 2 or 3 K for a single machine (4 cores), I think. It has several parallelization features. The hardest thing in this approach would be to find a competent Mathematica programmer, but someone with a background in functional/rule-based programming (LISP / Prolog, say) should be able to pick up things fairly quickly. Also, it may not be sufficiently fast if you need very high performance - I really don't know how it compares in terms of performance with other rule engines. On occasion, I had a chance to compare in Mathematica a rule-based solution for some problem to the one compiled to C, and I'd say well written rule-based code should be on the level of Python in terms of performance, and on the average perhaps one order of magnitude or so slower than the one compiled to C. But that was mostly for numerical/computational or data-manipulation-related problems, so I'd think for problems inherently based on rules, the performance gap could be smaller. One thing I am sure about is that in Mathematica you can create sets of rules of any generality and complexity fairly easily with a small amount of code. It is a best tool for exploratory programming based on rules that I encountered so far, with a very short development cycle. I invite you to visit the Mathematica tag here at SO to see what types of problems people are solving with it. For one prominent project written entirely in Mathematica language (15 millions lines of code), check out WolframAlpha knowledge engine. A: I do not think that the evaluation of the rules will be the challenge. I think that the greater challenge is to parse the rules that the user can enter. For parsing the rules you should consider to create some DSL. Martin Fowler has some thoughts about this here. Then maybe ANTLR then might be worth a look. For the evaluation part: I work in the finance industry and there are also complicated rules, but I never had to use a rule engine. The means of an imperative programming language (in my case C#) were (until now) sufficient. For some occasions I was considering a rules engine, but the technological risks(*) of a rule engine were always higher than the expected benefits. The rules were (until now) never that complicated, that declarative programming model was needed. If you are using a object oriented language you can try to apply the Specification Pattern. Eric Evans and Martin Fowler have written a more detailed explanation, which you can find here. Alternatively you can write your own simple rule engine. (*) Footnote: Somehow you will need to embed the rule engine into your application which is very likely written in some object oriented language. So there are some technological boundaries, which you have to bridge. Every such bridge is a technological risk. I had once witnessed a Java web application using a rule engine written in C. At the beginning the C program sometimes produced core dumps and tore down the whole web application. A: I think as with most make vs buy decisions it's always a tradeoff you have to make personally. If you buy an off the shelf solution which costs 100K+ and you're only going to use 1% of it than that is probably some money unwisely spent. However if the product is a perfect fit then you can almost be sure you can never build it for less (assuming they have a lot of experience in that particular field). So no you're not nuts to reinvent this wheel as long as you're not trying to do everything the off the shelve product does and just focus on the specific functionality you need and not get yourself tempted by the idea of building a very nice (but expensive) framework for something very simple. A: Is there a better alternative for .net? One option is to use an embedded script engine inside your .net code, like Iron Python. Give a GUI for your users to make rules, convert "the rule" to Python script, call the Python script engine inside of .Net to execute the script. Are we nuts to reinvent this wheel? If nothing off the shelf meets your needs then No. A: The problem is that these things are so intertwined with the how a business uniquely operates it's difficult, if not impossible, to effectively use an off the shelf solution. I've done something like this two different ways. The most recent (in VS 2005/Framework 2.0) was to create a base engine that handled the common minimum requirements that would be the case across the board. This would be stuff like name, address, etc. Then I wrote a series of extension DLLs that used common interfaces would be loaded via reflection for specific types/regions, for example, by state or product line. Power users could use a simple app to create an account configuration they needed (configurations were stored in a DB). If things changed, the underlying DLL could be modified or a new one added. I only had to add one new extension DLL during the 4 years I was on this project but there were typically one or two small mods needed a month to the rules. In a much earlier VB6 project I used a guided VBScript to provide power users with the ability to code certain rules. Although the users knew Excel scripting well and a wizard interface was written to help them do what they needed to do they usually just gave me the job of coding the rules. That plan sort of backfired so that's why I didn't use it again later but instead opted for a more "check this, select that" approach to rule building. A: Writing your own engine works if your rules are simple. The more complicated they get, the more time it will take to maintain it. You can use Drools Server to execute your rules and still do your main application with .NET or whatever language you like. You still need Java for the Drools Server part.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Adsense is firing blanks - Is there a test I can check against? I have been asked to drop in an adsense snippet for a clients site. the iFrame appears to be loading, but no content is visible. How can I test that everything is okay? The site is currently localhost only. A: Adsense sometimes just does this for a while when it is getting started. I'd give it a few hours and see if it starts working on its own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: handling URLs in django and Asp.Net i need to convert an api written in django to asp.net but the demand is , that urls are not changed.. means they request the same.. in django i can easily map urls to functions like this urls = ( '/heartbeat/check/', 'HeartbeatCheck', '/change/password/', 'changePassword', '/change/ccdetails/', 'changeCCDetails' ) but i wonder how can i do the same in asp.net website?? shud i need a separate page for each url?? or any possible way like in django.. thanx A: ASP.NET provides routing as well: http://msdn.microsoft.com/en-us/library/cc668201.aspx It works pretty similar to django's, actually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show Android preferences screen on app launch? I am very new to Android development. I want my Android app to launch the preference page the first time it is run. Any tips on how to do that ? Thanks. A: YOu will need to use sharedpreference to save boolean preference. This should work for you. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); boolean previouslyStarted = prefs.getBoolean("PREVIOUSLY_STARTED, false); if(!previouslyStarted){ SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(getString(R.string.pref_previously_started), Boolean.TRUE); edit.commit(); showPreference();//Here you launch your Preference Activity if it hasnt been launched before. } A: Store a hidden preference like 'has_launched_before' or something. On startup, check that preference, and if it is false, show the preferences screen instead of the main screen, and also set that preference to true so it doesn't happen on subsequent launches.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating seat plan with css I would like to create a seating plan by using css. As a box, I used this tutorial's css file http://net.tutsplus.com/tutorials/html-css-techniques/create-a-document-icon-with-css3/. Firstly, when I'm trying to add second box in a same row, it will skip a line, then I changed box's css with the following: .docIcon { background: #15cd2f; background: -webkit-linear-gradient(top, #caffb2 0, #15cd2f 15%, #caffb2 40%, #caffb2 70%, #15cd2f 100%); background: -moz-linear-gradient(top, #caffb2 0, #15cd2f 15%, #caffb2 40%, #caffb2 70%, #15cd2f 100%); background: -o-linear-gradient(top, #caffb2 0, #15cd2f 15%, #caffb2 40%, #caffb2 70%, #15cd2f 100%); background: -ms-linear-gradient(top, #caffb2 0, #15cd2f 15%, #caffb2 40%, #caffb2 70%, #15cd2f 100%); background: linear-gradient(top, #caffb2 0, #15cd2f 15%, #caffb2 40%, #caffb2 70%, #15cd2f 100%); border: 1px solid #ccc; display: block; width: 26px; height: 50px; float:left; text-align:center; } but then the problem is, I need row's to be centered instead of standing on left. How should I do that ? Thanks. A: .docIcon {display: inline-block;} Then wrap your boxes in a container that is centered and has text-align: center A: DA is right .... here see this http://jsfiddle.net/jzjVT/3/ if this is what you are trying to do..
{ "language": "en", "url": "https://stackoverflow.com/questions/7506186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ASP.NET MVC URL routing I have a question, can this be done using ASP.NET MVC (Razor, and MapRoute)? Example * *Category/ - calls controller Category and Index function *Category/{State_name} - calls controller Category and Cities(State_id) function, returns all cities inside that state. So URL is displaying state name , but Cities function receive state id? A: This should do it: routes.MapRoute("Category_byState", "Category/{State_id}", new { controller = "Category", action = "Cities" }); A: Yes u can, try public class CategoryController : Controller { // GET: /Category/ // OR // GET: /Category/State_name public ActionResult Index(string State_name) { if (!string.IsNullOrWhiteSpace(State_name)) { int? State_id = FindStateIdFromStateName(State_name); // retrive state_id from datastore where state_name == State_name if (State_id.HasValue) { // means the currect state_name passed to action var model = FindStateById(State_id.Value); return View("Cities", model); // will renders Cities.cshtml with specified model } else { // means the specified state_name not found! u can do something else, or allow continue bellow lines } } return View(); // will render normal Index.cshtml } } Let me know if you have any questions or need clarifications on any part. UPDATE I have one issue with the way! You get the ID from db with State_name, then get the model from db by State_name! Why not retrieve model from db by State_name at the first time? look: public class CategoryController : Controller { // GET: /Category/ // OR // GET: /Category/State_name public ActionResult Index(string State_name) { if (!string.IsNullOrWhiteSpace(State_name)) { var model = FindStateByName(State_name); if(model != null) return View("Cities", model); else // means the specified state_name not found! u can do something else, or allow continue bellow lines } return View(); // will render normal Index.cshtml } } and if you are on EF, then you can create this method: public State FindStateByName(state_name){ using(var context = new YourEntityContext()){ return context.States.SingleOrDefault(s => s.Name.ToLower() == state_name.ToLower()); } } Why not using this way?
{ "language": "en", "url": "https://stackoverflow.com/questions/7506190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding content-length to an API post request using Rails I'm trying to post some data to the Google Places api. However when I run the code (below) I receive a 411 Length Required error. Does anyone know how to resolve this using the code below. Thanks require 'rubygems' require 'httparty' class Partay include HTTParty base_uri 'https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=API_Key' end #add to google API options = { :location => { :lat => '33.71064', :lng => '-84.479605' } } { :accuracy => '50', :name=>"Rays NewShoeTree", :types=> "shoe_store", :language=> "en-AU" } puts Partay.post('/maps/api/place/add/json?sensor=false&key=API_Key', options) A: You need to specify a body in the post. Even just nil or an empty hash, then HTTParty will include the Content-Length header.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Netbeans AutoComplete Methods Zend Model Classes I have the following models classes however netbeans 7.0.1 autocomplete doesn't work for row classes. Model Class: class Application_Model_DbTable_Payments extends Zend_Db_Table_Abstract { protected $_name = 'payments'; protected $_rowClass = 'Application_Model_Payment'; } Row Class: class Application_Model_Payment extends Zend_Db_Table_Row_Abstract { public function setIdentifier($identifier = null){ return $this->identifier = $identifier; } } Code: $paymentsModel = new Application_Model_DbTable_Payments(); $payment = $paymentsModel->find(1)->current();// return an Application_Model_Payment Object $payment->setIdentifier();//doesn't appear on netbeans autocomplete, only Zend_Db_Table_Row methods appers How could I make netbeans show row class methods? A: Because netbeans uses heavily the docblock comments (and in this case find is an inherited method), unless you explicitly put the return type in the comment block for a method, Netbeans hasn't really got a clue what to do. You can give it a hand though by doing adding a block like this: /* @var $variable ClassName */ like so in your code $paymentsModel = new Application_Model_DbTable_Payments(); /* @var $payment Application_Model_Payment */ $payment = $paymentsModel->find(1)->current();// return an Application_Model_Payment Object $payment->setIdentifier(); It will 'hint' netbeans as to what the variable is. UPDATE: Here is an example of doing it from the class/method declaration. In this example $something is instantiation of Application_Model_Token. class User { /** * @return Application_Model_Token */ public function reset() { //Some code etc return $something } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7506194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I re enable a setInterval after I called clearInterval? Here's my javascript: <script type="text/javascript"> var timer; $(document).ready(function () { timer = setInterval(updatetimerdisplay, 1000); $('.countdown').change(function () { timer = setInterval(updatetimerdisplay, 1000); }); function updatetimerdisplay() { $(".auctiondiv .auctiondivleftcontainer .countdown").each(function () { var newValue = parseInt($(this).text(), 10) - 1; $(this).text(newValue); if (newValue >= 9) { $(this).css("color", ""); $(this).css("color", "#4682b4"); } if (newValue == 8) { $(this).css("color", ""); $(this).css("color", "#f3982e"); } if (newValue == 5) { $(this).css("color", ""); $(this).css("color", "Red"); } if (newValue <= 1) { //$(this).parent().fadeOut(); clearInterval(timer); } }); } }); var updateauctionstimer = setInterval(function () { $("#refreshauctionlink").click(); }, 2000); function updateauctions(response) { var data = $.parseJSON(response); $(data).each(function () { var divId = "#" + this.i; if ($(divId + " .auctiondivrightcontainer .latestbidder").text() != this.b) { $(divId + " .auctiondivrightcontainer .latestbidder").fadeOut().fadeIn(); $(divId + " .auctiondivrightcontainer .auctionprice .actualauctionprice").fadeOut().fadeIn(); $(divId + " .auctiondivleftcontainer .countdown").fadeOut().fadeIn(); } $(divId + " .auctiondivrightcontainer .latestbidder").html(this.b); $(divId + " .auctiondivrightcontainer .auctionprice .actualauctionprice").html(this.p); if ($(divId + " .auctiondivleftcontainer .countdown").text() < this.t) { $(divId + " .auctiondivleftcontainer .countdown").html(this.t); } }); } </script> Basically, I want to turn the timer back on, if any .countdown element has it's text change. The text will change because of an AJAX call I use to update that value. Currently the timer doesn't re enable and the countdown freezes after the value of .Countdown is changed. I think that the change() event fires when the text of an element changes. Is this correct? Any glaring mistakes on my part? A: You are trying to bind the change event before the elements exist. Put that code inside the ready event handler: $(document).ready(function () { timer = setInterval(updatetimerdisplay, 1000); $('.countdown').change(function () { timer = setInterval(updatetimerdisplay, 1000); }); }); You also might want set the timer variable to an identifiable value when the timer is off (e.g. null), so that you can check for that value before you start a timer to prevent from starting multiple timers. A: Your code contains a loop and condition: function updatetimerdisplay() { $(".auctiondiv .auctiondivleftcontainer .countdown").each(function () { ... if (newValue <= 1) { //$(this).parent().fadeOut(); clearInterval(timer); } ... } } It's very likely that one of these elements have a value which satisfy the condition newValue <= 1. In that case, the timer will stop. Even when you change the contents of an input field, the timer will immediately stop after that run. If you have to support multiple timers, use a wallet of timers (var timers = {};timers.time1=... or var timers = [];timers[0] = ...). If you have to support only a few timeouts, you can even use variables (var timer1=... ,timer2=..., timer3=...;).
{ "language": "en", "url": "https://stackoverflow.com/questions/7506202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Processing - Set X/Y Zero Coordinates To Center of Display Window I'm trying to use latitude and longitude coordinates to plot a map in Processing. Is there a way to set the zero coordinates of the X and Y axis to the center of the display window. Or does anyone know how to convert spherical coordinates to cartesian? Thanks A: I'll assume you have spherical coordinates of r, radius; theta, horizontal angle around Z-axis starting at (1,0,0) and rotating toward (0,1,0); and phi, vertical angle from positive Z-axis toward negative Z-axis; that being how I remember it from back when. Remember that angles are in radians in most programming languages; 2*pi radians = 180 degrees. x = r * cos(theta) * sin(phi) y = r * sin(theta) * sin(phi) z = r * cos(phi)
{ "language": "en", "url": "https://stackoverflow.com/questions/7506206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight 4 and parallel port Is there any class or library for the Silverlight 4 print directly to parallel port (LPT1)? A: Once you have an OOB Silverlight app with Elevated Trust that can access the local file system, you can make an attempt and dumping data to the parallel port with the file system apis. The name of the LPT device will be \\.\LPTx where x is the dos lpt port number that was mapped by windows. You can find this in the registry under HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\PARALLEL PORTS . On my machine it has the key \Device\Parallel2 maped to \DosDevices\LPT3 so on I would use the file name "\\.\LPT3" to access the prallel port as if it was a file. Just to be clear that is 2 slashes, a dot then another slash before the port name. A: Not unless your Silverlight app is a OOB with Elevated Trust and the client has installed on it some COM component that can manipulate the parallel port. So basically: No.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: Get image type from base64 string How do I get the image type from a base64 string? I read another post similar to this but it doesn't give the image type, jpeg, png, etc. Below is my current code. $type = finfo_buffer(finfo_open(), base64_decode($b64Img), FILEINFO_MIME_TYPE); print($type); //prints "application/octet-stream" A: This code should work, give it a try: $finfo = new finfo(FILEINFO_MIME); echo $finfo->buffer(base64_decode($b64Img)) . "\n"; A: Instead of FILEINFO_MIME you can also use FILEINFO_MIME_TYPE available since PHP 5.3.0. A: You will need to decode the base64 data and then read the magic of it: // read first 12 characters out of the base64 stream then decode // to 9 characters. (9 should be sufficient for a magic) $magic = base64_decode(substr($b64Img, 0, 12)); // determine file type if (substr($magic, 0, 1) == 0xff && substr($magic, 1, 1) == 0xd8) { // jpg } else if (substr($magic, 0, 1) == 0x89 && substr($magic, 1, 5) == "PNG\r\n" && substr($magic, 6, 1) == 0x1a && substr($magic, 7, 1) == "\r") { // png } ... A: Once you have the base64 text of your image, you just need to analyze the first section of it to determine the file type. All base64 strings begin with something like this: "data:image/(png|jpg|gif);base64,iVBORw0KG..." You just have to look at the part between the image/ and the ; and it will tell you the format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the difference between mixin() and extend() in Javascript libraries I'm looking through various libraries, and seeing extend() pop up a lot, but I'm also seeing mixin() show up. YUI has both mixins and extensions. What's the difference between these two concepts? When would I decide between a mixin and extending an object? Thanks, Matt A: The extend method is pretty common among JavaScript libraries and is generally a method that simply allows the consuming code to add all "own" properties and methods of one or more objects onto a target object. The code is usually pretty straightforward: iterate over all the own keys of each argument beyond the first and copy the value stored there to the first argument. "Mixin" refers to a design pattern in which you use one object as a sort of container for a particular set of properties and methods you want to share across many objects in your system. For example, you might have width and height getters and setters that could apply to all UI components in your application and so you would create, in the case of JavaScript, either a function that can be instantiated with "new" or an object literal that holds these methods. You could then use an "extend" type function to copy these methods onto any number of objects in your system. Underscore has a mixin method that is essentially just an extend where all of the passed in objects' methods are added to the base underscore object for use in chaining. jQuery does a similar thing with its extend method of jQuery.fn. Personally I like to keep extend as is, a "copy everything from these objects to this object" type behavior while having a separate mixin method that instead accepts only a single source object and then treats all further arguments as names of properties and methods to copy (if only the target and source are passed in with no further arguments then it just acts like a single-source extend). e.g. function mixin(target, source) { function copyProperty(key) { target[key] = source[key]; } if (arguments.length > 2) { // If there are arguments beyond target and source then treat them as // keys of the specific properties/methods that should be copied over. Array.prototype.slice.call(arguments, 2).forEach(copyProperty); } else { // Otherwise copy all properties/methods from the source to the target. Object.keys(source).forEach(copyProperty); } } A: You can definitely create mixins by using extends. Mixins give all the benefits of multiple inheritance, without hierarchy (prototypal inheritance in JavaScript). They both allow you to reuse an interface (or set of functions) on multiple objects. With mixins don't encounter the "diamond problem" that you can run into with parent-child relationships. The diamond problem occurs when a one object inherits the same function (or even function name) from two objects. Why? If one of those two objects modified the function, adding functionality (ie. in Java called "super"), JavaScript doesn't know how to interpret/combine the two methods anymore. Mixins are a way of avoiding this heirarchy. They define functionality that you can stick anywhere. Mixins also typically don't contain data of their own. So I could, for instance, write a mixin with $.extend() in jQuery. var newmixin = $.extend({}, mixin1, mixin2) would combine two interfaces, and flatten them (overwrite name conflicts). Here are 3 things to consider: * *Does the combination of the two interfaces have "hierarchy" ie. parent/child relationship. In JavaScript this would mean prototypal inheritance. *Are the functions copied, or referenced? If the original method changes, will the inherited methods change as well? *What happens when two methods of the same name are combined? And how are these conflicts dealt with? A: Mixins don't work with instanceof but extends do. Mixins allow multiple inheritance but by faking it, not by properly chaining the prototypes. I'll show an Ext-JS example but the concept applies to any class library that provides mixins, they all just copy properties to the object instead of chaining the prototype. Ext.define('Ext.Window', { extend: 'Ext.Panel', requires: 'Ext.Tool', mixins: { draggable: 'Ext.util.Draggable' } }); Ext.Window instanceof Ext.Panel //true Ext.Window instanceof Ext.util.Draggable // false Mixins are a great way to add some functionality to an object without resorting to inheritance. If you have to inherit something to get some functionality, then you can't use functionality from two classes. Many people believe it's evil. Ext-JS experienced that problem when they wanted to add Labelable functionality to FieldSet and others that were not input like fields. There was no way that it could benefit from the Labelable behavior inside Field since they couldn't extend Field since it had all the input behavior in it too. A: Edit for clarity: These are sometimes the same thing and sometimes not; mixin is a name of a pattern used for reusing functions between multiple objects, and extend is more the algorithm / method used to do so. There are cases where they are identical (for example underscores _.extend) and cases where they differ (backbone.js 's extend). In the case where they differ extend would generally link the prototype to the object being extended, whereas mixin would copy a list of methods onto the target.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Java reusing (static?) objects as temporary objects for performance I need to call methods of a class with multiple methods very often in a simulation loop. Some of these methods need to access temporary objects for storing information in them. After leaving the method the stored data is not needed anymore. For example: Class class { method1() { ... SomeObject temp = new SomeObject(); ... } method2() { ... SomeObject temp = new SomeObject(); SomeObject temp2 = new SomeObject(); ... } } I need to optimize as much as possible. The most expensive (removable) problem is that too many allocations happen. I assume it would be better not to allocate the space needed for those objects every time so I want to keep them. Would it be more efficient to store them in a static way or not? Like: Class class { private (static?) SomeObject temp; private (static?) SomeObject temp2; methods... } Or is there even a better way? Thank you for your help! Edit based on answers: Not the memory footprint is the actual problem but the garbage collection cleaning up the mess. SomeObject is a Point2D-like class, nothing memory expensive (in my opinion). I am not sure whether it is better to use (eventually static) class level objects as placeholder or some more advanced method which I am not aware of. A: Keep in mind that temp and temp2 are not themselves objects, but variables pointing to an object of type SomeObject. The way you are planning to do it, the only difference would be that temp and temp2 would be instance variables instead of local variables. Calling temp = new SomeObject(); Would still allocate a new SomeObject onto the heap. Additionally, making them static or instance variables instead of local would cause the last assigned SomeObjects to be kept strongly reachable (as long as your class instance is in scope for instance variables), preventing them from being garbage collected until the variables are reassigned. Optimizing in this way probably isn't effective. Currently, once temp and temp2 are out of scope, the SomeObjects they point to will be eligible for garbage collection. If you're still interested in memory optimization, you will need to show what the SomeObject is in order to get advice as to how you could cache the information it's holding. A: I would be wary in this example of pre-mature optimization. There are downsides, typically, that it makes the code more complex (and complexity makes bugs more likely), harder to read, could introduce bugs, may not offer the speedup you expected, etc. For a simple object such as representing a 2D point coordinate, I wouldn't worry about re-use. Typically re-use gains the most benefit if you are either working with a large amount of memory, avoid lengthy expensive constructors, or are pulling object construction out of a tight loop that is frequently executed. Some different strategies you could try: Push responsiblity to caller One way would be to to have the caller pass in an object pre-initialized, making the method parameter final. However, whether this will work depends on what you need to do with the object. Pointer to temporary object as method parameter Another way would be to have the caller pass as an object as a parameter that's purpose is essentially to be a pointer to an object where the method should do its temporary storage. I think this technique is more commonly used in C++, but works similarly, though sometimes shows up in places like graphics programming. Object Pool One common way to reuse temporary objects is to use an object pool where objects are allocated from a fixed bank of "available" objects. This has some overhead, but if the objects are large, and frequently used for only short periods of time, such that memory fragmentation might be a concern, the overhead may be enough less to be worth considering. Member Variable If you are not concerned about concurrent calls to the method (or have used synchronization to prevent such), you could emulate the C++ism of a "local static" variable, by creating a member variable of the class for your storage. It makes the code less readable and slightly more room to introduce accidental interference with other parts of your code using the variable, but lower overhead than an object pool, and does not require changes to your method signature. If you do this, you may optionally also wish to use the transient keyword on the variable as well to indicate the variable does not need to be serialized. I would shy away from a static variable for the temporary unless the method is also static, because this may have a memory overhead for the entire time your program runs that is undesirable, and the same downsides as a member variable for this purpose x2 (multiple instances of the same class) A: How large are these objects. It seems to me that you could have class level objects (not necessarily static. I'll come back to that). For SomeObject, you could have a method that purges its contents. When you are done using it in one place, call the method to purge its contents. As far as static, will multiple callers use this class and have different values? If so, don't use static. A: First, you need to make sure that you are really have this problem. The benefit of a Garbage Collector is that it takes care of all temporary objects automatically. Anyways, suppose you run a single threaded application and you use at most MAX_OBJECTS at any giving time. One solution could be like this: public class ObjectPool { private final int MAX_OBJECTS = 5; private final Object [] pool = new Object [MAX_OBJECTS]; private int position = 0; public Object getObject() { // advance to the next object position = (position + 1) % MAX_OBJECTS; // check and create new object if needed if(pool[position] == null) { pool[position] = new Object(); } // return next object return pool[position]; } // make it a singleton private ObjectPool() {} private static final ObjectPool instance = new ObjectPool(); public static ObjectPool getInstance() { return instance;} } And here is the usage example: public class ObjectPoolTest { public static void main(String[] args) { for(int n = 0; n < 6; n++) { Object o = ObjectPool.getInstance().getObject(); System.out.println(o.hashCode()); } } } Here is the output: 0) 1660364311 1) 1340465859 2) 2106235183 3) 374283533 4) 603737068 5) 1660364311 You can notice that the first and the last numbers are the same - the MAX_OBJECTS + 1 iterations returns the same temporary object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP variable additions Hey does anyone know a reason why this is not working? its not calculating any of the additions and just entering 0 into the database. Any help would be great, thank you!. $member_id = //users member id in database// $track = //the track results being updated// $engine = //the engine id from the members table in database// $engine_points_system = array(); $engine_points_system["qualpos1"] = 30; $engine_points_system["qualpos2"] = 20; $engine_points_system["qualpos3"] = 18; $engine_points_system["qualpos4"] = 17; $engine_points_system["qualpos5"] = 16; $enginepoints = 0; $qualifyingpoints = 0; $results_query = mysql_query("SELECT pos_1, pos_2, pos_3, pos_4, pos_5 from engine_qualifying_results WHERE track_id = '$track'") or die ("Failed to update" . mysql_error()); $row = mysql_fetch_array($results_query); $enginequalifying = array(); for ($i = 1; $i <= 5; $i++) { $enginequalifying["pos$i"] = $row['pos_$i']; } for($i = 1; $i <=5; $i++) { if($engine == $enginequalifying["pos$i"]){ $enginepoints += $engine_points_system["qualpos$i"]; $qualifyingpoints += $engine_points_system["qualpos$i"]; } } $results_query = mysql_query("INSERT INTO member_results (member_id, engine_points) VALUES ('$member_id', $enginepoints')") or die ("Failed to update" . mysql_error()); A: $enginequalifying["pos$i"] = $row['pos_$i']; In this line you have 'pos_$i'. This is the literal string 'pos_$i'. You should use "pos_$i" instead. $enginequalifying["pos$i"] = $row["pos_$i"]; UPDATE: In your code $enginequalifying is redundant, and not needed. You can just use $row in its place. for($i = 1; $i <=5; $i++){ if($engine == $row["pos_$i"]){ $enginepoints += $engine_points_system["qualpos$i"]; $qualifyingpoints += $engine_points_system["qualpos$i"]; } } Also, as @ax. points out, you have an extra ' (or a missing ') in your INSERT. $results_query = mysql_query("INSERT INTO member_results (member_id, engine_points) VALUES ('$member_id', '$enginepoints')") or die ("Failed to update" . mysql_error()); A: Look at this code: <?php $i = 5; print "i is $i"; print "\n"; print 'i is $i'; ?> You'd expect it to print: i is 5 i is 5 But instead, it will print: i is 5 i is $i This happens because when the string is wrapped in single quotes, $i is not evaluated. It is just the string $i. To fix the code, try replacing this line: $enginequalifying["pos$i"] = $row['pos_$i']; With this line: $enginequalifying["pos$i"] = $row["pos_$i"]; Quotes make a difference. And by the way, ESCAPE YOUR SQL!!!. Please? A: Not an answer, but too ugly to put into a comment: You could bypass the entire loop to build the enginequalifying array by simply doing: SELECT pos_1 AS pos1, pos_2 AS pos2, etc... for your query, then simply having: $enginequalifying = mysql_fetch_assoc($result); It's a waste of CPU cycles to have PHP fetch/rename database fields for you when a simple as alias in the original query string can accomplish the exact same thing. And incidentally, this will also remove the string-quoting error you've got that Rocket pointed out in his answer. A: I dont think it is possible to say without knowing what you have in your database. But I can tell you that you have a syntax error in the last SQL query ($enginepoints ends with a quote).
{ "language": "en", "url": "https://stackoverflow.com/questions/7506220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing url from JavaScript code and adding another value I have following mysql query: $colname_profile = "-1"; if (isset($_GET['user'])) { $colname_profile = $_GET['user']; } mysql_select_db($database_conn, $conn); $query_profile = sprintf("SELECT * FROM users WHERE user_id = %s", GetSQLValueString($colname_profile, "int")); $profile = mysql_query($query_profile, $conn) or die(mysql_error()); $row_profile = mysql_fetch_assoc($profile); $totalRows_profile = mysql_num_rows($profile); and following JS part of code I need to change: url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"), now, how do I add another value inside JS code from above query which should be in format of user='.$row_profile['user_id'].' so I need to keep whats already inside that JS url and at the end add that user ID. In case you need complete JS here it is <script type="text/javascript"> $(document).ready(function(){ $("#loadmorebutton").click(function (){ $('#loadmorebutton').html('<img src="../images/body/icons/ajax-loader.gif" />'); $.ajax({ url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id"), success: function(html){ if(html){ $("#historywrapper").append(html); $('#loadmorebutton').html('Load More'); }else{ $('#loadmorebutton').replaceWith('<center>No more posts to show.</center>'); } } }); }); }); </script> Thanks for help. A: maybe change url line to something like this: url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "&user=<?php echo urlencode($row_profile['user_id']); ?>", A: Given the way the question is asked, this will work: url: "loadmore.php?lastid=" + $(".profile_history_results:last").attr("uh_id") + "user=<?php echo $row_profile['user_id']; ?>", However I don't know if that is what you are looking for. Is $row_profile['user_id'] only a single value on a page or is this like a list of users and for each row in the table is there a different $row_profile['user_id'] that might exist? If this is a single value, for example the user_id of the user visiting the page and you want to pass that along with every ajax request, you might be better off storing that value is sessions elsewhere as it is unlikely to change unless the user logs out and back in under another account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QNetworkRequest with ssl local certificate I need to exchange data with server which requires local certificate (.crt file). I try this: loginRequest = QNetworkRequest(QUrl("https://somesite.com/login")); QSslConfiguration sslConf = loginRequest.sslConfiguration(); QList<QSslCertificate> certs = QSslCertificate::fromPath(Preferences::certificatePath()); qDebug() << certs.first().issuerInfo(QSslCertificate::Organization); // prints name sslConf.setLocalCertificate(certs.first()); qDebug() << "is valid " << sslConf.localCertificate().isValid(); // true qDebug() << "is null " << sslConf.localCertificate().isNull(); // false qDebug() << "protocol " << sslConf.protocol(); // 0 sslConf.setProtocol(QSsl::SslV3); // i also tried Qssl::AnyProtocol qDebug() << "protocol " << sslConf.protocol(); // 0 // if i uncomment these i expect everithing to work //QSslConfiguration::setDefaultConfiguration(sslConf); //QSslSocket::addDefaultCaCertificate(certs.first()); //loginRequest.setSslConfiguration(sslConf); QObject::connect(connectionManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(printSslErrors2(QNetworkReply*,QList<QSslError>))); m_reply = connectionManager->get(loginRequest); QObject::connect(m_reply, SIGNAL(readyRead()), this, SLOT(getCookie())); QObject::connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(printSslErrors(QList<QSslError>))); When this code executes i have the following messages in WireShark (filter: tcp && ssl && ip.addr == my_addr): Client Hello ServerHello, Certificate Server Key Exchange, Certificate request, Server Hello Done Alert (level: Warning, Description: no certificate), client key exchange, change cipher spec, encrypted handshake message Alert (level: Fatal, Description: Handshake failure) This is expected - the code to apply certificate is commented out, but the strange thing - I do not get any ssl errors from my QNetworkAccessManager and QNetworkReply (slots printSslErrors and printSslErrors2). If i uncomment any of these 3 lines: //QSslConfiguration::setDefaultConfiguration(sslConf); //QSslSocket::addDefaultCaCertificate(certs.first()); //loginRequest.setSslConfiguration(sslConf); I get NOTHING in wireshark (few SYN, ACK and FIN tcp messages, but no http or ssl traffic). Also there are still no errors from QNetworkAccessManager and QNetworkReply, so I have no idia what is going wrong. Is there any chance to make Qt accept my local certificate or may be there is some 3d party qt-oriented lib to help me out? P.S.: btw - ssl and https worked just fine a few days ago, before the server was changed to require client-side certificates. P.P.S.: certificate is self signed if it makes any difference. Also I tried to 'install' it (the p12 file) into system and both Chrome and IE7 are able to use it and communicate with server. A: Complete shot in the dark and goes on the assumption that Qt may in fact be reporting an error but you're not getting the signal. You're connecting signals from your connectionManager to this have you included the Q_OBJECT macro in the header for this? Also examine the output when you run your application as Qt may report issues connecting the signals/slots if that is indeed the case here. A: SOLUTION, Part I: I mostly solved this (the lack of connection), there were 2 reason: 1st - the apache server actually require private key (for some unknown reason, found it [here][1]), how to add private key: QFile x(Preferences::certificateKeyPath()); x.open(QIODevice::ReadOnly); pKey = QSslKey(x.readAll(),QSsl::Rsa); QSslError error1(QSslError::SelfSignedCertificate, certs.first()); QSslError error2(QSslError::CertificateUntrusted, certs.first()); QList<QSslError> expectedSslErrors; expectedSslErrors.append(error1); expectedSslErrors.append(error2); 2d - the certificate I had was not very 'good'. I dont know what it really means or why it was not working, but when I got new certificate from server admin and added private key the handshake succeeded. I still dont know how to catch sslErrors (for example to show user that his certificate is not working), but it is a good start SOLUTION, Part II: Solved the last part of the question (kina a woraround). It seems QNetworkReply not emitting SslErrors is a bug (or at least it does not work all the time or for all web-sites), found it [in Qt bug tracker][2]. And the workaround also from there: sinse we cant get SslErrors, we have to try and get smth else - [error][3], for example. It does not give detailed information about what have actually happend, but better than nothing. For me error code 6 - "the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted." is perfect (i dont care for anything else): QObject::connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleSslErrors(QNetworkReply::NetworkError))); The important part: if the user has wrong certificate and/or key - the signal is emited. But it is also emited if certificate and key are correct. It seems auth might still be not perfect, but you can easily shut it down with QObject::connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(printSslErrors(QList<QSslError>))); Conclusion it seems they have fixed a lot of SSL bugs in Qt 4.8, so I hope release will be soon
{ "language": "en", "url": "https://stackoverflow.com/questions/7506223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: (Titanium mobile, Android) activeTab.open() new window is not preserving tabs I am new and I saw similar questions but quite old and without solution. All I want is to open new window inside activeTab and preserve the tab group. Unfortunately my code opens new window but does not keep the tabs, the window is just full screen. I would greatly appreciate if someone could confirm if what I want to achieve is possible at all. Maybe with views somehow... Once again it should work for android. Here is the code: // this sets the background color of the master UIView (when there are no windows/tab groups on it) Titanium.UI.setBackgroundColor('#000'); // create tab group var tabGroup = Titanium.UI.createTabGroup(); // // create base UI tab and root window // var win1 = Titanium.UI.createWindow({ title:'Tab 1', backgroundColor:'#fff' }); var tab1 = Titanium.UI.createTab({ icon:'KS_nav_views.png', title:'Tab 1', window:win1 }); // // create controls tab and root window // var win2 = Titanium.UI.createWindow({ title:'Tab 2', backgroundColor:'#fff' }); var tab2 = Titanium.UI.createTab({ icon:'KS_nav_ui.png', title:'Tab 2', window:win2 }); var label2 = Titanium.UI.createLabel({ color:'#999', text:'I am Window 2', font:{fontSize:20,fontFamily:'Helvetica Neue'}, textAlign:'center', width:'auto' }); win2.add(label2); var data = [ {title:"Sample 1",color:'black',hasChild:true,font:{fontSize:16,fontWeight:'bold'}}, {title:"Sample 2",color:'black',hasChild:true,font:{fontSize:16,fontWeight:'bold'}} ]; var table = Titanium.UI.createTableView({ data:data, separatorColor: '#ccc', backgroundColor:'#fff' }); win1.add(table); // create table view event listener table.addEventListener('click', function(e) { var win = Titanium.UI.createWindow({ url:'windows/main.js' }); // this simply opens the new created window but full screen and without original tab group. tabGroup.activeTab.open(win,{animated:true}); }); // // add tabs // tabGroup.addTab(tab1); tabGroup.addTab(tab2); // open tab group tabGroup.open(); A: You have to create navigation group for each tab windows. For example //Here's the first window... var first = Ti.UI.createWindow({ backgroundColor:"#fff", title:"My App" }); Next, we’ll create a NavigationGroup. This is an iPhone-only component that controls a stack of windows (reference doc) – we’ll pass it our first window to use as its initially viewable window: //Here's the nav group that will hold them both... var firstnavGroup = Ti.UI.iPhone.createNavigationGroup({ window:first }); //This is the main window of the application var mainfirst = Ti.UI.createWindow(); mainfirst.add(firstnavGroup); then assing this mainfirst window to tab. Repeat this prosess for all tabs Now when you need to open new window then you have to write var second = Ti.UI.createWindow({ background:"#fff", title:"Child Window" }); firstnavGroup.open(second); I hope this will help you. A: There is currently no way to do that on android: http://developer.appcelerator.com/question/145471/application-with-strange-navigation-how-to-implement-it#answer-252500 here you can find a demo of my solution... http://sharesend.com/kbkasavo hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7506227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I Include Crystal Reports Assembly (crystaldecisions.reportappserver.commonobjectmodel Ver 13.0.2000.0) into Windows Installer? I have built a project using VS 2010 and I have 2 reports I am creating within the project. While in VS2010, I can debug the program and the reports work perfectly. Now I have come to the point where I want to publish my project and install it on a machine that my program will be used on. I tried 'Publishing' my project and running the 'Setup' file on the other computer and I get the following error: Unable to install or run the application. The application requires that assembly CrystalDecisions.ReportAppServer.CommonObjectModel Version 13.0.2000.0 be installed in the Global Assembly Cache (GAC) first. Please Contact your System Administrator. Doing some research, I have found out that you can manually change the GAC or have Windows Installer fix it for you. To be honest, I don't know where the GAC is or how to modify it. My ideal solution would be to figure out how to setup Windows Installer to fix the GAC and configure Crystal reports however to get my project to run on a basic machine. Can someone help me setup Windows Installer to install the appropriate Crystal Reports Engine so my project will work?? I am new to Windows Installer, so overkill on details won't bother me a bit!! Thanks so much in advance!! A: You can try adding a Crystal Reports runtime installer as a prerequisite to your main package. You need the one with version 13.0.2000.0. You can read more about prerequisites here: * *http://msdn.microsoft.com/en-us/library/77z6b8tz(VS.80).aspx?ppud=4 *http://msdn.microsoft.com/en-us/library/ms165429(VS.80).aspx *http://msdn.microsoft.com/en-us/library/ms165429.aspx A: You could also try setting CopyLocal=True for the crystal references.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Set position / size of UI element as percentage of screen size I'm trying to work out if it's possible to use percentage positions/sizes when creating a layout. What I want is something like this... ^ | | | 68% | | v Gallery (height equivalent of 16% total screen size) ^ | 16% v I'm testing on a device which in landscape has a display of 800x480 actual pixels and I'm currently forcing it with the following... <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="80px" android:layout_marginTop ="320px" /> </RelativeLayout> Obviously I don't want to hard-code fixed px units but I can't use 68% or 0.68 for layout_marginTop (for example). I've looked at dp units but I'm not sure if I can do it that way either. I have to admit UI design is a weak point of mine so any advice would be gratefully received. EDIT: For future reference if anyone is looking for a similar answer, following Alan Moore's suggestion I have the following working exactly how I want it... <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@drawable/bground" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="0.68" android:background="@android:color/transparent" /> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.16" /> <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="0.16" android:background="@android:color/transparent" /> </LinearLayout> I managed to find some other examples of using layout_weight and decided to set the TextView heights to 0dp and also used floats for the weights. Working great. :) A: The above problem can also be solved using ConstraintLayout through Guidelines. Below is the snippet. <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.constraint.Guideline android:id="@+id/upperGuideLine" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.68" /> <Gallery android:id="@+id/gallery" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/upperGuideLine" /> <android.support.constraint.Guideline android:id="@+id/lowerGuideLine" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.84" /> </android.support.constraint.ConstraintLayout> A: I think what you want is to set the android:layout_weight, http://developer.android.com/resources/tutorials/views/hello-linearlayout.html something like this (I'm just putting text views above and below as placeholders): <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1"> <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="68"/> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="16" /> <TextView android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="16"/> </LinearLayout> A: Use the PercentRelativeLayout or PercentFrameLayout from the Percent Supoort Library <android.support.percent.PercentFrameLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" app:layout_heightPercent="68%"/> <Gallery android:id="@+id/gallery" android:layout_width="match_parent" app:layout_heightPercent="16%"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_width="match_parent"/> </android.support.percent.PercentFrameLayout> A: For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it: Button btn = new Button (this); android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); btn.setHeight((int)(display.getHeight()*0.68)); A: Take a look at this: http://developer.android.com/reference/android/util/DisplayMetrics.html You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7506230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "78" }
Q: What date format is this? I am trying to query some data out of Home Bank using the data file it produces. This is a transaction that appears in the file: <ope date="734309" amount="-14.24" account="4" dst_account="0" paymode="0" flags="1" payee="239" category="2" wording="" info="" tags="" kxfer="0" /> I am interested in the date="734309". I've not seen this format before so don't know how to parse it. The application is written in C if that is any help. A: 734309 / 365 = 2011.80548 So I guess it's something like "days since 1 January in the year 1". If you know the actual date that that number should represent, you can reconstruct the precise offset from there. A: It's probably the result of the SQL TO_DAYS() function, which represents the number of days since the first day of 1 A.D. (I don't know whether TO_DAYS() is specific to MySQL or if it's a standard SQL function.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7506232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }