text
stringlengths
8
267k
meta
dict
Q: Java: Rectangle2D and negative dimensions I have a script in which the user clicks once to begin a Rectangle2D. When he moves the mouse, the rectangle is updated with the new coordinates. He clicks again to end it. It's then stored in an ArrayList, and all these items are painted. This all works fine; it's not the problem. However, if the second click is less than the first (i.e. getWidth() is negative), the rectangle doesn't show up (as stated in the documentation). My script to fix this doesn't work. It's supposed to detect negative values, and then 1) decrement the position value and 2) make the negatives positive. Instead, it just moves the entire rectangle up or left (depending on which axis is negative) and keeps it at 1px. What's wrong? private void resizeRectangle(final MouseEvent e) { double x = rectangle.getX(), y = rectangle.getY(), w = e.getX() - x, h = e.getY() - y; if (w < 0) { x = e.getX(); w = -w; } if (h < 0) { y = e.getY(); h = -h; } rectangle.setRect(x, y, w, h); } Thanks! UPDATE: This is closer, but still doesn't quite work: double x = rectangle.getX(); double y = rectangle.getY(); double w = e.getX() - x; double h = e.getY() - y; if (w < 0) { x = e.getX(); w = originalClickPoint.getX() - e.getX(); } if (h < 0) { y = e.getY(); h = originalClickPoint.getY() - e.getY(); } rectangle.setRect(x, y, w, h); A: Once you assign the new rectangle you also shift the origin (i.e.where the mouse button was pressed down initially) to the current point. You'll have to save this point in a separate field (not in the rectangle itself). x = Math.min(e.getX(), originalClickPoint.getX()); w = Math.abs(originalClickPoint.getX() - e.getX()); y = Math.min(e.getY(), originalClickPoint.getY()); h = Math.abs(originalClickPoint.getY() - e.getY()); Another way is to not correct the negative widths/heights of the rectangle but create a new (corrected) one when you draw it. A: Take a look at the Custom Painting Approaches. The source code for the DrawOnComponent example shows how I did this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Limit number of rows of listview I am developing an application that needs to pair with other devices through Bluetooth. I was having trouble in order to show the list of paired devices in correct manner. I had also viewed the example in the android api (Bluetooth Chat), but i was having the same problem. The list of paired devices are to big and then hides a search button that are at the bottom of the list. My xml code is very the same of the example: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/listpaired_devices" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/title_paired_devices" android:visibility="gone" android:background="#666" android:textColor="#fff" android:paddingLeft="5dp" /> <ListView android:id="@+id/paired_devices" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stackFromBottom="true" android:layout_weight="1" /> <TextView android:id="@+id/list_new_devices" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/title_other_devices" android:visibility="gone" /> <ListView android:id="@+id/new_devices" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stackFromBottom="true" android:layout_weight="2" /> <Button android:id="@+id/btscan" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/btscan" /> </LinearLayout> But and i can't show the search button at the bottom. Here my screen: My Screen You could see a bit of the button at the bottom of the dialog window. It's possible to limit the number of rows shown at the listview ? Can anyone tell me how i can fix this problem A: Firstly some points about your code: * *layout_weight is only meaningful if an object has no size in a certain dimension, that is you set layout_height or layout_width to 0, so this has no effect on your code. *Setting the height of a ListView to wrap_content is pretty meaningless, and even if it works it's bad practice. Use either 'fill_parent' or a definite height. *The button is hidden because, as per the point above, the ListViews you have created have no predefined size so take up as much space as they can, pushing the button off the screen. So let's think about what you really have there - it's just a single list with a button at the bottom (yes you may have headers or multiple sources of data in there but we'll get onto that). The following layout will give you a ListView at the top and a Button at the bottom. The ListView will take up any space not being used by the Button. Notice how the Button is defined before the ListView in the layout - this causes Android to calculate how much height the button takes up before considering the ListView. It then gives the ListView the rest of the height available. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btscan" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="@string/btscan" /> <ListView android:id="@+id/all_devices" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/btscan" android:stackFromBottom="true" /> </RelativeLayout> So that's the layout. Now lets consider the actual content of your list: you have a header, followed by a list of paired devices, followed by another header and then a list of new devices. You can create this using a single Adapter - Commonsware provides a very good implementation called MergeAdapter but you could code your own. MergeAdapter doesn't directly let you a view (e.g. for the headers) but thankfully Commonsware also provides the SackOfViewsAdapter which allows you to add views to it, and then you can add the SackOfViewsAdapter to the MergeAdapter. Here is some pseudo-code which should accomplish what is outlined above. // This is the adapter we will use for our list with ListView.setAdapter MergeAdapter listAdapter = new MergeAdapter(); // The first header - you'll need to inflate the actual View (myHeaderView1) from some resource // using LayoutInflater List<View> firstHeaderViews = new List<View(); firstHeaderViews.add(myHeaderView1); SackOfViewsAdapter firstHeaderAdapter = new SackOfViewsAdapter(firstHeaderViews) // Second header List<View> secondHeaderViews = new List<View(); secondHeaderViews.add(myHeaderView2); SackOfViewsAdapter secondHeaderAdapter = new SackOfViewsAdapter(secondHeaderViews); // Now to add everything to the MergeAdapter // First goes the first header listAdapter.addAdapter(firstHeaderAdapter); // Now your first list listAdapter.addAdapter(firstListAdapter); // Now your second header listAdapter.addAdapter(secondHeaderAdapter); // Now your second list listAdapter.addAdapter(secondListAdapter); // Now set the adapter to the list myList.setAdapter(listAdapter) The layout produced should look something like this. Note I extended the list to show how it behaves with a list longer than the screen; the button still remains visible. The red box marks the bounds of the screen. A: You can limit the number of rows shown at the list view, but not sure if that will really help you in what you want to achieve, because you're hiding information from the user that might be important to him. You can limit the number of rows by limiting the number of items you pass to the listview adapter, or you can set the visibility to 'gone' in the getView method when the list view reaches a certain position (you can check the 'position' parameter of getView()). However, I would suggest you use only one list view (add a separator for the 'new/other devices' title into the view for a list item, but hide it by default, and then, as already suggested by suri, use headers and footers for the listview (to place the scan button).
{ "language": "en", "url": "https://stackoverflow.com/questions/7540350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Find word with maximum number of occurrences What is the most optimal way (algorithm) to search for the word that has the maximum number of occurrences in a document? A: * *Scan the document once, keeping a count of how many times you have seen every unique word (perhaps using a hashtable or a tree to do this). *While performing step 1, keep track of the word that has the highest count of all words seen so far. A: Finding the word that occures most times in a document can be done in O(n) by a simple histogram [hash based]: histogram <- new map<String,int> for each word in document: if word in histogram: histogram[word] <- histogram[word] + 1 else: histogram[word] <- 1 max <- 0 maxWord<- "" for each word in histogram: if histogram[word] > max: max <- histogram[word] maxWord <- word return maxWord This is O(n) solution, and since the problem is clearly Omega(n) problem, it is optimal in terms of big O notation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use AdWhirl with an unsupported ad company? Does anyone know how AdWhirl works? I set up my custom event for Greystripe in which I initialize the SDK if it wasn't already initialized, and refresh the BannerView, but I don't see the custom event getting called. So my main question is, how and when does AdWhirl call the custom event? What are the rations and rollovers? I haven't done anything with them (mainly because I don't know why I need them. What does AdWhirl do with them?) Also, how do I control when AdWhirl refreshes my banner? I'd like to tie the refresh with a button action. I've been searching online nonstop for the past two days and read a lot of tutorials and example Java classes that people have shared, but none of them have worked. It just looks like AdWhirl is stagnate. It's so unclear to me how AdWhirl works beyond: it mediates between the app and all the ad opportunities you want to use in your ad. That's an entirely too high-level understanding for me to move forward. :( A: Have you read the wiki page that describes how to use Custom Events? You basically create a custom event in the backend UI which behaves like another ad network, and you can configure it's traffic. Then you can implement the function name that you named in the backend. The only unintuitive part is that you have to implement AdWhirlInterface to listen for the custom event, which means creating an adWhirlGeneric() method. This method can be empty though, I am not seeing it called when creating my own test event. Finally, make sure to set the AdWhirlInterface. So assuming on the backend you created a network with: Name: Test Network Function Name: testEvent and gave it traffic (I recommend giving it 100% traffic when testing), then your code would look something like this: public class MyActivity extends Activity { ... public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ... } ... public void testEvent() { // Place event code here. Log.d("Cust_Network", "Cust network got called!"); } } To control refreshing your ad, call rotateThreadedNow() on the AdWhirlLayout when a button is clicked, for example. This will take AdWhirl through the process of randomly determining a new ad network, and calling the correct adapter, or custom event in this case. If you choose to go this route, you may not want automatic refreshing, in which case you should disable automatic refreshing on the back end. The ration object is populated with data from the configuration data. Each ration represents an ad network, and has keys which represent the individual ad network ids, weight percentages that you set in the backend, and backfill priority. Backfill priority is the network order that AdWhirl will request from if the original request did not fill. This process of going through backfill priority is called rollover. You will need to know a little bit about rollover when implementing your own custom event. The wiki page mentioned has these recommendations to add to your custom event: // In your custom event code, you'll want to call some of the below methods. // // On success: // this.adWhirlLayout.adWhirlManager.resetRollover(); // this.adWhirlLayout.rotateThreadedDelayed(); // // On failure: // this.adWhirlLayout.rolloverThreaded(); If your custom event properly fetches an ad, you will want to reset the rollover order (so the next request will have the correct backfill order), and call rotateThreadedDelayed() so that a refresh will happen automatically in the amount of time you specified on the back end. If the ad request failed, you will want to call rolloverThreaded() so that AdWhirl can go through it's rollover process to check your other configured ad networks for ads. A: if you want you can use an open source library i've developed that allows to use AdWhirl with other (unsupported) ad networks (but also with the officially supported ones). This library is also extensible, so you can add a new network to it and manage easily through AdWhirl. The library is AdMAL (Ad Mediation Abstraction Layer) and is available on a github.com repository under the Apache 2.0 open source license: https://github.com/marcosiino/AdMAL Using AdMAL you can easily implement AdWhirl in your applications for both supported and unsupported network (the integration is easiest than implementing AdWhirl SDK). Actually it only supports iOS (it's developed in Objective-C), but i plan to port to android in the next months. I started AdMAL for my own purposes, then decided to release it to the public under an open source license some days ago. Hope this help! I encourage other developers to improve the library and implement new networks support, so that this can benefit to everyone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 3NF Normal form I have a question about 3NF normal form: Normalize, with respect to 3NF, the relational scheme E(A, B, C, D, E, F) by assuming that (A, B, C) is the unique candidate key and that the following additional functional dependencies hold: A,B -> D C,D -> E E -> F My understanding is that if I apply the 3NF which says that a schema is 3NF if all attributes non-prime do not transitively depend on any key candidate , the result should be: E'=(A,B,C,E,F), E''= (B,D) , E'''= A,B,C,D,F) , E''''=(D,E) , E''''''= (A,B,C,D,E), E''''''= (E,F) but I do think I'm wrong... Can someone help understand the issue? Thanks A: (Reformatted for readability) My understanding is that if I apply the 3NF which says that a schema is 3NF if all attributes non-prime do not transitively depend on any key candidate , the result should be: * *E1= {A,B,C,E,F} *E2= {B,D} *E3= {A,B,C,D,F} *E4= {D,E} *E5= {A,B,C,D,E} *E6= {E,F} 3NF means that a) the relation is in 2NF, and b) every non-prime attribute is directly dependent (that is, not transitively dependent) on every candidate key. In turn, 2NF means that a) the relation is in 1NF, and b) every non-prime attribute is dependent on the whole of every candidate key, not just on part of any candidate key. Given {ABC} is a candidate key, and given {AB->D}, you can see that D depends on part of a candidate key. So * *E0 = {A,B,C,D,E,F} is not in 2NF. You fix that by moving that dependent attribute to a new relation, and you copy the attributes that determine it to the same relation. * *R0 = {ABC DEF} This relation—which we started with, and which is not in 2NF—goes away, to be replaced with *R1 = {ABC EF} *R2 = {AB D} You want to continue from here? A: When it comes to getting normalization right, there is no substitute for understanding the formal definitions. If you're still working on building that understanding, there's a cute little mnemonic that people use to help remember the essence of 3NF and to judge whether a table that they're looking at is 3NF or not. "The key, the whole key, and nothing but the key, so help me Codd." How do you apply it? Every attribute of the relation must depend on the key. It must depend on the whole key. I must not depend on anything that isn't the key. When you look at your example, clearly there are problems and you need to normalize. You need to get to a point where every non-key column which violates 3NF is out of your original relation. Each of the non-key columns, D, E, and F all violate 3NF. Note that your additional functional dependencies cover all of the non-key columns in your original relation. Each of these additional functional dependencies is going to result in a relation: { A B D } - This solves 3NF for attribute D { C D E } - This solves 3NF for attribute E { E F } - This solves 3NF for attribute F What is left to cover from your original relation? Nothing except the candidate key: { A B C }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ashx error http handler 2 I'm getting the an error at "byte[] param = [...]" from the following http handler. Other ashx files are working. Tell me if you need more info... Request is not available in this context Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: Request is not available in this context public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); //Post back to either sandbox or live string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr"; string strLive = "https://www.paypal.com/cgi-bin/webscr"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; System.Web.UI.Page pa = new System.Web.UI.Page(); //HERE>HERE>HERE>HERE> byte[] param = pa.Request.BinaryRead(HttpContext.Current.Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; A: Why is there a call to System.Web.UI.Page's Request object? It won't have one since one hasn't been associated with the request. Your code: System.Web.UI.Page pa = new System.Web.UI.Page(); //HERE>HERE>HERE>HERE> byte[] param = pa.Request.BinaryRead(HttpContext.Current.Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); Shouldn't it read string strRequest; StreamReader reader = new StreamReader(context.Request.InputStream); strRequest = reader.ReadToEnd(); If all you want to do is get the raw string of the incoming request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: buildbot force build ignoring repository When I click on the 'builders' link of builbot URL and force a build, the git repository I specify on the form is getting ignored; the builder is using the repository it was originally built/configured with. Is this a known problem ? Is there some way to force the builder to use the new repo ? I'm running 0.8.4 on Ubuntu 10.04. Thanks for any help. A: This is a deliberate choice, as there various potential ways of creating a source stamp, that are insecure. Thus, someone could potentially execute arbitrary code on the slave, if buildbot used whatever repository URL passed into it. That said, it is easy to get the behavior you want. The simplest is to specify repourl=Property('repository', '<default-repository>') which will use the 'repository' property of the build (which gets initialized from the source stamp) or the default repository, if none is specified. (Property is imported from buildbot.process.properties)
{ "language": "en", "url": "https://stackoverflow.com/questions/7540368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: subplot titles in R I'm new in R. I have created 9x3 subplots using par(mfrow= c(3,3)) command using a simple loop and plotted scatter plot for pair-wise dependent variable. Now I want to have sub titles through (a-c) for 1st row; (d-f) for 2nd row & (g-i) for the last. Using "sub" command I could get (a-c) for 1st row but unable to get (d-f) for 2nd row & successively. Can anybody let me know in what way I can do so? A: Each plot call can create its own title using the main= assignment. The tricky step is getting a "master title". For that you will probably want to use mtext. Well OK, I suppose there may be some tricks to getting the subtitles you want with R "expressions", but that would be better illustrated if you offer a dataset and code than discussing in the abstract.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inspect helper clone I use the Google Chrome developer tools. When I want to inspect an element, I usually right click it and select "inspect element". This doesn't work for draggable helper clones. My code is as follows: $myElement.draggable({helper: 'clone'}); How can I inspect the helper clone that is only created once I start dragging the element? A: * *Go to Script Sources tab *In the right panel under Event Listener Breakpoints and under DOM Mutation choose DOMNodeInserted 3 . When a jQuery UI drag with clone helper happens a new DOM element inserted in DOM tree. This element would be last element before body end tag. then developer tool halt the document from operation because it have a breakpoint for insertion of a DOM element. 4 . Now you can inspect the cloned element and edit the CSS or so... Note: It seems those breakpoints doesn't work in Mac very well. Try it here: http://jsbin.com/ijacet/2 UPDATE: Now you can break on node insertion by right clicking on element: A: Just throw an exception from inside some code that is triggered while you are dragging - this will kill the js that erases the draggable element when you release the mouse button and freeze the draggable where it was on the screen when the exception occurred. Then you are free to inspect it to your hearts content :) The easy way is to throw an exception when you try to drop the element on a dropable, that's how i usually do it. A: As far as I know, you can't. You could (for testing purposes only) clone it explicitly, and append it to the document. Then you could inspect the clone just like any other element. Something like this would probably accomplish that: var tempElement = $myElement.clone(); tempElement.appendTo('body'); now, the clone should appear at the bottom of the document body, and you should be able to select it with your mouse when in the Inspector mode. Depending on what you're trying to figure out, this may or not give you enough information to extrapolate what the draggable's automatically created clone would look like. A: jQueryUI will create an exact copy of the draggable item. Therefore you don't need to inspect the item you drag, but you can inspect the item which is being dragged. Using the appendTo() option in the draggable you will even be able to define a location at which the draggable will be put into. ( http://jqueryui.com/demos/draggable/#option-appendTo ) Doing this by hand (so placing the code there by hand, in the container in which you like) you can inspect the actual object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Jquery append a div area Hi I want to add a new line in a table every time a button is clicked in my code, The code below works but I am expecting it inside the DIV tag called 'selector' as an addition to my table but instead it appears at the top of the page, What am i doing wrong please ? thanks <script type="text/javascript"> $(document).ready(function(){ $("#test").click(function() { tested(this) }); }); function tested() { newline = "<tr bgcolor='#666666'><td>&nbsp;</td> <td><input type='button' id='test1' value='Click to Test' /></td><td>&nbsp;</td> </tr> " ; $('#selector').append(newline) } </script> <table width="500" border="1" cellspacing="1" cellpadding="1" bgcolor="#CCCCCC" align="center"> <tr> <td width="50">top</td> <td>&nbsp;</td> <td width="50">&nbsp;</td> </tr> <div id='selector' > <tr bgcolor="#666666"> <td>&nbsp;</td> <td><input type="button" id="test" value="Click to Test" /></td> <td>&nbsp;</td> </tr> </div> <tr> <td>Bottom</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </body> </html> A: Your code is not valid html - and this is bound to cause unexpected behaviour in different browsers. You cannot include a div tag as a direct child of a table - use a tbody for this purpose intead: <table width="500" border="1" cellspacing="1" cellpadding="1" bgcolor="#CCCCCC" align="center"> <thead> <tr> ... </tr> </thead> <tbody id='selector' > ... </tbody> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/7540380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex for multiple email address replacements OK so here is my situation. I have a site that is run by WordPress. I need to ensure email obfuscation and as such have installed a plugin called 'Graceful Email Obfuscation'. This works great already. The catch is that I want a catchall in case someone does not follow the rules it specifies for entering email addresses (ie [email] test@example.com [/email]). The following regex works great at grabbing all the emails BUT I don't want it to touch the ones that are correctly written as [email]test@example.com[/email]. What do I need to add? // Match any a href="mailto: AND make it optional $monster_regex = '`(\<a([^>]+)href\=\"mailto\:)?'; // Match any email address $monster_regex .= '([^0-9:\\r\\n][A-Z0-9_]+([.][A-Z0-9_]+)*[@][A-Z0-9_]+([.][A-Z0-9_]+)*[.][A-Z]{2,4})'; // Now include all its attributes AND make it optional $monster_regex .= '(\"*\>)?'; // Match any information enclosed in the <a> tag AND make it optional $monster_regex .= '(.*)?'; // Match the closing </a> tag AND make it optional $monster_regex .= '(\<\/a\>)?`'; $monster_regex .= 'im'; // Set the modifiers preg_match_all($monster_regex, $content, $matches, PREG_SET_ORDER); My inputs for testing are this: <a href = "test@example.com">Tester</a> test@example.com <a href = "test@hotmail.com">Hotmail Test</a> [email]test@example.com] The output I am getting is this: ( [0] => Array ( [0] => <a href="mailto:test@example.com">Tester</a> [1] => <a href="mailto: [2] => [3] => test@example.com [4] => [5] => [6] => "> [7] => Tester</a> ) [1] => Array ( [0] => test@example.com [1] => [2] => [3] => test@example.com [4] => [5] => [6] => [7] => ) [2] => Array ( [0] => <a href="mailto:test@hotmail.com">Hotmail Test</a> [1] => <a href="mailto: [2] => [3] => test@hotmail.com [4] => [5] => [6] => "> [7] => Hotmail Test</a> ) [3] => Array ( [0] => [email]test@example.com[/email] [1] => [2] => [3] => [email]test@example.com [4] => [5] => [6] => [7] => [/email] ) ) Thanks in advance. A: So you want to match anything that looks like an email address unless it's already enclosed in [email]...[/email] tags? Try this: '%(?>\b[A-Z0-9_]+(?:\.[A-Z0-9_]+)*@[A-Z0-9_]+(?:\.[A-Z0-9_]+)*\.[A-Z]{2,4}\b)(?!\s*\[/email\])%i' NB: This answer only addresses the problem of how to match something that's not contained some larger structure. I don't intend to get into a debate over how (or whether) to match email addresses with regexes. I simply extracted the core regex from the question, bracketed it with word boundaries (\b) and wrapped it in an atomic group ((?>...)). Once a potential match is found, the negative lookahead asserts that the address isn't followed by a closing [/email] tag. Assuming the tags are correctly paired, that means the address already properly tagged. And if they aren't correctly paired, it's the plugin's job to catch it. While I'm here, I'd like to offer some comments on your regex: * *The range expression A-z appeared in some of your character classes. Probably just a typo, but some people use that as an idiom for matching uppercase or lowercase letters. That's an error because it also matches several punctuation characters whose code points happen to lie between the two letter ranges. (I fixed that when I edited the question.) *The characters <, >, :, ", @, = and / have no special meaning in regexes and don't need to be escaped. It doesn't hurt anything, but regexes hard enough to read already; why throw in a bunch of backslashes and square brackets you don't need? *The question mark in (.*)? belongs inside the parens: (.*?). That way it will reluctantly match everything before the next </a>. If there's nothing to match, it will match nothing. Making it optional is not only redundant, it could lead to serious performance penalties.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MySQL search problem to find lowercase and uppercase letters at the sametime I have a table where users enters there username in both lower case(eg: arup) and uppercase(eg: Arup) or both (eg: aRuP). But my problem is now that if I search database to show member username like %Arup, mysql returns empty result if not founds exactly. id | username | name | sex 1 arUp Arup Sarma Male <?php $q=strip_tags($_POST['user']); /// eg. Arup $qry=mysql_fetch_row(mysql_query("SELECT id,name,sex FROM membertable WHERE username='%$q'")); echo $qry['0']."<br>".$qry['1']."<br>".$qry['2']; ?> /// Now above sql query will return zero result as there is no username in the form of arUp. How to make SQL query Case-insensitive ? anyone help please... A: I think that this link could help to understand your problem... Anyway you could solve your problem with this: SELECT * FROM your_table WHERE LOWER(username) LIKE '%arup' A: You can call UPPER on both sides of the comparison: SELECT id,name,sex FROM membertable WHERE UPPER(username) = UPPER('%$q') The "right way", according to the official manual, is choosing a case-insensitive collation, which might be faster but is also more complicated. A: based on this: http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html i'd try this: where username COLLATE latin1_swedish_ci = '%$q'
{ "language": "en", "url": "https://stackoverflow.com/questions/7540385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android, Saving and loading a bitmap in cache from different activities I have i bitmap that needs to show in a new activity, so i cahe it and in the opened activity i try to load it but i get a nullPointerException. Here i save the image : File cacheDir = getBaseContext().getCacheDir(); File f = new File(cacheDir, "pic"); try { FileOutputStream out = new FileOutputStream( f); pic.compress( Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Intent intent = new Intent( AndroidActivity.this, OpenPictureActivity.class); startActivity(intent); and then in the new activity i try to open it : public void onCreate(Bundle icicle) { super.onCreate(icicle); File cacheDir = getBaseContext().getCacheDir(); File f = new File(cacheDir, "pic"); FileInputStream fis = null; try { fis = new FileInputStream(f); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeStream(fis); ImageView viewBitmap = (ImageView) findViewById(R.id.icon2); viewBitmap.setImageBitmap(bitmap); setContentView(R.layout.open_pic_layout); A: Just check your code: ImageView viewBitmap = (ImageView) findViewById(R.id.icon2); viewBitmap.setImageBitmap(bitmap); setContentView(R.layout.open_pic_layout); You have written findViewById() before setting Content View. Its wrong. public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.open_pic_layout); // do your operations here }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: how to get info using ast parser i want to get info from every class of a .java file so that i can save in a structure (maybe a list) the methods that every method of every class calls. Can anyone help me? thanx! A: ANTLR can generate a lexer/parser that will give you an AST. It has Java grammars ready to go, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get image with ajax request? There is some .php file, that returns .png image file. How to get this image with jQuery $.ajax() ? Also, is there were some mistakes with input parameters, .php file will return error in JSON way. How to understand, which infomation was returned - image or JSON with error? UPDATE: I need to draw some statistics graphics with this script. .php file gets some data (for example account id, which statistics is requested) and checks - if this user (user id is got from session is allowed to view the requested user's statistics, or not). If it's allowed than image is returned, if not - than json error. So i can make but if there will be error, image doesn't load. But I need to show error notification to user. A: If you are return this image as attachment to response - I thing you can't get this attachment in javascript variable, otherwise if you return image in a response stream and set property content type you can just assign you .php to image srs: $('img').attr('src', 'my-image-handler.php'); A: You can use it like this: <img src="data:image/png;base64,R0lGODlhUA... " width="80" height="15" /> So i suggest you get the base64 encoded string from the ajax request and use that to display the image A: http://www.anthonymclin.com/code/7-miscellaneous/98-on-demand-image-loading-with-jquery You need to send the image in the right format to the AJAX request. Solutions are for example octect stream, base64 etc. there are many ways to achieve on demand content loading. The important thing is to keep server-side and client-side synchron. It's like, if you send JSON to the server, get XML back, but expect HTML you're JS won't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I fetch the HTML contents of one single TYPO3 page into another CMS? We need to display the content of one single TYPO3 page in Habari. It would suffice to retrieve the HTML, as styling (CSS) is done separatly. However, we only want the HTML of the content elements - not the whole, fully rendered page. * *How could we achieve that? *Does TYPO3 (or one of its plugins) provide a facility for that? A: This can be done via a custom Typoscript template-record in the Typo3 backend that just outputs the content without any further HTML and or tags. Putting something like this in the 'setup': page = PAGE page.config.disableAllHeaderCode = 1 page.10 < styles.content.get Then make sure in the template-record it say's that it's a root-template, and that it clears constants and setup before this template. And put this record on the top most page (aka root). Also make sure that you included the static template of CSS Styled Content. This can be done when editing the template-record inside Typo3. A: You could do this in Habari using something like this: $url = "http://your-typo3-url/"; $output = RemoteRequest::get_contents( $url ); $output will then be the HTML contents of the page. You can then use a combination of strpos() and substr() to pull the relevant HTML content you want, eg just the <body> You can do this in one of your theme template files, the theme's theme.php file itself or even within a plugin. You can then use Habari's native caching to cache the content too so you don't have to retrieve the Typo3 page with every page view. A: BTW, You could use typo3_webservice fro that. It uses XMLRPC protocol, and quite easy to implement with PHP. http://typo3.org/extensions/repository/view/typo3_webservice/current/
{ "language": "en", "url": "https://stackoverflow.com/questions/7540390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP/PEAR SearchReplace - String is "varyingText" - How to replace "varyingText" with "newVaryingText"? I have a simple application based on the php pear class SearchReplace: // Define result of Activate click if (isset($_POST['action']) and $_POST['action'] == 'Activate') { include "$docRoot/includes/pear/SearchReplace.php" ; $files = array( "$docRoot/promotions/index.php" ) ; $snr = new File_SearchReplace( '$promoChange = "";', '$promoChange = "'.$currentYear.'/'.$currentPromotion.'";', $files) ; $snr -> doSearch() ; } Notice the string that it is configured to search for: $promoChange = ""; What I need to do, is replace this string, when there is a varying value assigned to the variable $promoChange So basically, what I am trying to replace would look something like this: $promoChange = "2011/sep-oct"; I would need something along the lines of: $promoChange = "%"; What would be the correct way of doing this? If anyone has any input in this matter, it would be appreciated greatly, Thank You! A: You could open the file and replace using regex manually. The regex you need probably looks something like: $text = preg_replace( '/\$promoChange = "[^"]*";/', '$promoChange = "' . $currentYear . '/' . $currentPromotion . '"', $text ); I would caution against using something like this for anything more complicated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change fill color of a cell in MS Excel 2010? i need to change color of a cell in excel 2010 by function. a person who has low score be "Red" for example. A: Here are the steps to use conditional formatting (using Excel 2007/2010): * *Select the cells you want to apply the formatting to *Click on Conditional Formatting on the ribbon *Go to Highlight Cell Rules *Select "Less than..." *Enter the number you want and choose a 'fill' you want Hint: Don't highlight the entire column of cells and apply the conditional formatting to it - it will hurt performance. Just highlight the cells you really need to apply it to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert NaN to 0 in JavaScript Is there a way to convert NaN values to 0 without an if statement? Example: if (isNaN(a)) a = 0; It is very annoying to check my variables every time. A: You can do this: a = a || 0 ...which will convert a from any "falsey" value to 0. The "falsey" values are: * *false *null *undefined *0 *"" ( empty string ) *NaN ( Not a Number ) Or this if you prefer: a = a ? a : 0; ...which will have the same effect as above. If the intent was to test for more than just NaN, then you can do the same, but do a toNumber conversion first. a = +a || 0 This uses the unary + operator to try to convert a to a number. This has the added benefit of converting things like numeric strings '123' to a number. The only unexpected thing may be if someone passes an Array that can successfully be converted to a number: +['123'] // 123 Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number. A: Using a double-tilde (double bitwise NOT) - ~~ - does some interesting things in JavaScript. For instance you can use it instead of Math.floor or even as an alternative to parseInt("123", 10)! It's been discussed a lot over the web, so I won't go in why it works here, but if you're interested: What is the "double tilde" (~~) operator in JavaScript? We can exploit this property of a double-tilde to convert NaN to a number, and happily that number is zero! console.log(~~NaN); // 0 A: Write your own method, and use it everywhere you want a number value: function getNum(val) { if (isNaN(val)) { return 0; } return val; } A: Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place? If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus. The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete. NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it. A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.) Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this: function getFoobarFromUser(elementid) { var foobar = parseFloat(document.getElementById(elementid).innerHTML) if (isNaN(foobar)) foobar = 3.21; // default value return(foobar.toFixed(2)); } A: I suggest you use a regex: const getNum = str => /[-+]?[0-9]*\.?[0-9]+/.test(str) ? parseFloat(str) : 0; The code below will ignore NaN to allow a calculation of properly entered numbers: const getNum = str => /[-+]?[0-9]*\.?[0-9]+/.test(str) ? parseFloat(str) : 0; const inputsArray = [...document.querySelectorAll('input')]; document.getElementById("getTotal").addEventListener("click", () => { let total = inputsArray.map(fld => getNum(fld.value)).reduce((a,b)=>a+b); console.log(total) }); <input type="text" /> <input type="text" /> <input type="text" /> <input type="text" disabled /> <button type="button" id="getTotal">Calculate</button> A: Methods that use isNaN do not work if you're trying to use parseInt(). For example, parseInt("abc"); // NaN parseInt(""); // NaN parseInt("14px"); // 14 But in the second case, isNaN produces false (i.e., the null string is a number). n="abc"; isNaN(n) ? 0 : parseInt(n); // 0 n=""; isNaN(n) ? 0: parseInt(n); // NaN n="14px"; isNaN(n) ? 0 : parseInt(n); // 14 In summary, the null string is considered a valid number by isNaN, but not by parseInt(). It was verified with Safari, Firefox and Chrome on macOS v10.14 (Mojave). A: NaN is the only value in JavaScript which is not equal to itself, so we can use this information in our favour: const x = NaN; let y = x!=x && 0; y = Number.isNaN(x) && 0 We can also use Number.isNaN instead of the isNaN function as the latter coerces its argument to a number isNaN('string') // true which is incorrect because 'string'=='string' Number.isNaN('string') // false A: Something simpler and effective for anything: function getNum(val) { val = +val || 0 return val; } ...which will convert a from any "falsey" value to 0. The "falsey" values are: * *false *null *undefined *0 *"" ( empty string ) *NaN ( Not a Number ) A: var i = [NaN, 1,2,3]; var j = i.map(i =>{ return isNaN(i) ? 0 : i}); console.log(j) A: Please try this simple function var NanValue = function (entry) { if(entry=="NaN") { return 0.00; } else { return entry; } } A: Using user113716's solution, which by the way is great to avoid all those if-else, I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity. In the process writing of non-numbers in unit and quantity textboxes, their values are being replaced by zero, so the final posting of user data has no non-numbers. <script src="/common/tools/jquery-1.10.2.js"></script> <script src="/common/tools/jquery-ui.js"></script> <!--------- link above two lines to your jQuery files ------> <script type="text/javascript"> function calculate_subtotal(){ $('#quantity').val((+$('#quantity').val() || 0)); $('#unit').val((+$('#unit').val() || 0)); var calculated = $('#quantity').val() * $('#unit').val(); $('#subtotal').val(calculated); } </script> <input type = "text" onChange ="calculate_subtotal();" id = "quantity"/> <input type = "text" onChange ="calculate_subtotal();" id = "unit"/> <input type = "text" id = "subtotal"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7540397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "316" }
Q: Can binarysearch be used for checking primality? I wonder if binary search can be used to check whether a number is prime , Since the real question is can I find a number which is divisble other than the number itself and 1, and therefore I can imagine looking through an array of ordered integers from 2 to i/2 (i being a number being checked)....... A: Obviously not. Binary search is a method of dividing the interval to two (almost) equal parts and decide which one contains the search value. Testing any number to see whether it is a divisor doesn't tell you anything about which interval to choose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery: Get tag inside element with class <div id="yes"> <div class="wrapper"> <something>...</else> <p>foobar</p> </div> </div> I want to get the p-tag to append a classname $("div.wrapper", "#yes").addClass("newClassName"); But where to add the "p"? A: Try $("div#yes > div.wrapper > p").addClass("newClassName"); Here is a jsFiddle demo A: This can be achieved by the folowing code: $("#yes div.wrapper p").addClass("newClassName"); This code gets any p-tag within any div with the class "wrapper" which is located in an element with the id "yes". A: $(".wrapper").find("p").addClass("newClassName"); A: $("#yes").find("p").addClass("newClassName");
{ "language": "en", "url": "https://stackoverflow.com/questions/7540409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to disable thunderbird shortcut i use both thunderbird and zend. ctrl+shift+r is used by them. but when i use it in zend and other places, i found that it is a global shortcut of thunderbird. does any one know how to disable the shortcuts or it's just a bug for me only? A: You can install keyconfig and deactivate the shortcut.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you refactor two classes with the same, duplicated events? Both of these classes contain another private class that raises events. These two classes then re-raise these events to clients. Unfortunately, each of the two classes has this exact same code: public class FirstClass { public delegate void FooEventHandler(string foo); public delegate void BarEventHandler(string bar); public delegate void BazEventHandler(string baz); public event FooEventHandler Foo; public event BarEventHandler Bar; public event BazEventHandler Baz; private PrivateObject privateObject; public FirstClass() { privateObject.Foo += FirstClass_Foo; privateObject.Bar += FirstClass_Bar; privateObject.Baz += FirstClass_Baz; } private void FirstClass_Foo(string foo) { if (Foo != null) { Foo(foo); } } private void FirstClass_Bar(string bar) { if (Bar != null) { Bar(bar); } } private void FirstClass_Baz(string baz) { if (Baz != null) { Baz(baz); } } } As you can see, I have to re-raise events from a private object. It is redundant. I tried using inheritance and placing this duplicate code in a base class but I keep getting errors like: The event 'BaseClass.Foo' can only appear on the left hand side of += or -= (except when used from within the type) Does anyone know how to get rid of this duplicate code? A: what about exposing the events of the private object as properties of your wrapper? As in, public class ExternalClass { private InternalClass _internalObject = new InternalClass(); public event InternalClass.someDelegate SomeEvent { add { _internalObject.SomeEvent += value; } remove { _internalObject.SomeEvent -= value; } } } public class InternalClass { public delegate void someDelegate(string input); public event someDelegate SomeEvent; } If you are familiar with c# Properties you probably already know the get and set keywords. The add/remove keywords are basically the same thing, only they are fired when you attempt to add or remove a value to your property. So, when you command to (un)register your delegate to ExternalClass.SomeEvent, you are actually (un)registering to the InternalClass.SomeEvent event. If you are not familiar with c# Properties, http://msdn.microsoft.com/en-us/library/x9fsa0sw(v=vs.80).aspx would help you. A: I think this will work for you. The public interface allows PrivateObject to remain internal. The only other trick is that RegisterIFooEvents must be called in the constructor. public interface IFooEvents { event BaseClass.FooEventHandler Foo; event BaseClass.BarEventHandler Bar; event BaseClass.BazEventHandler Baz; } internal class PrivateObject : IFooEvents { public event BaseClass.FooEventHandler Foo; public event BaseClass.BarEventHandler Bar; public event BaseClass.BazEventHandler Baz; public void ChangeFoo(string foo) { if (Foo != null) { Foo(foo); } } } public abstract class BaseClass : IFooEvents { public delegate void BarEventHandler(string bar); public delegate void BazEventHandler(string baz); public delegate void FooEventHandler(string foo); private IFooEvents _fooEvents; public event FooEventHandler Foo { add { _fooEvents.Foo += value; } remove { _fooEvents.Foo -= value; } } public event BarEventHandler Bar { add { _fooEvents.Bar += value; } remove { _fooEvents.Bar -= value; } } public event BazEventHandler Baz { add { _fooEvents.Baz += value; } remove { _fooEvents.Baz -= value; } } protected void RegisterIFooEvents(IFooEvents fooEvents) { _fooEvents = fooEvents; } } public class FirstClass : BaseClass { private readonly PrivateObject _privateObject; public FirstClass() { _privateObject = new PrivateObject(); RegisterIFooEvents(_privateObject); } public void ChangeFoo(string foo) { _privateObject.ChangeFoo(foo); } } Test run in console app: class Program { static void Main(string[] args) { var class1 = new FirstClass(); class1.Foo += EventRaised; class1.ChangeFoo("TEST"); } static void EventRaised(string arg) { Console.WriteLine(arg); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Add line break after some (ex. 8) words I was searching for a script to put a line break after a number of words. I found this here in stackoverflow: Applying a style to and inserting a line break after the first word in a link So, i change it a little: var el = $('.wtt'); //where wtt is the class of the elements that you want to add the <br /> var text = obj.html(); var parts = text.split(' '); //number 7 represents 8 words $('.wtt').html($('.wtt').html().replace(parts[7],parts[7]+'<br />')); A: The following would replace the 8th space in a string with a <br> var text = 'hello there purple giraffe, how are you doing today.'; alert(text.replace(/^((\S+\s+){7}\S+)\s+/, '$1<br>')); \S+ matches one or more non-space character. \s+ matches one or more space character.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SAX2 (Xerces-C): How to get the line number of parsed tags? I parse an XML file in C++ using the SAX2 api of Xerces-C. So I do implement the DefaultHandler interface and its functions void startElement( const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const xercesc::Attributes& attrs ); and void endElement( const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname ); When the xml file has a syntax error, the thrown SAXParseException gives me the line number where the error occurred and I can print the error line to the user. In my application it is possible that the syntax is well formed but the contained data doesn't have much sense. In this case I would also like to print the error line to the user. But I didn't find a way to get the current line number, because the xml is syntactically correct and there is no SAXParseException thrown. Is there a way to get the line number of a tag? A: Override the setDocumentLocator() method in your class derived from xercesc::DefaultHandler to get hold of the xercesc::Locator object. You can then call its getLineNumber() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cache result/data sets in EF 4.1? I have a view in MVC3 application that calls a stored procedure (that takes a while to execute) to populate a grid on a view and would like to cache that data somehow? Not familiar with EF cacheing but I would actually like to somehow run the query possibly on a background thread in the background on start up so that when the user clicks on this particular view (which is a common data view the usere want to see) results are fast and cached as dispalyed in the webgrid Any information would be greatly appreciated. Thanks! A: Use the repository pattern to request your data entity. Inside your repository class cache the result in the MemoryCache (a specific type of cache in .net). Any time you then request the object the repository class knows to get it from te cache or not and the caller doesn't need to know anything about the caching. I would use either code first OR the poco templates to not have any baggage stored from other dependencies . For POCO - you can either use the EF POCO Templates, or a code first model to give you poco classes without the EF baggage. Let me know if you have any specific q's on these steps and I can go into more detail. If you need to take a while loading this on application start, another thread is definitely the way to do it as any long running Application_start code in the main thread can cause a deadlock. A more basic approach per user is to put the object in the users session but that's indeed up to you. There is no EF caching as part if the EF framework that exists outside of the ObjectContext lifetime. Another method is to handle this in the controller method as shown here: How to cache mvc3 webgrid results (so that col sort click doesn't?
{ "language": "en", "url": "https://stackoverflow.com/questions/7540430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best Practice: using jQuery within an iframe CASE 1: once when using fancybox, i was not able to get the following code to work within an iframe.(yes i tried all the flavours related to the following code. see here [i have also replied to this thread] ) parent.$.fancybox.close(); Finally I solved this problem by removing the main jquery file(jquery-1.5.2.min.js) from within the iframe. CASE 2: in another page of the same project, the same fancybox(iframe) was saying $ is not defined. Now, I solved this problem by adding the main jquery file(jquery-1.5.2.min.js) inside the iframe. The problem i am facing now: $.fancybox.resize wont work for this iframe!(i strongly believe its cuz of the main jquery(jquery-1.5.2.min.js) i am including inside the iframe.) This is confusing to me. I searched for issues when using jquery in iframes. some say there is no problem having another jquery inside the iframe. most ppl dont seem to have problems? cuz i was not able to find many related questions. * *Please tell me what is going wrong here. Something i need to take care of when using jquery within iframes?. *Also please refer me to some resources i need to be looking up to handle these kinds of problems. like related to iframes? or iframes and javascript, scope related problems? etc? Note: 1. these iframes are working correctly when individually accessed with a jquery-1.5.2.min.js included at the top. 2. My environment : windows xp | firefox 3.6.22 | jquery 1.5.2 | fancybox 1.3.4 A: Have you thought it might be a bug in jquery? After all, you are using an old version. Maybe you should download Jquery 1.6.4, try it, and post back here if you're still having problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IDisposable with member from missing external assembly fails in finalizer I have 2 assemblies, A containing the Main method and the Foo class, that uses Bar the class from assembly B: Bar assembly (assembly B): public sealed class Bar : IDisposable { /* ... */ public void Dispose() { /* ... */ } } Foo class (assembly A): public class Foo : IDisposable { private readonly Bar external; private bool disposed; public Foo() { Console.WriteLine("Foo"); external = new Bar(); } ~Foo() { Console.WriteLine("~Foo"); this.Dispose(false); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) external.Dispose(); disposed = true; } } Entry point (in assembly A): class Program { static void Main(string[] args) { try { var foo = new Foo(); Console.WriteLine(foo); } catch (FileNotFoundException ex) { // handle exception Console.WriteLine(ex.ToString()); } Console.ReadLine(); } } One of the requirements for this piece of software is that it must gracefully handle the case when a dll is missing. So when I delete assembly B, and start the application I would expect that the try catch block in the main method handles the FileNotFoundException thrown when the assembly B is missing. Which it sort of does, but that is where the problems start... When the application continues (a line is entered in the console), the finalizer of the Foo class is called (?!) although no instance of Foo was created - the constructor hasn't been called. Since there is no instance of the class there is no way for me to call GC.SupressFinalize on the instance externally. The only thing you see in the console output when running the project without the B assembly is ~Foo. So the questions: * *Why is the finalizer called even though no instance of the class is created? (to me it makes absolutely no sense! I would love to be enlightened) *Is it possible to prevent the application from crashing without a try-catch block in the finalizer? (this would mean refactoring the whole code base...) Some background: I encountered this problem when writing a plugin enable enterprise application with the requirement that it must continue operation if a dll is missing in the plugin deployment folder and flagging the faulty plugin. I figured that the try-catch block around the external plugin loading procedure would suffice, but obviously it doesn't, since after catching the first exception the finalizer is still invoked (on the GC thread), which finally crashes the application. Remark The above code is the most minimalistic code I could write to reproduce the exception in the finalizer. Remark 2 If I set the breakpoint in the Foo constructor (after deleting Bar's dll) it is not hit. This means if I would set have a statement in the constructor that creates a critical resource (before newing up Bar) it wouldn't be executed, hence no need for the finalizer to be called: // in class Foo public Foo() { // ... other = new OtherResource(); // this is not called when Bar's dll is missing external = new Bar(); // runtime throws before entering the constructor } protected virtual void Dispose(bool disposing) { // ... other.Dispose(); // doesn't get called either, since I am external.Dispose(); // invoking a method on external // ... } Remark 3 An obvious solution would be to implement the IDisposable like below, but that means breaking the reference pattern implementation (even FxCop would complain). public abstract class DisposableBase : IDisposable { private readonly bool constructed; protected DisposableBase() { constructed = true; } ~DisposableBase() { if(!constructed) return; this.Dispose(false); } /* ... */ } A: I think the complaint here is that the object is failing to construct, but the finalizer is still invoked and because the finalizer thread is catching the exception, you are prevented from catching it yourself? This is perfectly legitimate behavior. Suppose the class partially constructed, and had opened some critical resource before it threw? What would happen if the finalizer didn't run? The cases for this are simplified in C#, but in C++ it was the subject of many posts and books (Sutter: Exceptional C++). SO: Is Finalizer Called if constructor throws (C++/c#) The answer to the implicit question, how do I handle binding failures for missing/optional assemblies at run time?, is that you don't. The best solution is to poll the directory, load the assemblies manually, and retrieve the contained types based on interfaces exposed by the assembly and your convention. Screen shot of binding failure from inside the finalizer thread. If you comment out disposing line for Bar, the exception goes away, but the binding failure does not. A: Why is the finalizer called even though no instance of the class is created? The question makes no sense. Obviously an instance is created; what would the finalizer be finalizing if there wasn't an instance created? Are you trying to tell us that there's no "this" reference in that finalizer? the constructor hasn't been called The constructor can't be called because jitting the constructor references a field whose type is missing. How could a constructor body that can't even be jitted be called? You seem to think that just because a constructor cannot be called, that an instance cannot be created. That doesn't follow logically at all. Clearly there must be an instance before the ctor is called because a reference to that instance is passed to it as "this". So the memory manager creates an instance - and the garbage collector knows that there's memory allocated - and then it calls the constructor. If calling the constructor throws an exception - or is interupted by an asynchronous exception such as a thread abort - there's still an instance there, known to the garbage collector, and therefore in need of finalization when it is dead. Since the object will never be assigned to any live variable -- it cannot be, since the assignment happens after the ctor, and the ctor threw when the jitter tried to jit it -- it will be determined to be dead on the next gen zero collection. It will then be put onto the finalizer queue, which will make it alive. the finalizer is still invoked (on the GC thread), which finally crashes the application. Then fix the finalizer so that it does not do that. Remember, the ctor can be interrupted at any time by an asynchronous exception such as a thread abort. You cannot rely on any invariant of an object being maintained in the finalizer. Finalizers are deeply weird code; you should assume that they can run in arbitrary order on arbitrary threads with the object in an arbitrarily bad state. You are required to write extremely defensive code inside a finalizer. If I set the breakpoint in the Foo constructor (after deleting Bar's dll) it is not hit. Correct. As I said, the constructor body cannot even be jitted. How could you hit a breakpoint in a method that cannot even be jitted? This means if I would set have a statement in the constructor that creates a critical resource (before newing up Bar) it wouldn't be executed, hence no need for the finalizer to be called. Whether or not you think a finalizer needs to be called is completely irrelevant to the garbage collector. The finalizer might have other semantics than merely cleaning up resources. The garbage collector does not attempt to psychically determine the developer's intentions and make decisions about whether it needs to call the finalizer or not. The object was allocated and has a finalizer and you did not suppress finalization on it, so it's gonna be finalized. If you don't like that then don't make a finalizer. You made a finalizer because presumably you wanted all instances of the object to be finalized, and so they're going to be. Frankly, I would revisit your basic scenario. The idea that you can safely recover and continue to execute code in an appdomain where required DLLs are missing seems like an extremely bad idea to me. Getting this right is going to be very difficult. A: You might want to put your Foo class in a third assembly AssemblyC, and then setup an handler for the AppDomain.CurrentDomain.AssemblyResolve event first in your main function. Then attempt to load and execute the Foo class through Reflection; this way, you can check whether the file exists and react properly. After that, the event handler will fire whenever an assembly is missing (starting from the direct dependencies of AssemblyC, which would be the Bar class in this example). A: It is a guess, but I tried something like this: public class Foo : IDisposable { private Bar external; private bool disposed; public static Foo CreateFoo() { Foo foo = new Foo(); foo.external = new Bar(); return foo; } private Foo() { } ~Foo() { Console.WriteLine("~Foo"); this.Dispose(false); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) external.Dispose(); disposed = true; } } That sample will work as you expect. And now my guess: I think that the constructor is not the first method that is called, when an object will be created. It looks like that something out of our control is allocating the space for the created object before constructor is called, or something similar. This is the point where I suppose GC to start working. It is getting the ClassInfo and knows that a finalizer is available. So it starts the Finalizer-Thread and creates a handle to that allocated memory. Know the constructor would be called, and the object would be created from that handle. But before calling a constructor (even a method) something checks for availability of all referenced types within this code block. This is the point where the FileNotFoundException is thrown. Note, that is before you see debugger entering the constructor. Now we move into the Finalizer-Thread, it looks at it's handle of Foo and sees that this handle is not used anymore (actually it was never used). It starts finalizing. This is the point where your finalizer is called. You access the Dispose(bool) method within, and this is the point where the second FileNotFoundException will be thrown, because you are accessing Bar class within that method. That exception will throw on that obscure method check before calling it. I assume that it has something to do with some optimizations, maybe referenced types are lazy loaded. The strange thing, when the constructor won't throw an exception directly, like in my example, the GC will check this and will not call the finalizer for that object. Maybe I'm wrong and the object is still used and not collected by GC. Edit: The best solution would be rather simple. Remove the finalizer from your class. You don't have unmanaged resources in use, so you won't need a finalizer or Dispose(bool) at all. A: I think you will have to refactor some things. It's difficult for us to know where it will be the most appropriate without being at your seat :-) For example, adding a try catch to all finalizers does not seem a so big deal to me (you can search finalizers using a regex for example), but it may be to you. The .NET Framework really assumes that the assemblies you reference and the types you use are there at runtime. If you want a more dynamic system, a plugin-type architecture, you need to architect your assembly and your types differently for example using things like the System.Addin namespace or other libraries such as MEF (see this on SO: Choosing between MEF and MAF (System.AddIn)) So, in your case, you could solve the issue in Foo like this: public class Foo : IDisposable { // use another specific interface here, like some IBar, // this is a sample, so I use IDisposable which I know is implemented by Bar private readonly IDisposable external; public Foo() { Console.WriteLine("Foo"); external = Activator.CreateInstance(Type.GetType("AssemblyB.Bar, AssemblyB")) as IDisposable; } ... same code } But that means refactoring too...
{ "language": "en", "url": "https://stackoverflow.com/questions/7540433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting change in the value of python variables Is there some way to call a function each-time the value of a variable changes, in python? Something like a listener, perhaps? Specifically, I'm referring to the case where only the variable is shared between scripts like a GAE-Session. (Which uses Cookies, Memcache, etc to share data) Example: ScriptA & ScriptB, share a session variable. When Script B changes it, SctiptA has to call a method to handle that change. A: Use properties. Only mutable values can change to begin with. class Something(object): @property def some_value(self): return self._actual @some_value.setter def some_value(self, value): print ("some_value changed to", value) self._actual = value A: If the variable is a class attribute, you may define __setattr__ in the class. A: You Probably need extend type "int" or "float", and override the function "setattr", make it to response in your own way. class MyInt(int): ... def __setattr__(self, attr, val): ... super(MyInt, self).__setattr__(attr, val) ... var = MyInt(5) A: For this case (And I can't believe im saying the words) sounds like situation for setters def set_myvar(x): my_var = x some_function() return my_var
{ "language": "en", "url": "https://stackoverflow.com/questions/7540443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In what "event" should i put the -account-ID-session code? I am currently building a new site, where my customers get their own subdomain. for example: user1.mydomain.com user2.mydomain.com userDef.mydomain.com ... The site is built in and running on: IIS, asp.net C# So. Because there is a lot of virtual host subdomains. i have a Function in my code that connects to the database and check the ID of the account. SELECT account_ID where account_subdomain = 'user##' LIMIT 1; Depending on the ID both masterpage AND contentpage return different data / design. My question is, in which "event" should i put my function that put the accountID in the session("accountID")? because i want this on every single page i tried to put it in page_load in masterpage, but this is too late. I guess that page_load in content page is rendered before the page_load in masterpage? Soo, is there any good place to put my function so the account ID checkup is done before anything else is written on the webpage? Thanks! Matte A: One option is to create an HttpModule and put your code in there, since it would get to the page requests before the actual page starts processing. That would ensure that your account id was available on every page and set before any of the events you would need it in. If you do end up going this route, you would need to put your code in the PostAcquireRequestState or PreRequestHandlerExecute events so that Session will be available for you to modify. A: Try putting the code in Page_Init event of your master page. Page_Load event of content page is called before the Page_Load event of the master page. However, in case of Page_Init this is in reverse.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need help to make the first option blank in php retrieving column in mySQL? I have a good php script that works. But I need to modify it so the first select option is blank. Can anyone help? <?php // connect to MySQL $query = "SELECT <col> FROM <table>"; $result = mysql_query($query); ?> <select name="sel" id="sel"> <?php while($row = mysql_fetch_assoc($result)){ echo "<option>{$row['<col>']}</option>"; } ?> </select> A: Is this what you mean? <?php // connect to MySQL $query = "SELECT <col> FROM <table>"; $result = mysql_query($query); ?> <select name="sel" id="sel"> <option value="-1"></option> <?php while($row = mysql_fetch_assoc($result)){ echo "<option>{$row['<col>']}</option>"; } ?> </select> A: Just make it blank: <?php // connect to MySQL $query = "SELECT <col> FROM <table>"; $result = mysql_query($query); ?> <select name="sel" id="sel"> <option></option> <?php while($row = mysql_fetch_assoc($result)){ echo "<option>{$row['<col>']}</option>"; } ?> </select>
{ "language": "en", "url": "https://stackoverflow.com/questions/7540446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to see what menu item was clicked from Android.Gallery if I have two menu items When you want to send an image to facebook from your device, you open the Android.Gallery and select image and press share. I see Facebook have two Menu items in the Share-List: - facebook - facebook for HTC Sence (in my phone HTC Desire) If i want to have the same setup how is this done? Registering for the android.intent.action.SEND in my activity of course give me one Menu item. But i need two and handle them differently . A: you can have two activity's and each on having it's own SEND
{ "language": "en", "url": "https://stackoverflow.com/questions/7540448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which unique id to use for blogs and comments? This is a question that arose from the consequences of another question here: Is it better to have two separate user tables or one? Assuming I have two types of users, an Author and a Reader, each stored in relational tables keyed to a main Accounts table like so: TABLE Accounts { id email password salt created modified } TABLE reader { id user_id ... } TABLE author { id user_id ... } When an Author posts a blog, should I tag the blog with the unique id from the Authors table, or the unique id from the Accounts table? Same goes with reader comments - should I tag the comment with the Reader table unique id, or the Account table unique id? So, basically either: TABLE Blogs { id author_id } OR TABLE Blogs { id account_id } Which is less likely to bite back later on? A: TABLE user { id email password salt created modified } TABLE profile { user_id age favorite_movie ... other useless stuff... } TABLE user_role { user_id role_id } TABLE role { id name (author, admin, user, subscriber, etc...) } TABLE blog { id user_id title text ...etc... } user HASMANY role user HASONE profile user HASONE blog So a user can be an admin, and an author. You can find their blogs by looking for a matching blog for this user_id. If you have account type dependant fields then place them all in the "profile" table. A: Only you can answer fully, but my gut says that the blog entries should be tagged by author. The only reason to use account conceptually would be if a non-author can create (author) a blog post. So far, with the info provided, this does not look to be the case. Note that I also think that all authors should be users: everybody is a user, but only some users also have authorship status.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Elements in java ArrayList taking up two places I have made a LinkedList to store State objects which is a class I have created. I can add states to the list as expected, but whenever I try the size() method on the list it always returns twice the amount of elements I have added. Why is it doing this and how can I then use the get(n) method if each element has 2 values of n? Here's the code used to create and add to the list: static ArrayList<State> stateTable = new ArrayList<State>(); stateTable.add(new State(new Item(0,0))); I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable. Thanks A: I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable. If you already add the states to your list inside the constructor and additionally have the line stateTable.add( new State(new Item(0,0)) // <= first time inside new State(...) ); // <= second time explicitely in this line then you are indeed adding it twice. A: search for .add( and make sure you are not calling it in multiple places. If your ArrayList is not marked as private mark it as private. If you return your ArrayList from a method do return a read-only version via: Collection.unmodifiableList(stateTable); If you load the data in one method or the constructor and do not intend to do it anywhere else than do it something like: private static final List<State> stateTable; static { final List<State> temp; temp = new ArrayList<State>(); temp.add(new State(new Item(0,0))); stateTable = Collections.unmodifiableList(stateTable); } Using the unmodifiableList will cause your program to crash if you add objects into it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UNIX named PIPE end of file I'm trying to use a unix named pipe to output statistics of a running service. I intend to provide a similar interface as /proc where one can see live stats by catting a file. I'm using a code similar to this in my python code: while True: f = open('/tmp/readstatshere', 'w') f.write('some interesting stats\n') f.close() /tmp/readstatshere is a named pipe created by mknod. I then cat it to see the stats: $ cat /tmp/readstatshere some interesting stats It works fine most of the time. However, if I cat the entry several times in quick successions, sometimes I get multiple lines of some interesting stats instead of one. Once or twice, it has even gone into an infinite loop printing that line forever until I killed it. The only fix that I've got so far is to put a delay of let's say 500ms after f.close() to prevent this issue. I'd like to know why exactly this happens and if there is a better way of dealing with it. Thanks in advance A: A pipe is simply the wrong solution here. If you want to present a consistent snapshot of the internal state of your process, write that to a temporary file and then rename it to the "public" name. This will prevent all issues that can arise from other processes reading the state while you're updating it. Also, do NOT do that in a busy loop, but ideally in a thread that sleeps for at least one second between updates. A: What about a UNIX socket instead of a pipe? In this case, you can react on each connect by providing fresh data just in time. The only downside is that you cannot cat the data; you'll have to create a new socket handle and connect() to the socket file. MYSOCKETFILE = '/tmp/mysocket' import socket import os try: os.unlink(MYSOCKETFILE) except OSError: pass s = socket.socket(socket.AF_UNIX) s.bind(MYSOCKETFILE) s.listen(10) while True: s2, peeraddr = s.accept() s2.send('These are my actual data') s2.close() Program querying this socket: MYSOCKETFILE = '/tmp/mysocket' import socket import os s = socket.socket(socket.AF_UNIX) s.connect(MYSOCKETFILE) while True: d = s.recv(100) if not d: break print d s.close() A: I think you should use fuse. it has python bindings, see http://pypi.python.org/pypi/fuse-python/ this allows you to compose answers to questions formulated as posix filesystem system calls A: Don't write to an actual file. That's not what /proc does. Procfs presents a virtual (non-disk-backed) filesystem which produces the information you want on demand. You can do the same thing, but it'll be easier if it's not tied to the filesystem. Instead, just run a web service inside your Python program, and keep your statistics in memory. When a request comes in for the stats, formulate them into a nice string and return them. Most of the time you won't need to waste cycles updating a file which may not even be read before the next update. A: You need to unlink the pipe after you issue the close. I think this is because there is a race condition where the pipe can be opened for reading again before cat finishes and it thus sees more data and reads it out, leading to multiples of "some interesting stats." Basically you want something like: while True: os.mkfifo(the_pipe) f = open(the_pipe, 'w') f.write('some interesting stats') f.close() os.unlink(the_pipe) Update 1: call to mkfifo Update 2: as noted in the comments, there is a race condition in this code as well with multiple consumers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How dump assembler from executable I have an executable I compiled with C# and I would like to dump the code in assembler code from it, are there any tools to do that? Also is it possible to also create an executable from the assembler generated? A: C# doesn't compile down to assembler level, it compiles into a common intermediate language (CIL), which isn't the same thing. Compiled C# requires an interpreter, and always will. You can't just copy pieces of the compiled form into a non .NET program. A: C# doesn't compile to machine code, or at least the Microsoft C# compiler doesn't compile to machine code. However, you can get the intermediate language bytecode in an assembly-like printout using ildasm. Also, if you want to see one way that the CLR could just-in-time compile your C# code, compile to assembly language using Mono. An example given on their website: mono --aot program.exe Then you can objdump -d to get assembly language from this, at least on a *nix/Mac machine, or a Windows machine with Cygwin or MinGW.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html form to edit php code I'm working on a project that allows users to edit PHP code in PHP file. I have a PHP page that uses the mail function to send emails. I want to allow the user to change the message sent out (in the mail function). I know how to re-write over a file but how to edit it, I'm not sure... So here's the mail function: $name=$_POST['userName']; $emaily=$_POST['userEmail']; $email = "$sponsor_email"; $subject = "the subject"; $message = "This is the message I want the user to be able to edit."; mail($email, $subject, $message, "From: $user-email"); Now I've got the $message var printed out on in the html form (so the users can see what will be changed but i don't know how I'd go about actually writing the code to change it on from submit. Any ideas? Thanks! Sorry guys.... I didnt explain the situation properly. The php file with the mail function will not be used to send an email from that form. All i want the form to do is edit the php file basically. I don't want to send the email with this form, this is for users to edit the mail function. Hope thats more clear... A: Put the textarea in the form named "message", then do $message = $_POST['message']; A: create a PHP that read what is in the PHP file that contains code to be edited then print it out in a HTML textarea then make another file that will write that modified code in the PHP file that has the code(to be modified). You can use google find how to read and write in a file. A: On your editing page, just do something like below: $message = file_get_contents("path to message file"); echo "<textarea id=\"message\">".$message."</textarea>"; Then you can edit whatever the contents of the file were. Might be better though if you used a database, and sanitized the user input - rather than saving everything to a file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clojure simple sort function error I'm new in clojure, i try create functions thats will be sort collections and store it in object. My code: (defn uniq [ilist] ([] []) (def sorted (sort ilist))) I try to run it: (uniq '(1,2,3,6,1,2,3)) but get error: #<CompilerException java.lang.IllegalArgumentException: Key must be integer (NO_SOURCE_FILE:0)> What's wrong? Thank you. A: As with your other question, you're trying to use pattern-matching where it just doesn't apply. Your function would work fine1 if you deleted the ([] []) entirely. 1 You also shouldn't use def here; as the other respondents have noted, you want to use let for establishing local bindings. However, here you don't need any bindings at all: just return the result of the sort call. In fact, the def will cause you to return a Var instead of the actual sorted list. A: Since there's no need at all to use either 'let' or 'def', I have to agree with amalloy about Bart J's answer. Sure it warrants the upvotes because it's useful info, but it's not the right answer. Actually, defining the function is kind of useless, since (sort ilist) would do the trick. The result of the function is the 'object' you want. That is, unless you want to use the result of the sort multiple times at different places in the function body. In that case, bind the result of sort to a function local variable. If you only need the sort once, don't bother binding it at all, but just nest it inside other functions. For instance if you want to use it inside a unique function (which I guess is what you're wanting to do): (defn uniq "Get only unique values from a list" [ilist] ; remove nils from list (filter #(not(nil? %)) ; the list of intermediate results from (reduce comppair sortedlist) ; (includes nils) (reductions ; function to extract first and second from a list and compare (fn comppair [first second & rest] (if (not= first second) second)) ; the original sort list function (sort ilist)))) (uniq '(1,2,3,6,1,2,3)) (1 2 3 6) Then again, you could also just use the built-in distinct function, and take a look at it's source: (distinct '(1,2,3,6,1,2,3)) (1 2 3 6) (source distinct) (defn distinct "Returns a lazy sequence of the elements of coll with duplicates removed" {:added "1.0"} [coll] (let [step (fn step [xs seen] (lazy-seq ((fn [[f :as xs] seen] (when-let [s (seq xs)] (if (contains? seen f) (recur (rest s) seen) (cons f (step (rest s) (conj seen f)))))) xs seen)))] (step coll #{}))) A: To store the sorted collection into a variable do this: (let [sorted (sort your-collection)]) To understand the difference between a let and a def, this should help: You can only use the lexical bindings made with let within the scope of let (the opening and closing parens). Let just creates a set of lexical bindings. def and let do pretty much the same thing. I use def for making a global binding and lets for binding something I want only in the scope of the let as it keeps things clean. They both have their uses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to write - If Visible selector? Not sure how to write this; If .sub1 is visible, .homepage fadeTo .25 Sub1 has a FadeIn and I want the homepage opacity to drop to .25 if the sub1 is open? I have this; $("#cat").click(function(){ if ($('.sub1').is(':visible') ) { $(".homepage").fadeTo(500, .25);} else { $(".homepage").fadeTo(500, 1); } The actual website I am making > Website Mockup > Clicking Categories fades in the sub menu and makes homepage opacity 25%, clicking categories again, makes submenu fade Out making homepage 100%.....But clicking categories > Fashion > Mens Fashion > Smart, Brings up 'Mens Smart Fashion div" but clicking categories again fades the Mens Smart fashion div out, and brings .sub1 back, but the .homepage is 100% and not 25% when the .sub1 is open A: You can filter the visible .sub1 and check the length, this may not be so great if there are multiple .sub1's, maybe add a little specificity to the selector. This technique will filter out elements with css visibility:hidden or opacity: 0 for the first .sub1 (':eq(0)'). If the length is 0 the condition will return false. if($('.sub1:eq(0):visible').length) { //.homepage fade to .25 } Revised: $("#cat").click(function(){ if ($('.sub1').css('opacity') == .25 ) { $('.homepage').fadeTo(500, 1); } else { $('.homepage').fadeTo(500, .25); } }); I think the reason the it would not fade back in is because your condition was checking for opacicty:0 which you never reached when fading to .25. You should set the condition to check a number .25 to avoid checking multiple strings such as '.25' or '0.25'. Firefox reports '0.25'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save this code into a variable? Is there any way to save this block of code into a PHP variable ? The reason of doing this is because I want to send it through mail() echo 'MONDAY<BR>'; query_posts('meta_key=Date1&meta_value=MONDAY'); while (have_posts()): the_post(); if (in_category( '11' )) { echo get_post_meta($post->ID, 'HomeSlogan', true); } else { the_title(); } echo'<br>'; endwhile; This is what zneak suggests <?php ob_start(); echo 'MONDAY<br>'; query_posts('meta_key=Date1&meta_value=MONDAY'); while (have_posts()): the_post(); if (in_category( '11' )) { echo get_post_meta($post->ID, 'HomeSlogan', true); } else { the_title(); } echo'<br>'; endwhile; $mail = ob_get_contents(); echo $mail; ob_end_clean(); ?> A: You can either use string concatenation and avoid echo altogether, or use output buffering. Output buffering saves your script's output into a buffer instead of sending it to the browser, so it's easier to use if you have functions that print text and that you can't really control. // concatenation $mail = 'MONDAY<br>'; $mail .= 'more text'; $mail .= 'yet more text'; // output buffering ob_start(); echo 'MONDAY<br>'; echo 'more text'; echo 'yet more text'; $mail = ob_get_contents(); ob_end_clean(); For output buffering, you might want to read about ob_start, ob_get_contents and ob_end_clean.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: symfony 1.4/ doctrine 1.2 active record relationship tables code organize Let´s say I have a schema containing 3 tables: Users,Pages and Followers. An user can follow many pages. The followers table would contain the page_id and user_id. I need to create a method to return all the users following a page.. Should i create the method in the PageTable class ($page->getFollowers()) or should i create a method in the followersTable class $followers->getByIdPage($id). In a pure OO application the first approach makes more sense and also feels more natural but since symfony/doctrine creates also a class for the relationship tables I dont know. The approach i am trying to follow in my app each table class should only return objects from the table related to that class. Example: All the methods in the page class should return Page objects. By this approach if I put the method in followers class I shold only return objects of that class and not Pages objects thats what i need. Any thoughts about this? A: You should create the method getFollowers() in Page class. It makes sense because you want the followers of an object page. PageTable class should return a Collection of Page object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to continue developement of live Django Webapp? I am building a Django powered web app that has a large database component. I am wondering, how would I go about continuing to develop the web app while users are using the live, production version? There are two parts to the problem, as I see it, as follows: * *Making changes to templates, scripts, and other files *Making database schema changes Now, the first problem is easy to manage with a SVN system. Heck, I could just have a "dev" directory which have all my in-development files and, once ready, just copy them into the "production" directory. However, the second problem is more confusing to me. How do I test/develop new database changes without affecting the main/live database? I have been using South to do schema migrations during the initial creation stages of the web app, but surely I wouldn't want to make changes to the database while it is being used. Especially if I make changes that I don't want to keep. Any thoughts/ideas? A: You need another server on which to do your development. Typically, this is a personal machine, like your laptop. Often, you also have a copy of your production environment on a server, known as the staging server. Your workflow would be like this: * *Work on your code on your development machine, make all the changes you want, it's just you using it. *When the code is ready for production, you push it to the staging server to see that it really works properly in a server environment. *When you're sure it's ready for production, push it to the production server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Streaming a remote file i'm new to fmod, and I'm trying to use it for a simple application. I just need to open a remote music file (mostly mp3, and if that can help I can transcode on the server to always have mp3). When I try to FMOD_System_CreateSound(system, "http://somewhere.com/song.mp3", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &song); That works fine, it open and play the mp3 fine. But, when I try to do what I realy need : FMOD_System_CreateSound(system, "http://somewhere.com/somepage.view?id=4324324324556546456457567456ef3345&var=thing", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &song); It just don't works. That link for example would return a stream.mp3 file, but FMOD just fail on it. Is there a way to make it works ? I guess the problem is FMOD just don't find the filename in the link, but I can't change the link :/ If it's not possible, is there a way to make fmod works with curl (curl download the file perfectly), like a function to call for each part of the file ? Thanks A: The main issue with session ID based URLs is they can get quite long. Old versions of FMOD only supported 256 characters (causing truncation and failure to load), but any recent supported version allows up to 1024 characters. I would recommend updating to a more recent version of FMOD and report back if you have any troubles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reloadData call second function When i call a reload data then second times pass same directGestire function. How to correct update tableView? -(void)directGesture:(UISwipeGestureRecognizer *)gesture{ if (gesture.state == UIGestureRecognizerStateEnded) { NSLog(@"Get gesture"); [self.tableView beginUpdates]; [[self displayedObjects] removeObjectAtIndex:2]; [self.tableView endUpdates]; //have a problem second pass [self.tableView reloadData]; } } A: - (void)directGesture:(UISwipeGestureRecognizer *)gesture{ if (gesture.enabled) { //code here } //блокировка гестуры // NSLog(@"gesture.enabled 1 = %@\n", (gesture.enabled ? @"YES" : @"NO")); gesture.enabled = NO; // NSLog(@"gesture.enabled 2 = %@\n", (gesture.enabled ? @"YES" : @"NO")); //[gesture setDirection:UISwipeGestureRecognizerDirectionUp] ; [self.tableView reloadData]; gesture.enabled = YES; //NSLog(@"gesture.enabled 3 = %@\n", (gesture.enabled ? @"YES" : @"NO")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Regex: Match text NOT part of a HTML tag I would really want to have a Regex that is executable in node.js (so no jQuery DOM Handling etc., because the tags can have a different nesting) that matches all the text that is NOT a HTML tag or part of it into seperate groups. E.g. I'd like to match "5","ELT.","SPR"," ","plo","Unterricht"," ","&nbsp" and "plo" from that String: <tr class='list even'> <td class="list" align="center" style="background-color: #FFFFFF" > <span style="color: #010101">5</span> </td> <td class="list" align="center" style="background-color: #FFFFFF" > <b><span style="color: #010101">ELT.</span></b> </td> <td class="list" align="center" style="background-color: #FFFFFF" > <b><span style="color: #010101">SPR</span></b> </td> <td class="list" style="background-color: #FFFFFF" >&nbsp;</td> <td class="list" align="center" style="background-color: #FFFFFF" > <strike><span style="color: #010101">pio</span></strike> </td> <td class="list" align="center" style="background-color: #FFFFFF" > <span style="color: #010101">Unterricht</span> </td> <td class="list" style="background-color: #FFFFFF" >&nbsp;</td> <td class="list" style="background-color: #FFFFFF" >&nbsp;</td> <td class="list" align="center" style="background-color: #FFFFFF" > <b><span style="color: #010101">pio</span></b> </td> </tr> I can assure that there will be no ">"'s within the tags. The solution I found was (?<=^|>)[^><]+?(?=<|$), but that won't work in node.js (probably because the lookaheads? It says "Invalid group") Any suggestions? (and yes, I really think that Regex is the right way to go because the html may be nested in other ways and the content always has the same order because it's a table) A: Try 'yourhtml'.replace(/(<[^>]*>)/g,' ') '<tr class="list even"><td class="list" align="center" style="background-color: #FFFFFF" ><span style="color: #010101">5</span></td><td class="list" align="center" style="background-color: #FFFFFF" ><b><span style="color: #010101">ELT.</span></b></td><td class="list" align="center" style="background-color: #FFFFFF" ><b><span style="color: #010101">SPR</span></b></td><td class="list" style="background-color: #FFFFFF" > </td><td class="list" align="center" style="background-color: #FFFFFF" ><strike><span style="color: #010101">pio</span></strike></td><td class="list" align="center" style="background-color: #FFFFFF" ><span style="color: #010101">Unterricht</span></td><td class="list" style="background-color: #FFFFFF" > </td><td class="list" style="background-color: #FFFFFF" > </td><td class="list" align="center" style="background-color: #FFFFFF" ><b><span style="color: #010101">pio</span></b></td></tr>'.replace(/(<[^>]*>)/g,' ') It will give a space delimited text that you want to match (which you can split on space). A: Maybe you can split directly using the tags themselves: html.split(/<.*?>/) Afterwards you have to remove the empty strings from the result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: log4j for logging a Web Application which is in production I am using log4j for logging Our Application which will be into production in three weeks. Our Application will be deployed into remote location server We want to take help of lo4j if an user reports error while using the Application . Regarding this I have some questions * *What should be the path of the Log file generated ?? For example (log4j.appender.file.File=C:/app.log) *Should we use RollingFileAppender or DailyRollingFileAppender A: If your remote server is on windows then path for log file will suits in the C directory. else you can set any directory path and assign it to lo4j file like this #log4j.appender.InputFieldFileAppender.File=${logs.root.directory}\\loging.log DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. You can use InputFieldFileAppender if there is no special case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: linear layout orientation changes What i want is : * *In portrait mode : an imageView and a text below *In landscape mode : an imageView on the left and a text to the right How can i do that ? knowing that in my manifest there is a : android:configChanges="orientation|keyboardHidden" in this activity. A: You may use an alternative resource res/layout-port/ (or res/layout-land/) where you define your additional layout. It will be used when you have the specified orientation, otherwise it will fall back to the default layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set THTTPRio.Converter.Options to soLiteralParams in OnBeforeExecuteEvent This refer to the post Delphi SOAP Envelope and WCF. Could someone please post a sample code which can show me how to set soLiteralParams in THTTPRio.Converter.Options in Delphi 7. I have the following code currently. I have drag-dropped a HTTPRIO component into the document which has created a line HTTPRIO1: THTTPRIO at the beginning of the code. I basically want to understand how I set soLiteralParams in the above component. Following is the code I am trying to execute which is giving me error. procedure TForm1.CleanUpSOAP(const MethodName: String; var SOAPRequest: WideString); var RIO: THTTPRIO; begin //The following line is giving error // RIO.Converter.options := [soLiteralParams]; end; In the above code I have declared a variable RIO of the type THTTPRIO, which I am not sure is correct. A: Just guessing, as you provide very little information in your question. Use the variable assigned to the component you dropped on your form. Don't declare a new local one (which you never created anyway). To set the Converter.Options in code, you'll need to add OPToSOAPDomConv to your uses clause. implementation uses OPToSOAPDomConv; // BTW, this name might not be a good one if it's the // OnBeforeExecute event handler as that isn't // clear from the name. procedure TForm1.CleanUpSOAP(const MethodName: String; var SOAPRequest: WideString); begin // Note this clears any previous options! HTTPRIO1.Converter.Options := [soLiteralParams]; // If you want to keep the previous options instead of replacing them // HTTPRIO1.Converter1.Options := HTTPRIO1.Converter1.Options + [soLiteralParams]; end; If you've dropped the component on the form, I'm not sure why you're not handling this in the Object Inspector instead, however. If this doesn't solve the problem, edit your question and provide the exact error message you're receiving, including any memory addresses in the case of an exception being raised. A: I have cracked this. The issue was that I didn't refer to OPconvert.pas file, which contained the TSOAPConvertOption enumeration. I don't know whether copying this file into the same folder as my project files and referring to this in the "uses" section is the right way, but it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: If security is not an issue, is an immutable interface a good pattern? It is commonly suggested that immutable classes should be sealed, to enforce a promise to consumers that observed properties of the class will remain invariant. Certainly that would seem a good practice for classes that would be employed in security contexts. On the other hand, there are a number of cases where it may be useful to have a number of immutable classes with common base features, and also have editable versions of such classes. For example, a graphics program might have a DrawnText object which contains a location, font, and string, and a derivative DrawnFancyText string which adds parameters to curve text around a shape. It may be useful in some contexts to have immutable versions of those objects (e.g. for things like undo buffers), but in other contexts it may be more useful to have mutable versions. In such a context, there are some contexts where one will need a readable DrawnFancyText object but not care whether it's mutable or not, but there are others where one will need an immutable derivative of either DrawnText or DrawnFancyText but won't care which. Achieving the former would require EditableDrawnFancyText and ImmutableDrawnFancyText to have a common base; achieving the latter would require ImmutableDrawnText and ImmutableDrawnFancyText to have a common base. Unfortunately, such a pattern cannot be achieved without multiple inheritance since ImmutableDrawnText has no relationship to EditableDrawnFancyText. Fortunately, interfaces do allow multiple inheritance even though classes do not. It would seem the best way to achieve the proper inheritance relationship would be to define interfaces: * *IDrawnText *IDrawnFancyText : IDrawnText *IEditableDrawnText : IDrawnText *IEditableDrawnFancyText : IEditableDrawnText, IDrawnFancyText *IImmutableDrawnText : IDrawnText *IImmutableDrawnFancyText : IImmutableDrawnText, IIDrawnFancyText It would seem that having consumers of the class use interfaces rather than classes would achieve all of the proper object relationships. On the other hand, exposing interfaces would mean that consumers would have to trust that nobody implements a so-called "immutable" interface with an object that allows outside mutation. For non-security-sensitive information, would it be good to use interfaces so as to allow proper inheritance relations, and rely upon implementers not to violate contracts? Ideally, it would be possible to expose a public interface well enough to allow outside instances to be passed around, without having to allow outside code to define its own implementations. If that were doable, that would seem like the optimal approach. Unfortunately, while one can expose public abstract classes with 'internal'-qualified constructors, I'm unaware of any such ability with interfaces. Still, I'm not sure the possibility of someone implementing "IImmutableDrawnText" with an object that allows outside mutation is necessarily a real problem. Edit IDrawnText would only expose getters but not setters, but its documentation would explicitly state that objects implementing IDrawnText may or may not be mutable via other means; IImmutableDrawnText would expose the same members as IDrawnText, but the documentation would expressly state that classes which allow mutation are forbidden from implementing the interface. Nothing would prevent mutable classes from implementing IImmutableDrawnText in violation of the contract, but any and all such classes would be broken implementations of that interface. A: There's no such thing as an "immutable interface". There's an interface that doesn't declare methods that mutate the object, but no way for it to prohibit mutation. And allowing mutation allows all the thread-safety and "security" issues that go along with it. The reason immutable classes should be sealed, is that they make that promise that they can't (normally) be modified once created. A subclass can break that promise (and LSP along with it), and prohibiting inheritance is the only way to enforce the promise. BTW, immutability isn't for security. A language/framework that allows reflection (like, say, C#/.net?) can be used to modify the object virtually at will, ignoring everything the object's done to prevent it. Immutability mainly just makes that hard to do accidentally. A: An interface does not define mutability/immutability; rather, it only serves to constrain what the consumer can do. Just because an interface does not expose mutation facilities does not mean you should assume the object is immutable. For example, IEnumerable says nothing about a collection's immutability, but it is not a mutable interface. Basically: you would need to define that elsewhere - probably in documentation. If that way of splitting up the functionality helps with your domain, then: go for it! If it doesn't help, don't force it on yourself unnecessarily (never invent a requirement). Also: if a type is not sealed it can't really claim to be immutable, as the (base) type itself won't even know what is possible. Again, this may or may not be a real problem. A: You might look at the WPF Freezable class for inspiration if you want to implement this pattern. It is described as follows: Defines an object that has a modifiable state and a read-only (frozen) state. Classes that derive from Freezable provide detailed change notification, can be made immutable, and can clone themselves.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: No output when running C++ applications via Eclipse CDT IDE Eclipse can build my applications for me so far, and I can execute them directly (via Windows 7 Explorer), but I get no results when I use the run command via the CDT perspective. The console tab only tells me that the application terminated, even with a console app with input (cin >> and so forth). Win32 apps don't execute either. Once again I can execute them directly via the debug folder, so this must be an IDE issue. Is this normal? Or are there settings I could change to make it work? Thanks for any advice! A: Solved it! It's because my workspace was in the "Program Files" directory, which has a space in it. Probably a MinGW issue. Thanks to Keith Thompson for the help though!
{ "language": "en", "url": "https://stackoverflow.com/questions/7540500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ArrayAdapter custom view state gets repeated when scrolling I have a ListView that gets populated with custom view items. The custom view consists of an icon, a label and a checkbox. When I first create the list, everything displays as it should. If I scroll down the list, the icons and labels continue to be correct further down the list but the checkbox states start to get mixed up, displaying other items as checked besides the ones I chose. Example: My list starts with no checkboxes set as checked for any items. I see 10 items on screen. I toggle the checkbox on item 10. It updates appropriately. If I scroll down the list, I find that the checkbox for item 20, item 30, etc. start with the checkbox already toggled even though they were never visible to interact with. If I scroll back and forth repeatedly, more and more items in a non-identifiable pattern appear checked. List setup in my activity: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.default_list); profile = (Profile) i.getParcelableExtra("profile"); ArrayList<Application> apps = new ApplicationListRetriever(this).getApplications(true); adapter = new ApplicationsAdapter(this, R.layout.application_list_item, apps, getPackageManager(), profile); setListAdapter(adapter); } ApplicationsAdapter: public class ApplicationsAdapter extends ArrayAdapter<Application> { private ArrayList<Application> items; private PackageManager pm; private Profile profile; private ArrayList<ApplicationListener> listeners = new ArrayList<ApplicationListener>(); public ApplicationsAdapter(Context context, int textViewResourceId, ArrayList<Application> objects, PackageManager pm, Profile profile) { super(context, textViewResourceId, objects); this.pm = pm; items = objects; this.profile = profile; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater li = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = li.inflate(R.layout.application_list_item, null); } final Application info = items.get(position); if (info != null) { TextView text = (TextView) v.findViewById(R.id.label); CheckBox check = (CheckBox) v.findViewById(R.id.check); ImageView img = (ImageView) v.findViewById(R.id.application_icon); //see if the app already is associated and mark checkbox accordingly for (Application app : profile.getApps()) { if (info.getPackageName().equals(app.getPackageName())) { check.setChecked(true); break; } } check.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { for (ApplicationListener listener : listeners) { listener.applicationReceived(info, isChecked); } } }); try { text.setText(info.getName()); } catch (Exception ex) { Log.e("ApplicationsAdapter", "Label could not be set on adapter item", ex); } if (img != null) { try { img.setImageDrawable(pm.getApplicationIcon(info.getPackageName())); } catch (NameNotFoundException e) { e.printStackTrace(); } } } return v; } } List item layout: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/application_icon" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:layout_width="36dp" android:layout_height="36dp" android:paddingRight="3dp" android:adjustViewBounds="true" /> <TextView android:layout_width="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/application_icon" android:layout_height="wrap_content" android:id="@+id/label" android:text="Application Name" /> <CheckBox android:id="@+id/check" android:layout_centerVertical="true" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" /> </RelativeLayout> Also worth noting is if I set a breakpoint on the line where I call check.setChecked(true); it only hits that point if the original item I checked is on screen, never for any of the other items that display as checked. Any ideas why the later items would display as checked or what I can try to fix it? A: It is caused by View recycling. You should completely refresh the state of your View when getView is called. Although you are refreshing almost everything, you've forgotten one little thing. Suppose the list shows 5 items on screen and the second item is checked. The user then scrolls down a further 5 items - however due to view recycling they're really just the same 5 views as before the user scrolled, so the one of the items on-screen will still be checked even though it shouldn't be, because in your code above if no package is matched you are not setting the checkbox to unchecked (so it will stay checked), you are assuming it is already unchecked (which due to View recycling it may not be). The fix is simple: simply set the checkbox to unchecked before your logic to check if it need be checked: // Do not assume the checkbox is unchecked to begin with, it might not be // if this view was recycled, so force it to be unchecked by default and only // check it if needed. check.setChecked(false); for (Application app : profile.getApps()) { if (info.getPackageName().equals(app.getPackageName())) { check.setChecked(true); break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Restrict number of requests from an IP I am writing an application wherein its a requirements to restrict the number of logins a user can have from a single IP address (as a way to stop spam). We can't use captcha for some reason! The only 2 ways I could think of to make this work was to either store in the database, the number of requests coming in from each IP. OR To store a tracking cookie which has the information regarding the same. Now, the downside of the first mode is that there would be too much of db traffic - the application is going to be used by a ton of people. The downside of storing this info as a cookie is that users can clear them up ad start fresh again. I need suggestions, if there could be a way wherein the high db traffic and the loose bond with cookie based tracking can be handled. A: You're talking about "logins" and a web-application therefore you have some sort of a session persisted somwhere. When creating those sessions you need to keep track of the number of active sessions per IP and not allocate new sessions when that threshold is reached. Without more specific information about your framework / environment, that's about the best answer anyone can provide. Also be aware that this approach fails in numerous ways because of NAT (network address translation). For example, our office has exactly one public IP address for X hundred people. The internal network is on private IP space. A: if you want to get the IP and store somewhere, you could use $_SERVER['REMOTE_ADDR'] to get the IP of the user, make a field like "ip" in your database and you make a query in your SQL to check if the IP was used. There are also other ways of tracking, like Flash Cookie, people usually don't know the existance of it, so most people wouldn't know how to clear it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: FF Xpather to Nokogiri -- Can I just copy and paste? I was doing this manually and then I got stuck and I can't figure out why it's not working. I downloaded xpather and it is giving me: /html/body/center/table/tbody/tr[3]/td/table as the path to the item I want. I have manually confirmed that this is correct but when I paste it into my code, all it does is return nil Here is my code: a = parentdoc.at_xpath("//html/body/center/table/tbody/tr[3]/td/table[1]") puts a If I do something like this: a = parentdoc.at_xpath("//html/body/center") puts a I get a huge chunk of text from the page. I can keep adding elements until I hit tbody then it returns nil again. I even tried something like: //html/body/center/table/*/tr[3] and that did the same thing returning nil What am I missing? A: Your problem is that Firefox is inserting a <tbody> element that is not present in the HTML. When you use xpather, it is working from the HTML that the browser is using (rather than the raw HTML that ycombinator.com is returning) and it finds this path: //html/body/center/table/tbody/tr[3]/td/table Nokogiri will be working with the raw HTML so you want this //html/body/center/table/tr[3]/td/table When I apply that XPath to the URL in your comment: doc.at_xpath('//html/body/center/table/tr[3]/td/table').text I get this output: "csoghoian 1 hour ago | link | parent2 responses:1. Chrome is the only major browser not to ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7540506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Microsoft Office software as part of my web service backend? What licensing issues arise if I install and use Microsoft Office software (in this case Visio) as part of my web service backend? My company's flagship piece of software can convert Microsoft Visio files for use in their environment, but of course requires a local install of Visio to decode the files. The system I'm to create is to offer a sort of web service where people can upload their Visio files, and then we can show off the benefits of buying our full price software. In order to do this I'd need an install of our software on the server, as well as Visio. What I'm a little concerned about is technically any visitor to the site is technically using Visio. I can't really find any other examples when searching online (it doesn't help when things like "server", "cloud" are essentially buzzwords) so any advice would be greatly appreciated! A: I don't know the legal details but MS say if you do this every user would require a Visio Licence. You can certainly do it technically but MS also warn that office automation was intended to be done in an interactive session - I take this to mean they don't guarantee that its not going to pop up a dialog or something at some point. They provide server side options for most office products but not Visio. I don't know what your application is but I can think of three options that may be relevant: * *Create a downloadable application that opens Visio and converts the file to your internal format and then uploads it to your server *Have files uploaded to the server which then creates a task for someone in your company to download the file and do something with it. You could significantly automate this process *Get the users to upload VDX files and process the data as XML Note if your application is using Visio in such a way that you don't have your own internal data structure can you use option 1 and just have some of the functionality done on the server through authenticate web services? this way they get to see what it can do but it only works while connected to your server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: efficient line from hough transform coordinates i'm working with a hough transform (polar coordinates). i'd like to compute a vector representation of a line from a coordinate from the hough transform. my current implementation loops through all the pixel coordinates in the image from (0,0) to (M, N) where M and N are the size of the image. as the loop traverses the space, this value is computed: // angle and rho are the polar coordinates from hough space. tmp = (int) ( (i * cos( angle ) ) + ( j * sin(angle) ) ); where tmp - rho == 0, is part of the line, so i track that position. when the loop reaches the end of the image (i,j) == (M,N), the loop is done again from the opposite direction (M, N) to (0,0). the first (tmp-rho == 0) going left to right and the second (tmp-rho == 0) going right to left are the coordinates of the line. i then subtract those pixel coordinates to get a vector of the line in the hough space. this is terribly inefficient (slow) and i'm 100% sure there's a better way to compute this but, i can't seem to figure it out. any help would be greatly appreciated! A: You can solve your equation for i=0, i=M, j=0, j=N instead of looping rho = i * cos(angle) + j * sin(angle) i = 0 --> j1 = rho / sin(angle) i = M --> j2 = (rho - M*cos(angle)) / sin(angle) j = 0 --> i1 = rho / cos(angle) j = N --> i2 = (rho - N*sin(angle)) / cos(angle)
{ "language": "en", "url": "https://stackoverflow.com/questions/7540511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get systemtimestamp in Cassandra How will i get systemtimestamp from cassandra-cli like select sysdate from dual; in oracle. i am using cassandra in windows7. A: I'm not sure this makes sense for Cassandra. Each Cassandra node has its own system clock - these are distributed and independent so there is no inherent "system" time as such - but, the nodes and clients must be synchronized using NTP or similar, otherwise you may get out-of-order updates i.e. data corruption. When making updates, the client's timestamp is used, not the server's (again, NTP sync needed). See http://wiki.apache.org/cassandra/DataModel So the shared NTP clock is the only meaningful system time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQuery scrollTop() not doing anything My .scrollTop() is just not working. It's used in a function (which do get called - checked with an alert) but nothing happens. I tried: $(window).scrollTop(); $("html").scrollTop(); $(document).scrollTop(); I tried them separately and together, and it just doesn't do anything. All I need to do is let my page scroll to the top. Any tips and tricks? A: scrollTop() gets the current scroll top of an element but doesn't set it, try the jQuery ScrollTo plugin, it has the functionality you need. A: You need $("html, body").scrollTop(0); that is a cross-browser solution to scroll to the vertical position 0 (to the top). The way you are doing scrollTop() does nothing because its a getter that returns the current vertical position. A: $("body").scrollTop(); would work just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Exchange symetric keys between server and client in a secure way I have an algorithm that I believe to be secure. So the server creates a public and private key combination for every new connection. In this example I am just dealing with one thread but in reality I will have to construct several threads so that the server can be listening for multiple connections. The client is Alice and it also creates a public and private key combination. here is how the client Alice creates a random symmetric key to give to the server bob securely. server code (Bob) : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Security.Cryptography; using System.IO; namespace ServerListener { class Program { static TcpListener server; static CngKey bobKey; // server private key static byte[] alicePubKeyBlob; // client public key static byte[] bobPubKeyBlob; // server public key static byte[] symetricKey; // the symetric key that will later be used to transfer data more efficeintly static void Main(string[] args) { // create server private and public keys CreateKeys(); // start listening for new connections IPAddress ipAddress = IPAddress.Parse("192.168.0.120"); server = new TcpListener(ipAddress, 54540); server.Start(); var client = server.AcceptTcpClient(); // once a connection is established open the stream var stream = client.GetStream(); // we need the client public key so we need to instantiate it. alicePubKeyBlob = new byte[bobPubKeyBlob.Length]; // waint until the client send us his public key stream.Read(alicePubKeyBlob, 0, alicePubKeyBlob.Length); // alicePubKeyBlob should now be the client's public key // now let's send this servers public key to the client stream.Write(bobPubKeyBlob, 0, bobPubKeyBlob.Length); // encrytpedData will be the data that server will recive encrypted from the client with the server's public key byte[] encrytpedData = new byte[1024]; // wait until client sends that data stream.Read(encrytpedData, 0, encrytpedData.Length); // decrypt the symetric key with the private key of the server symetricKey = BobReceivesData(encrytpedData); // server and client should know have the same symetric key in order to send data more efficently and securely Console.Read(); } private static void CreateKeys() { //aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); //alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); } private static byte[] BobReceivesData(byte[] encryptedData) { Console.WriteLine("Bob receives encrypted data"); byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) iv[i] = encryptedData[i]; using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine("Bob creates this symmetric key with " + "Alices public key information: {0}", Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to: {0}", Encoding.UTF8.GetString(rawData)); } aes.Clear(); return rawData; } } } } Client code (Alice) : using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Security.Cryptography; using System.IO; namespace ClientAlice { class Program { static CngKey aliceKey; // client private key static byte[] alicePubKeyBlob; // client public key static byte[] bobPubKeyBlob; // server public key static byte[] symetricKey; // the symetric key that we want to give to the server securely static void Main(string[] args) { //create the client private and public keys CreateKeys(); // initialice the server's public key we will need it later bobPubKeyBlob = new byte[alicePubKeyBlob.Length]; // connect to the server and open a stream in order to comunicate with it TcpClient alice = new TcpClient("192.168.0.120", 54540); var stream = alice.GetStream(); // send to the server the public key (client's public key) stream.Write(alicePubKeyBlob, 0, alicePubKeyBlob.Length); // now wait to receive the server's public key stream.Read(bobPubKeyBlob, 0, bobPubKeyBlob.Length); // create a random symetric key symetricKey = new byte[1000]; Random r = new Random(); r.NextBytes(symetricKey); // Encrypt the symetric key with the server's public key byte[] encrytpedData = AliceSendsData(symetricKey); // once encrypted send that encrypted data to the server. The only one that is going to be able to unecrypt that will be the server stream.Write(encrytpedData, 0, encrytpedData.Length); // not the server and client should have the same symetric key } private static void CreateKeys() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); } private static byte[] AliceSendsData(byte[] rawData) { byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice creates this symmetric key with " + "Bobs public key information: {0}", Convert.ToBase64String(symmKey)); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { // create CryptoStream and encrypt data to send var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } } Console.WriteLine("Alice: message is encrypted: {0}", Convert.ToBase64String(encryptedData)); ; Console.WriteLine(); return encryptedData; } } } perhaps I should use the ssl connection. I think we learn a lot when creating this kind of programs. I want to know if this technique will be a secure way of Alice giving a symmetric key to Bob in a secure way. A: Your code is subject to man-in-the-middle attacks. SSL addresses this problem by relying on trusted third-party and validating the public key by checking the certificate chain up to the trusted root. So your best option is to (a) take SSL and use it, and (b) learn by reading security books (first) rather than by implementing your own algorithms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QtCreator 2.3--Lost ability to see QString contents in debugger So I recently upgraded to QtCreator 2.3 (and want to keep it for its QtQuick support) and initially debugger performance slowed to an unusable crawl (though I could still see QString contents). Googling around led me to install gdb 7.3.1, the latest stable release at this time, and that happily brought debugger stepping speed back up to usable levels. But now the debugger won't display the contents of a QString, just the address of the char array, and a lot of private members that don't tell me anything informative. Anybody know how I can get the debugger to display string contents again? I'm on Ubuntu 10.04. A: Check this http://developer.qt.nokia.com/forums/viewthread/6323 Edit: The page isn't available anymore, the domain is currently parked. @gshep Please replace the link if you can remember the title of the page and find another instance of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pollard-Rho Factorization Parallelization I recently stumbled upon a paper on a parallelization of Pollard's Rho algorithm, and given my specific application, in addition to the fact that I haven't attained the required level of math, I'm wondering if this particular parallelization method helps my specific case. I'm trying to find two factors—semiprimes—of a very large number. My assumption, based on what little I can understand of the paper, is that this parallelization works well on a number with lots of smaller factors, rather than on two very large factors. Is this true? Should I use this parallelization or use something else? Should I even use Pollard's Rho, or is there a better parallelization of a different factorization algorithm? A: The wikipedia article states two concrete examples: Number Original code Brent's modification 18446744073709551617 26 ms 5 ms 10023859281455311421 109 ms 31 ms First of all, run these two with your program and take a look at your times. If they are similar to this ("hard" numbers calculating 4-6 times longer), ask yourself if you can live with that. Or even better, use other algorithms like simple classic "brute force" factorization and look at the times they give. I guess they might have a hard-easy factor closer to 1, but worse absolute times, so it's a simple trade-off. Side note: Of course, parallelization is the way to go here, I guess you know that but I think it's important to emphasize. Also, it would help for the case that another approach lies between the Pollard-rho timings (e.g. Pollard-Rho 5-31 ms, different approach 15-17 ms) - in this case, consider running the 2 algorithms in seperate threads to do a "factorization race". In case you don't have an actual implementation of the algorithm yet, here are Python implementations. A: The basic idea in factoring large integers is to use a variety of methods, each with its own pluses and minuses. The usual plan is to start with trial division by primes to 1000 or 10000, followed by a few million Pollard rho steps; that ought to get you factors up to about twelve digits. At that point a few tests are in order: is the number a prime power or a perfect power (there are simple tests for those properties). If you still haven't factored the number, you know that it will be hard, so you will need heavy-duty tools. A useful next step is Pollard's p-1 method, followed by its close cousin the elliptic curve method. After a while, if that doesn't work, the only methods left are quadratic sieve or number field sieve, which are inherently parallel. The parallel rho method that you asked about isn't widely used today. As you suggested, Pollard rho is better suited to finding small factors rather than large ones. For a semi-prime, it's better to spend parallel cycles on one of the sieves than on Pollard rho. I recommend the factoring forum at mersenneforum.org for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to pass filename via intent, to be used in that activity's view i've a list of filename in a listactivity. when the user clicks on a filename that image should be loaded. i pass the filename via an intent, that bit works ok. the recieving activity can get the filename. this activity has a custom view and this is where the problem lies. The custom view should be able to stream the correct filename recieved in it's activity from the sdcard and display the resulting bitmap in the view. i can get the filename in the activity but the filename in the view is null. how can i get around this? thanks in advance Matt. package com.tecmark; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.view.WindowManager; public class ShowDistortion extends Activity{ private static final String TAG = "*********showdistortion"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.showdistortion); String fn = getIntent().getStringExtra("filename"); Log.e(TAG, "filename = " + fn); final ShowDistortedBitmap sdb = (ShowDistortedBitmap)findViewById(R.id.showdistortedbitmap); sdb.filename = fn; } } . package com.tecmark; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.os.Environment; import android.util.AttributeSet; import android.util.Log; import android.view.View; public class ShowDistortedBitmap extends View{ private static final String TAG = "*********ShowDistortedBitmap"; private File tempFile; private byte[] imageArray; private Bitmap finalBitmap; protected String filename; public ShowDistortedBitmap(Context context, AttributeSet attrs) { super(context, attrs); tempFile = new File(Environment.getExternalStorageDirectory(). getAbsolutePath() + "/"+filename); Log.e(TAG, "filename ====== "+filename); imageArray = new byte[(int)tempFile.length()]; try{ InputStream is = new FileInputStream(tempFile); BufferedInputStream bis = new BufferedInputStream(is); DataInputStream dis = new DataInputStream(bis); int i = 0; while (dis.available() > 0 ) { imageArray[i] = dis.readByte(); i++; } dis.close(); } catch (Exception e) { e.printStackTrace(); } finalBitmap = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length); if(finalBitmap == null){ Log.e(TAG, "finalbitmap = null"); }else{ Log.e(TAG, "finalbitmap = not null"); } } @Override public void onDraw(Canvas canvas){ super.onDraw(canvas); Log.e(TAG, "******about to draw finalBitmap "); canvas.drawBitmap(finalBitmap, 0, 0, null); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drag-drop text over DIV I have a div in my website, and when it's clicked upon, it reveals the search box (done with jQuery). However, I would like this div to accept drag'n'dropped text. In my use case, a user selects regular text from anywhere on the site, and drag'n'drops it to copy-paste it into the search box. If the search box was always visible, he could simply drop it into the text box, handled natively by the browser/OS. However, is there a way I could simulate the same thing with this div? The user would drop his text onto the div, and it would fire the click event to show the text box and paste the dropped text into the box. My website is uses Modernizr+jQuery+jQuery UI and HTML5/CSS3. IE6 compatibility is a non-issue. Thank you in advance! A: You can use the HTML5 Drag and Drop events: $('#dropTextHere').bind('drop', function (e) { var theDroppedText = e.originalEvent.dataTransfer.getData('Text'); }); You can read more about it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Best way to save a Parent object Just wondering what's the best-practice for saving a Parent that ordinarily contains a collection of Child objects (many-to-many in my case), but that collection in the Parent is currently set to null because it hasn't been loaded? In my case, the Parent is passed to my service layer from a Web page. The web page has only populated the Parent's simple attributes from a form. I know there are several Child objects linked to the Parent in the database, but the 'children' property is currently null. If I save the Parent, even though my of Children is set to cascade="none", when I save Parent, all the links are deleted (I can even see the delete statements NHibernate issues in the logs). I can think of several ways to solve this: 1) Load the children seperately and then set the Parent's child collection to them and then save the parent (works but this is an additional trip to the database). 2) Issue an update on ONLY the simple properties using HQL or Native SQL. Update: I'm not sure my cascade behaviour is working properly actually. From the docs, it suggests that NHibernate won't mess with my collection unless cascade is set to save-update, all-delete-orphan etc. But this is my mapping (from Order.hbm.xml) <bag name="OrderItems" table="order_item" cascade="none" lazy="true"> <key column ="order_id" /> <many-to-many class="MenuItem" column="item_id"/> </bag> When Order.OrderItems is null, and I save my Order object using SaveOrUpdate(Order), it definately deletes the collection. I want them to be preserved. Is my configuration wrong or something? Thanks A: I wouldn't actually use the real Parent object for passing data from UI to the service layer. You could instead implement a lightweight class (Data transfer object) that would contain just those basic properties and then pass it to the service tier and populate (either manually or using AutoMapper) the parent's properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SqlDependency.Start An attempt to attach an auto-named database for file failed iv'e got copy of NORTHWND.mdf along with NORTHWND.LOG in my App_Data folder MY CONNECTION STRING : <add name="northwind_connection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|NORTHWND.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> when i attempt to open and close the connection everything works out fine. string connStr = WebConfigurationManager.ConnectionStrings["northwind_connection"].ToString(); SqlConnection conn = new SqlConnection(connStr); SqlCommand command = new SqlCommand("Select * From Products"); command.Connection = conn; conn.Open(); SqlDataReader reader = command.ExecuteReader(); GridView1.DataSource = reader; GridView1.DataBind(); conn.Close(); now beside this code i want to add SqlCacheDependency to the page when i place the code : Shown in msdn SqlDependency.Start(connStr); I GET THE FOLLOWING ERROR : An attempt to attach an auto-named database for file C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\NORTHWND.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. any ideas why this happens , what do i need to configure for the SqlCacheDependency to work. thanks in advance eran. in addition i would like to add that if i change my connection string to a specific one <add name="northwind_connection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\NORTHWND.MDF; Integrated Security=True" providerName="System.Data.SqlClient" /> everything works as it should but that seems wrong since i don't expect users to change the connection string to their path , that's why i would like to put it in App_Data or at list give a relative path to .\SQLEXPRESS which also doesn't work : <add name="myConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=NORTHWND;Integrated Security=True;" providerName="System.Data.SqlClient"/> please shed some light on this issue there must be some configuration that makes this possible . thanks in advance. eran. A: I don't think you can use SqlCacheDependency with an auto-attach (SQLEXPRESS) type connection string. You need to attach the database in Management studio, and change your connection string to look like: server=(local);database=Northwind;Integrated Security=SSPI; Then you need to execute ALTER DATABASE NORTHWIND SET ENABLE_BROKER If you need to provide this kind of setup for users then you can write a SQL Script that will do it for them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Merging 2 Binary Search Trees How do you merge 2 Binary Search Trees in such a way that the resultant tree contains all the elements of both the trees and also maintains the BST property. I saw the solution provided in How to merge two BST's efficiently? However that solution involves converting into a Double Linked List. I was wondering if there is a more elegant way of doing this which could be done in place without the conversion. I came up with the following pseudocode. Does it work for all cases? Also I am having trouble with the 3rd case. node* merge(node* head1, node* head2) { if (!head1) return head2; if (!head2) return head1; // Case 1. if (head1->info > head2->info) { node* temp = head2->right; head2->right = NULL; head1->left = merge(head1->left, head2); head1 = merge(head1, temp); return head1; } else if (head1->info < head2->info) { // Case 2 // Similar to case 1. } else { // Case 3 // ... } } A: Assuming we have two trees A and B we insert root of tree A into tree B and using rotations move inserted root to become new root of tree B. Next we recursively merge left and right sub-trees of trees A and B. This algorithm takes into account both trees structure but insertion still depends on how balanced target tree is. You can use this idea to merge the two trees in O(n+m) time and O(1) space. The following implementation is due to Dzmitry Huba: // Converts tree to sorted singly linked list and appends it // to the head of the existing list and returns new head. // Left pointers are used as next pointer to form singly // linked list thus basically forming degenerate tree of // single left oriented branch. Head of the list points // to the node with greatest element. static TreeNode<T> ToSortedList<T>(TreeNode<T> tree, TreeNode<T> head) { if (tree == null) // Nothing to convert and append return head; // Do conversion using in order traversal // Convert first left sub-tree and append it to // existing list head = ToSortedList(tree.Left, head); // Append root to the list and use it as new head tree.Left = head; // Convert right sub-tree and append it to list // already containing left sub-tree and root return ToSortedList(tree.Right, tree); } // Merges two sorted singly linked lists into one and // calculates the size of merged list. Merged list uses // right pointers to form singly linked list thus forming // degenerate tree of single right oriented branch. // Head points to the node with smallest element. static TreeNode<T> MergeAsSortedLists<T>(TreeNode<T> left, TreeNode<T> right, IComparer<T> comparer, out int size) { TreeNode<T> head = null; size = 0; // See merge phase of merge sort for linked lists // with the only difference in that this implementations // reverts the list during merge while (left != null || right != null) { TreeNode<T> next; if (left == null) next = DetachAndAdvance(ref right); else if (right == null) next = DetachAndAdvance(ref left); else next = comparer.Compare(left.Value, right.Value) > 0 ? DetachAndAdvance(ref left) : DetachAndAdvance(ref right); next.Right = head; head = next; size++; } return head; } static TreeNode<T> DetachAndAdvance<T>(ref TreeNode<T> node) { var tmp = node; node = node.Left; tmp.Left = null; return tmp; } // Converts singly linked list into binary search tree // advancing list head to next unused list node and // returning created tree root static TreeNode<T> ToBinarySearchTree<T>(ref TreeNode<T> head, int size) { if (size == 0) // Zero sized list converts to null return null; TreeNode<T> root; if (size == 1) { // Unit sized list converts to a node with // left and right pointers set to null root = head; // Advance head to next node in list head = head.Right; // Left pointers were so only right needs to // be nullified root.Right = null; return root; } var leftSize = size / 2; var rightSize = size - leftSize - 1; // Create left substree out of half of list nodes var leftRoot = ToBinarySearchTree(ref head, leftSize); // List head now points to the root of the subtree // being created root = head; // Advance list head and the rest of the list will // be used to create right subtree head = head.Right; // Link left subtree to the root root.Left = leftRoot; // Create right subtree and link it to the root root.Right = ToBinarySearchTree(ref head, rightSize); return root; } public static TreeNode<T> Merge<T>(TreeNode<T> left, TreeNode<T> right, IComparer<T> comparer) { Contract.Requires(comparer != null); if (left == null || right == null) return left ?? right; // Convert both trees to sorted lists using original tree nodes var leftList = ToSortedList(left, null); var rightList = ToSortedList(right, null); int size; // Merge sorted lists and calculate merged list size var list = MergeAsSortedLists(leftList, rightList, comparer, out size); // Convert sorted list into optimal binary search tree return ToBinarySearchTree(ref list, size); } A: The best way we could merge the trees in place is something like: For each node n in first BST { Go down the 2nd tree and find the appropriate place to insert n Insert n there } Each iteration in the for loop is O(log n) since we are dealing with trees, and the for loop will be iterated n times, so in total we have O(n log n). A: The two binary search trees (BST) cannot be merged directly during a recursive traversal. Suppose we should merge Tree 1 and Tree 2 shown in the figure. The recursion should reduce the merging to a simpler situation. We cannot reduce the merging only to the respective left subtrees L1 and L2, because L2 can contain numbers larger than 10, so we would need to include the right subtree R1 into the process. But then we include numbers greater than 10 and possibly greater than 20, so we would need to include the right subtree R2 as well. A similar reasoning shows that we cannot simplify the merging by including subtrees from Tree 1 and from Tree 2 at the same time. The only possibility for reduction is to simplify only inside the respective trees. So, we can transform the trees to their right spines with sorted nodes: Now, we can merge the two spines easily into one spine. This spine is in fact a BST, so we could stop here. However, this BST is completely unbalanced, so we transform it to a balanced BST. The complexity is: Spine 1: time = O(n1), space = O(1) Spine 2: time = O(n2), space = O(1) Merge: time = O(n1+n2), space = O(1) Balance: time = O(n1+n2), space = O(1) Total: time = O(n1+n2), space = O(1) The complete running code is on http://ideone.com/RGBFQ. Here are the essential parts. The top level code is a follows: Node* merge(Node* n1, Node* n2) { Node *prev, *head1, *head2; prev = head1 = 0; spine(n1, prev, head1); prev = head2 = 0; spine(n2, prev, head2); return balance(mergeSpines(head1, head2)); } The auxiliary functions are for the tranformation to spines: void spine(Node *p, Node *& prev, Node *& head) { if (!p) return; spine(p->left, prev, head); if (prev) prev->right = p; else head = p; prev = p; p->left = 0; spine(p->right, prev, head); } Merging of the spines: void advance(Node*& last, Node*& n) { last->right = n; last = n; n = n->right; } Node* mergeSpines(Node* n1, Node* n2) { Node head; Node* last = &head; while (n1 || n2) { if (!n1) advance(last, n2); else if (!n2) advance(last, n1); else if (n1->info < n2->info) advance(last, n1); else if (n1->info > n2->info) advance(last, n2); else { advance(last, n1); printf("Duplicate key skipped %d \n", n2->info); n2 = n2->right; } } return head.right; } Balancing: Node* balance(Node *& list, int start, int end) { if (start > end) return NULL; int mid = start + (end - start) / 2; Node *leftChild = balance(list, start, mid-1); Node *parent = list; parent->left = leftChild; list = list->right; parent->right = balance(list, mid+1, end); return parent; } Node* balance(Node *head) { int size = 0; for (Node* n = head; n; n = n->right) ++size; return balance(head, 0, size-1); } A: A BST is a ordered or sorted binary tree. My algorithm would be to simple : * *traverse through both trees *compare the values *insert the smaller of the two into a new BST. The python code for traversing is as follows: def traverse_binary_tree(node, callback): if node is None: return traverse_binary_tree(node.leftChild, callback) callback(node.value) traverse_binary_tree(node.rightChild, callback) The cost for traversing through the BST and building a new merged BST would remain O(n) A: This blog post provides a solution to the problem with O(logn) space complexity. (Pay attention that the given approach does not modify input trees.) A: This can be done in 3 steps: * *covert the BSTs to sorted linked list (this can be done in place with O(m+n) time) *Merge this two sorted linked lists to a single list (this can be done in place with O(m+n) time) *Convert sorted linked list to balanced BST (this can be done in place with O(m+n) time) A: Here is what I would do. This solution is O(n1+n2) time complexity. STEPS: * *Perform the inorder traversal of both the trees to get sorted arrays --> linear time *Merge the two arrays --> again linear time *Convert the merged array into a Balanced binary search tree --> again linear time This would require O(n1+n2) time and space. Links you may find useful while implementing: * *How to merge 2 sorted arrays *Inorder traversal *Sorted array to a balanced BST A: The following algorithm is from Algorithms in C++. The idea is almost the same as in the algorithm posted by PengOne. This algorithm does in place merging, time complexity is O(n+m). link join(link a, link b) { if (b == 0) return a; if (a == 0) return b; insert(b, a->item); b->left = join(a->left, b->left); b->right = join(a->right, b->right); delete a; return b; } insert just inserts an item in the right place in the tree. void insert(link &h, Item x) { if (h == 0) { h = new node(x); return; } if (x.key() < h->item.key()) { insert(h->left, x); rotateRight(h); } else { insert(h->right, x); rotateLeft(h); } } rotateRight and rotateLeft keep tree in the right order. void rotateRight(link &h) { link x = h->left; h->left = x->right; x->right = h; h = x; } void rotateLeft(link &h) { link x = h->right; h->right = x->left; x->left = h; h = x; } Here link is node *. A: Assuming the question is just to print sorted from both BSTs. Then the easier way is, * *Store inorder traversal of 2 BSTs in 2 seperate arrays. *Now the problem reduces to merging\printing elements from 2 sorted arrays, which we got from step one. This merging can be done in o(m) when m>n or o(n) when m Complexity: o(m+n) Aux space: o(m+n) for the 2 arrays A: MergeTwoBST_to_BalancedBST.java public class MergeTwoBST_to_BalancedBST { // arr1 and arr2 are the input arrays to be converted into a binary search // structure and then merged and then balanced. int[] arr1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }; int[] arr2 = new int[] { 11, 12, 13, 14, 15, 16, 17, 18 }; BSTNode root1; BSTNode root2; // vector object to hold the nodes from the merged unbalanced binary search // tree. Vector<BSTNode> vNodes = new Vector<BSTNode>(); /** * Constructor to initialize the Binary Search Tree root nodes to start * processing. This constructor creates two trees from two given sorted * array inputs. root1 tree from arr1 and root2 tree from arr2. * * Once we are done with creating the tree, we are traversing the tree in * inorder format, to verify whether nodes are inserted properly or not. An * inorder traversal should give us the nodes in a sorted order. */ public MergeTwoBST_to_BalancedBST() { // passing 0 as the startIndex and arr1.length-1 as the endIndex. root1 = getBSTFromSortedArray(arr1, 0, arr1.length - 1); System.out.println("\nPrinting the first binary search tree"); inorder(root1); // traverse the tree in inorder format to verify whether // nodes are inserted correctly or not. // passing 0 as the startIndex and arr2.length-1 as the endIndex. root2 = getBSTFromSortedArray(arr2, 0, arr2.length - 1); System.out.println("\nPrinting the second binary search tree"); inorder(root2); // same here - checking whether the nodes are inserted // properly or not. } /** * Method to traverse the tree in inorder format. Where it traverses the * left child first, then root and then right child. * * @param node */ public void inorder(BSTNode node) { if (null != node) { inorder(node.getLeft()); System.out.print(node.getData() + " "); inorder(node.getRight()); } } /** * Method to traverse the tree in preorder format. Where it traverses the * root node first, then left child and then right child. * * @param node */ public void preorder(BSTNode node) { if (null != node) { System.out.print(node.getData() + " "); preorder(node.getLeft()); preorder(node.getRight()); } } /** * Creating a new Binary Search Tree object from a sorted array and * returning the root of the newly created node for further processing. * * @param arr * @param startIndex * @param endIndex * @return */ public BSTNode getBSTFromSortedArray(int[] arr, int startIndex, int endIndex) { if (startIndex > endIndex) { return null; } int middleIndex = startIndex + (endIndex - startIndex) / 2; BSTNode node = new BSTNode(arr[middleIndex]); node.setLeft(getBSTFromSortedArray(arr, startIndex, middleIndex - 1)); node.setRight(getBSTFromSortedArray(arr, middleIndex + 1, endIndex)); return node; } /** * This method involves two operation. First - it adds the nodes from root1 * tree to root2 tree, and hence we get a merged root2 tree.Second - it * balances the merged root2 tree with the help of a vector object which can * contain objects only of BSTNode type. */ public void mergeTwoBinarySearchTree() { // First operation - merging the trees. root1 with root2 merging should // give us a new root2 tree. addUtil(root1); System.out.println("\nAfter the root1 tree nodes are added to root2"); System.out.println("Inorder Traversal of root2 nodes"); inorder(root2); // inorder traversal of the root2 tree should display // the nodes in a sorted order. System.out.println("\nPreorder traversal of root2 nodes"); preorder(root2); // Second operation - this will take care of balancing the merged binary // search trees. balancedTheMergedBST(); } /** * Here we are doing two operations. First operation involves, adding nodes * from root2 tree to the vector object. Second operation involves, creating * the Balanced binary search tree from the vector objects. */ public void balancedTheMergedBST() { // First operation : adding nodes to the vector object addNodesToVector(root2, vNodes); int vSize = vNodes.size(); // Second operation : getting a balanced binary search tree BSTNode node = getBalancedBSTFromVector(vNodes, 0, vSize - 1); System.out .println("\n********************************************************"); System.out.println("After balancing the merged trees"); System.out.println("\nInorder Traversal of nodes"); inorder(node); // traversing the tree in inoder process should give us // the output in sorted order ascending System.out.println("\nPreorder traversal of root2 nodes"); preorder(node); } /** * This method will provide us a Balanced Binary Search Tree. Elements of * the root2 tree has been added to the vector object. It is parsed * recursively to create a balanced tree. * * @param vNodes * @param startIndex * @param endIndex * @return */ public BSTNode getBalancedBSTFromVector(Vector<BSTNode> vNodes, int startIndex, int endIndex) { if (startIndex > endIndex) { return null; } int middleIndex = startIndex + (endIndex - startIndex) / 2; BSTNode node = vNodes.get(middleIndex); node.setLeft(getBalancedBSTFromVector(vNodes, startIndex, middleIndex - 1)); node.setRight(getBalancedBSTFromVector(vNodes, middleIndex + 1, endIndex)); return node; } /** * This method traverse the tree in inorder process and adds each node from * root2 to the vector object vNodes object only accepts objects of BSTNode * type. * * @param node * @param vNodes */ public void addNodesToVector(BSTNode node, Vector<BSTNode> vNodes) { if (null != node) { addNodesToVector(node.getLeft(), vNodes); // here we are adding the node in the vector object. vNodes.add(node); addNodesToVector(node.getRight(), vNodes); } } /** * This method traverse the root1 tree in inorder process and add the nodes * in the root2 tree based on their value * * @param node */ public void addUtil(BSTNode node) { if (null != node) { addUtil(node.getLeft()); mergeToSecondTree(root2, node.getData()); addUtil(node.getRight()); } } /** * This method adds the nodes found from root1 tree as part it's inorder * traversal and add it to the second tree. * * This method follows simple Binary Search Tree inserstion logic to insert * a node considering the tree already exists. * * @param node * @param data * @return */ public BSTNode mergeToSecondTree(BSTNode node, int data) { if (null == node) { node = new BSTNode(data); } else { if (data < node.getData()) { node.setLeft(mergeToSecondTree(node.getLeft(), data)); } else if (data > node.getData()) { node.setRight(mergeToSecondTree(node.getRight(), data)); } } return node; } /** * * @param args */ public static void main(String[] args) { MergeTwoBST_to_BalancedBST mergeTwoBST = new MergeTwoBST_to_BalancedBST(); mergeTwoBST.mergeTwoBinarySearchTree(); } } BSTNode.java: public class BSTNode { BSTNode left, right; int data; /* Default constructor */ public BSTNode() { left = null; right = null; data = 0; } /* Constructor */ public BSTNode(int data) { left = null; right = null; this.data = data; } public BSTNode getLeft() { return left; } public void setLeft(BSTNode left) { this.left = left; } public BSTNode getRight() { return right; } public void setRight(BSTNode right) { this.right = right; } public int getData() { return data; } public void setData(int data) { this.data = data; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Implementing fa unction that adds and sorts data in a singly linked list (addsort)? I'm very new to C++ so it's a bit hard to understand the syntax sometimes. Anyways, I'm supposed to implement a function that adds and sorts the data given into a linked list. For example if I pass 2 into the list [1,4,5] then I should get [1,2,4,5] Here is what I have written so far, and no it does not work, I keep getting "blah blah not declared in this scope" void addSorted(Data * ){ temp = 0; if (head == NULL) { head = new LinkNode(newData); } else { LinkNode * current = head; while (current->next != NULL) { current = current->next; } if(current->data > current->next->data){ temp = current->data; current->data = current->next->data; current->next->data = temp; } current->next = new LinkNode(newData); } } Someone please help me, I'm using the struct LinkNode I think which is already given, in addition to a bunch of other functions like add, insert, remove, get, and size I'm not looking to just get the answer, I need to know why what I have isn't working. A: Hope that you have really put your effort in it..I am posting the whole function for inserting data into list in sorted order which I had written long time back void addData(node * head, int data){ if(head == NULL) { // First node node * temp = new node; temp -> data = data; temp -> next = NULL; head = temp; root = head; }else{ node * prev = NULL; while(head -> next != NULL){ // Sorted Addition Logic is HERE if(data >= head -> data){ prev = head; head = head -> next; continue; }else{ node * temp = new node; temp -> data = data; temp -> next = head; if(prev != NULL) prev -> next = temp; else head = temp; break; } } if(head -> next == NULL){ node * temp = new node; temp -> data = data; head -> next = temp; temp -> next = NULL; } } } Seeing your code, it seems that your logic itself is wrong...you are always ending on the last node (while loop) and in the next if statment you are trying to compare the data of the next node which is not present
{ "language": "en", "url": "https://stackoverflow.com/questions/7540554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Classic ASP Session/IIS Reset Bug in IIS 7? I have an application in classic asp running on IIS 7. The website uses global ASA (Application_OnStart and Session_OnEnd, the others are not being used) The problem is this. When one user logs in/out, sometimes the entire site does some sort of IIS reset and all the visitors of that site will have their sessions all reset. If any visitor was logged, it kicks them out and they have to login again. There is some sort of activity triggering this mass session reset, or better yet, IIS reset, because it only happens sometimes. I am not sure what could be causing it.. Any suggestions? A: Use the "Recycling..." action on the relevant Application pool in IIS Manager to check the Recycling conditions. Anything that causes recycling of the application pool will result in the loss of all current sessions. Use the same dialog to turn on logging of recycles (if not already on). Use event log to track any recycles and their cause. A: Internet Information Services (IIS) application pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks. Please check this event id on technet. It explains a bit more. If you disable recycle settings and your application is buggy then there is lots of chances of your website getting down. Recently I also increased the session timeout of my website but it was timing out 12:45 irrespective of ilde time out. Hence I shifted the recycle settings to 20:00 during non buiness hours. So that it can clear all the unwanted app pools.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hierarchy in array (php) -> how to get parent? I have a hierarchy in array and i'd like to know how can i "move" from children to parent. Is there a better way to work with php and hierarchy? I'd like to avoid using recursive steps for each child i need to check a parent. Is there a class or something similar? As exists with xml? A: Spl comes with various data structures. Perhaps you are looking for one of them : http://fr2.php.net/manual/en/spl.datastructures.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7540558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: iLO3: Multiple SSH commands is there a way to run multiple commands in HPs integrated Lights-Out 3 system via SSH? I can login to iLO and run a command line by line, but I need to create a small shell-script, to connect to iLO and to run some commands one by one. This is the line I use, to get information about the iLO-version: /usr/bin/ssh -i dsa_key administrator@<iLO-IP> "version" Now, how can I do something like this? /usr/bin/ssh -i dsa_key administrator@<iLO-IP> "version" "show /map1 license" "start /system1" This doesn't work, because iLO thinks it's all one command. But I need something to login into iLO, run these commands and then exit from iLO. It takes too much time to run them one after the other because every login into iLO-SSH takes ~5-6 seconds (5 commands = 5*5 seconds...). I've also tried to seperate the commands directly in iLO after manual login but there is no way to use multiple commands in one line. Seems like one command is finished by pressing return. iLO-SSH Version is: SM-CLP Version 1.0 The following solutions did NOT work: /usr/bin/ssh -i dsa_key administrator@<iLO-IP> "version; show /map1 license; start /system1" /usr/bin/ssh -i dsa_key administrator@<iLO-IP> "version && show /map1 license && start /system1" A: This Python module is for HP iLO Management. check it out http://pypi.python.org/pypi/python-hpilo/ A: Try putting your commands in a file (named theFile in this example): version show /map1 license start /system1 Then: ssh -i dsa_key administrator@iLO-IP < theFile Semicolons and such won't work because you're using the iLO shell on the other side, not a normal *nix shell. So above I redirect the file, with newlines intact, as if you were typing all that into the session by hand. I hope it works. A: You are trying to treat iLO like it's a normal shell, but its really HP's dopy interface. That being said, the easiest way is to put all the commands in a file and then pipe it to ssh (sending all of the newline characters): echo -e "version\nshow /map1 license\nstart /system1" | /usr/bin/ssh -i dsa_key administrator@<iLO-IP> A: That's a messy workaround, but would you might fancy using expect? Your script in expect would look something like that: # Make an ssh connection spawn ssh -i dsa_key administrator@<iLO-IP> # Wait for command prompt to appear expect "$" # Send your first command send "version\r" # Wait for command prompt to appear expect "$" # Send your second command send "show /map1 license\r" # Etc... On the bright side, it's guaranteed to work. On the darker side, it's a pretty clumsy workaround, very prone to breaking if something goes not the way it should (for example, command prompt character would appear in version output, or something like that). A: I'm on the same case and wish to avoid to run a lot of plink commands. So I've seen you can add a file with the -m option but apparently it executes just one command at time :-( plink -ssh Administrator@AddressIP -pw password -m test.txt What's the purpose of the file ? Is there a special format for this file ? My current text file looks like below: set /map1/oemhp_dircfg1 oemhp_usercntxt1=CN=TEST set /map1/oemhp_dircfg1 oemhp_usercntxt2=CN=TEST2 ... Is there a solution to execute these two commands ? A: I had similar issues and ended up using the "RIBCL over HTTPS" interface to the iLO. This has advantages in that it is much more responsive than logging in/out over ssh. Using curl or another command-line HTTP client try: USERNAME=<YOUR_ILO_USERNAME> PASSWORD=<YOUR_ILO_PASSWORD> ILO_URL=https://<YOUR_ILO_IP>/ribcl curl -k -X POST -d "<RIBCL VERSION=\"2.0\"> <LOGIN USER_LOGIN=\"${USERNAME}\" PASSWORD=\"${PASSWORD}\"> <RIB_INFO MODE="READ"> <GET_FW_VERSION/> <GET_ALL_LICENSES/> </RIB_INFO> <SERVER_INFO MODE=\"write\"> <SET_HOST_POWER HOST_POWER=\"Yes\"> </SERVER_INFO> </LOGIN> </RIBCL>" ${ILO_URL} The formatting isn't exactly the same, but if you have the ability to access the iLO via HTTPS instead of only ssh, this may give you some flexibility. More details on the various RIBCL commands and options may be found at HP iLO 3 Scripting Guide (PDF).
{ "language": "en", "url": "https://stackoverflow.com/questions/7540566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UISwitch customization? Is possible to add images to an UISwitch background,like when the state is ON (be one background) and when the state is OFF (another background image)? A: To change the background color (not image) all you have to do is below. This changes the off color for all UISwitch controls in realm. [[UISwitch appearance] setTintColor:[UIColor brownColor]];//Off Color _locationSwitch.onTintColor = [UIColor orangeColor];//On Color If you want to use image, use the following cool hack of using the segmented control. https://stackoverflow.com/a/5088099/1705353 If you want to write a lot of code, you can write your own control. Valeriy Van pointed to: https://github.com/homick/iPhone-Snippets/tree/master/General Also another resource is: http://www.raywenderlich.com/23424/photoshop-for-developers-creating-a-custom-uiswitch with code at: http://cdn2.raywenderlich.com/wp-content/uploads/2012/10/CustomSwitchResources.zip A: I would like to suggest you to follow Custom UISwitch & App Store approval to have a better idea, which is suggesting you to create a custom switch control. A: You can recreate a custom UISwitch by subclassing UIControl. By doing this you can have full control over what the switch looks like. You can look take a look at SevenSwitch. A custom UISwitch replacement I've created. The on/off colors can be customized to your liking. https://github.com/bvogelzang/SevenSwitch
{ "language": "en", "url": "https://stackoverflow.com/questions/7540569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sphinx delta index ignoring main index I have a really strange problem where for some reason my indexes simply do not function as they should. I have built a fully working delta index in Sphinx with full cron jobs to keep it all in shape and everything is fine. Then I come to query in PHP with: class sphinx_searcher{ function __construct(){ $config = array('host'=>'localhost', 'port'=>9312); $this->sphinx = new SphinxClient(); $this->sphinx->SetServer ( $config['host'], $config['port'] ); $this->sphinx->SetConnectTimeout ( 1 ); } function query(){ $this->sphinx->SetSortMode(SPH_SORT_RELEVANCE); $this->sphinx->SetLimits(0, 20); // Testing first page $this->sphinx->SetRankingMode(SPH_RANK_PROXIMITY_BM25); $this->sphinx->SetArrayResult ( true ); $res = $this->sphinx->Query("040*", "media media_delta"); if($res) return $res; else return $this->sphinx->GetLastError(); } } For some reason it takes one or the other index (so far only the latter). When I query by media alone I get doc id 1 and 2 but when I query by both I get only doc id 3 which is in the delta index. Here is my data source config: source media { type = mysql sql_query_pre = SET NAMES utf8 sql_query_pre = REPLACE INTO sph_counter SELECT 1, MAX(id) FROM documents sql_query = \ SELECT id, deleted, _id, uid, listing, title, description, tags, author_name, playlist, UNIX_TIMESTAMP(date_uploaded) AS date_uploaded \ FROM documents \ WHERE id<=( SELECT max_doc_id FROM sph_counter WHERE counter_id=1 ) sql_field_string = tags sql_field_string = description sql_field_string = author_name sql_field_string = title sql_attr_uint = deleted sql_attr_string = _id sql_attr_string = uid sql_attr_string = listing sql_attr_uint = playlist sql_attr_timestamp = date_uploaded sql_ranged_throttle = 0 sql_query_info = SELECT * FROM media WHERE id=$id sql_query_killlist = SELECT id FROM documents WHERE deleted = 0 } source media_delta : media { sql_query_pre = SET NAMES utf8 sql_query = \ SELECT id, deleted, _id, uid, listing, title, description, tags, author_name, playlist, UNIX_TIMESTAMP(date_uploaded) AS date_uploaded \ FROM documents \ WHERE id>( SELECT max_doc_id FROM sph_counter WHERE counter_id=1 ) } Here is my index config: index media { source = media path = /home/sam/sphinx/var/data/media docinfo = extern mlock = 0 morphology = stem_en, stem_ru, soundex min_word_len = 1 charset_type = sbcs min_infix_len = 2 infix_fields = title, tags enable_star = 1 expand_keywords = 1 html_strip = 0 index_exact_words = 1 } index media_delta : media { source = media_delta path = /home/sam/sphinx/var/data/media_delta } I am really confused as to what I have got wrong and am hoping some one here could help me find out what is wrong? EDIT: Out of using all Indexes: array(9) { ["error"]=> string(0) "" ["warning"]=> string(0) "" ["status"]=> int(0) ["fields"]=> array(4) { [0]=> string(5) "title" [1]=> string(11) "description" [2]=> string(4) "tags" [3]=> string(11) "author_name" } ["attrs"]=> array(10) { ["deleted"]=> int(1) ["_id"]=> int(7) ["uid"]=> int(7) ["listing"]=> int(7) ["title"]=> int(7) ["description"]=> int(7) ["tags"]=> int(7) ["author_name"]=> int(7) ["playlist"]=> int(1) ["date_uploaded"]=> int(2) } ["total"]=> string(1) "0" ["total_found"]=> string(1) "0" ["time"]=> string(5) "0.000" ["words"]=> array(1) { ["040*"]=> array(2) { ["docs"]=> string(1) "2" ["hits"]=> string(1) "2" } } } Thanks, A: After working though a few possiblities, spotted the issue, sql_query_killlist = SELECT id FROM documents WHERE deleted = 0 That says any document with "deleted=0" will disappear. I.e. will be "killed". I suppose in this context its confusing the 'hit' is still counted in the "words" array. Despite been later killed. (the words array is the raw number before any filtering - its direct from the index - so any setFilter (or in this case the kill-list) will make it an overestimate) So change it to WHERE deleted = 1 :) Always the most unexpected of things!
{ "language": "en", "url": "https://stackoverflow.com/questions/7540571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is there a way to do "git log -n 100 -from 200"? Is there a way to do like paginated retrieval of commit history like git log -n 100 -from 200? It would fetch 100 commits after the first 200th commit. Is there such a feature? A: You can do that with: git log -n 100 --skip=200 The documentation for these options can be found here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: comparing two vector images I want to compare two vector images (say SVG) and see how close they are. Basically, I want to test the correctness of a tracing algorithm which converts raster images to vector format. The way I am thinking to test this algorithm is: -Take some vector images. -Rasterize the vector image to png. -Feed the above png to tracing algorithm. -Compare the output of tracing program (which is SVG) with the original one. While I know there are some metrices for raster images like RMSE (in imagemagick), I am not familiar if there are some standard metrices for vector formats. I can think of some simple ones like number of arcs, lines, curves etc. But these can not detect the deviation in geometry and colors. Could someone suggest a good standard metric or some other approach to this problem. A: I am not aware of standard metrics for this, but I do have a pointer that I hope will be helpful. The Batik project uses a set of tools to test that its rendering of SVG documents does not diverge excessively from a set of reference images. My understanding is that it essentially rasterises the SVG and performs a pixel-based diff of the two images to see how they differ. It ought to be smart enough to overlook unavoidable differences that may stem for instance from subtle differences in antialiasing. You can read more about it (especially the SVGRenderingAccuracyTest section) at: http://jpfop.sourceforge.net/jaxml-batik/html-docs/test.html. That, of course, means that you'll be doing raster comparisons and not vector comparisons. Vector comparisons in your case will be fiendishly difficult because entirely different curves may produce extremely similar rendering — something which I assume is fine. What's more, the input may have a shape that is hidden behind another, making it impossible for the output to possibly guess what it is. The output will therefore end up showing as entirely wrong even though it may produce a pixel-perfect equivalent rendering. If however you do wish to perform vector comparisons (perhaps your data is constrained in a manner that makes this more viable) the simplest may be to first normalise both SVGs (convert all shapes to paths, eliminate all metadata, apply inheritance of all properties and normalise their values, normalise path data to always use the same form, etc.) and use this for two purposes: first, to look at the diffs in the normalised tree structure. That should already give you some useful information. Second, if you feel brave, measure the surface of the difference between individual curves. I would think twice about embarking on the latter though, because it is likely to give you lots of false negatives.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: PhoneGap -- or something else? For iOS app utilizing Swipes and Pinches My iOS app needs to utilize "swipes" gestures and "pinches". I'd rather not develop native iOS app myself, but use some tool like PhoneGap or anything like that. I want this to be pretty much a Web app, as much as possible, so I don'd deal with constant forever-taking updates thru App Store. Any suggestions? Thanks! A: To answer your question, yes PhoneGap can work with swipe. I just got done trying it with jQuery Mobile to answer this questions here: How to swipe between several jquery mobile pages? As for Pinch. The Mobile Safari browser that works inside of PhoneGap supports it, so I suspect that you would be able to use it in the same context as you would in a normal mobile web application. Pinch to zoom, double tap to Zoom and center to a block element. I do not believe that PhoneGap or JQuery Mobile give you access to any pinch events to intercept and do your own thing with, like "pinch to make a noise" or something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cluetip plug-in on jQuery loaded nods This is the scenario: The user clicks on e.g. a button, that loads (using jQuery) a node, e.g. '<span id="selected" title="|click to reselect">selected: #' + id + '</span>' Then goes jQuery (for cluetip) code: $('#selected').cluetip({splitTitle: '|', showTitle: false}); Cluetip applied to that jQuery loaded node does not fire. Anyone knows the solution? Much appreciated. A: Here's an example: $('#button').click(function () { $('#container').append('<span id="selected">...</span>'); $('#selected').cluetip(); }); A: Try putting your reference to ClueTip at the bottom of your page, not in the header. <script type="text/javascript" src="cluetip url here"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7540577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Process.Start will not launch chrome I'm having trouble getting Process.Start to launch chrome. If chrome is set as the default browser - nothing is opened. I also have tried providing two argument ex: Process.Start("chrome",url) Process.Start("PathToChrome",url) Process.Start("chrome.exe",url) None of those work either. It works fine when IE or Firefox are the default browser. This same problem has been reproduced on two computers. A: A shot in the dark, but: Since you tagged this question "windows installer", it occurs to me you may have been calling Process.Start() in a custom installer. If so, is the setup project property InstallAllUsers set to true? If so, set it to false and Process.Start(someUrl) should work correctly, even if Chrome is the default browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am working with arrays and need to sort the array. This array keeps showing out of range exceptions I have established an array and a large textbox which displays the array. Basically, you enter a name, 4 quarterly sales figures and it calculates the yearly total. I am now starting on the sort button. This would sort given columns numbers from most to least. I have gotten an if statement that looks like it should work for column five (the total column). I keep getting an out of range exception and am not sure why. Any ideas out there? I am sure this is a simple problem I am not seeing. do { swapFlag = false; for (n=0; n < lastIndexUsed; n++) { if (quarters[n, sortCol] < quarters[n+1, sortCol]) { //Column 5 temp = quarters[n,5]; quarters[n,5] = quarters[n +1, 3]; quarters[n +1, 3] = temp; //swapflag swapFlag = true; } } } while (swapFlag); This shows how I get 0-5 for sortCol: if (rbRegion.Checked) sortCol = 0; if (rb1.Checked) sortCol = 1; if (rb2.Checked) sortCol = 2; if (rb3.Checked) sortCol = 3; if (rb4.Checked) sortCol = 4; if (rbTotal.Checked) sortCol = 5; Button Variables: int n; int temp; int sortCol = 0; string ntemp; bool swapFlag; Global Variables int lastIndexUsed = -1; int[,] quarters = new int[10, 5]; string[] Branch = new string[10]; A: quarters is defined as int[,] quarters = new int[10, 5]; since arrays are zero based this gives you index 0...4 on the second dimension but you are trying to access index 5: temp = quarters[n,5]; A: It seems to me, that you could have n = quaters.size - 1, and therefore n + 1 = quaters.size. So it gets out of array's bound. A: I smell the problem is with these: quarters[n+1, sortCol] quarters[n+1, 3] Make sure n+1 is a valid index. What if lastIndexUsed itself is the maximum valid index? Then n+1 would cause IndexOutOfRangeException. A: I'd suggest to use more instances of List<int> quartersSortCol0 and use if (rbRegion.Checked) quartersSortCol0.Sort() and avoid ineffective constructions like your "while-for" above. While you can use overload of Sort method with custom comparison.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How can I create a new DataGridView control for each new row in another datagridview in vb.net? I have a DataGridView control (DataGridView6) that displays a list of managers. I want to generate a new DataGridView everytime I add a new manager to the list and put it in a specific place on my form. EDIT: say if i have a main datagridview, and i want to add another datagridview of the same size directly below it, how would i achieve this using the event handler method described in your answer below? im not sure if this is the most efficient way of displaying new members in the program though... How do can I do this as simply as possible? A: Use the DataGridView's "RowsAdded" event. Every time you add a new row (ie manager) to DataGridView6, have the event handler create a new DataGridView and place it where you want it. It's hard to give a more detailed answer without the specifics of your implementation, but something like that should work. EDIT - So something like this? DataGridView dgv = new DataGridView(); dgv.Location = new Point(DataGridView6.Location.X,DataGridView6.Location.Y + <somevalue>); If you need to keep adding them below this, you could just make a variable NextY that you increment each time you add a new one. You can store them all in a LinkedList or something similar so you can access them easily in order. A: I'm not very good at VB, so I've written it in C# first: DataGridView DataGridView6; DataGridView DataGridView7; DataGridViewRow CreateRow(object data) { DataGridViewRow row = null; int index = DataGridView6.Rows.Add(); row = DataGridView6.Rows[index]; // row.Cells[0] = something; // basically, add your date return row; } void DisplayManagerRow(DataGridViewRow row) { DataGridView7.DataSource = null; int columns = (DataGridView6.Columns != null) ? DataGridView6.Columns.Count : 0; if ((row != null) && (0 < columns)) { DataGridView7.Columns.Clear(); List<DataGridViewColumn> cols = new List<DataGridViewColumn>(columns); for (int i = 0; i < columns; i++) { DataGridViewColumn dgvCol = (DataGridViewColumn)DataGridView6.Columns[i].Clone(); DataGridView7.Columns.Add(dgvCol); } DataGridView7.Rows.Add(row); } } Now, to try this in VB: private DataGridView6 As DataGridView private DataGridView7 As DataGridView Private Function CreateRow(ByVal data As Object) As DataGridViewRow Dim index As Int16 = DataGridView6.Rows.Add() Dim row As DataGridViewRow = DataGridView6.Rows(index) ' row.Cells(0) = something ' basically, add your date Return row End Function Private Sub DisplayManagerRow(ByVal row As DataGridViewRow) DataGridView7.DataSource = Nothing Dim columns As Int32 = 0 If Not (DataGridView6.Columns = Nothing) Then columns = DataGridView6.Columns.Count End If If ((row Is Not Nothing) And (0 < columns)) Then DataGridView7.Columns.Clear() Dim cols As List<DataGridViewColumn> = new List<DataGridViewColumn>(columns) For (Dim i As Int32 = 0; i < columns; i++) Dim dgvCol As DataGridViewColumn = CType(DataGridView6.Columns(i).Clone(), DataGridViewColumn) DataGridView7.Columns.Add(dgvCol) Next For DataGridView7.Rows.Add(row) End If End Sub I can't even remember how to write a For loop in VB! Pathetic! Does that get the point across, though? Is this what you are trying to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/7540596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between lazy loading in NHibernate and Entity Framework While playing around with the Entity Framework and NHibernate using POCO entities, I made the following observation which I find a bit unusual: I have two POCO entities, an 'Order' and a 'Product'. There is a many-to-many relationship between the two. When I add a product to an Order, I use a 'FixUp' method to ensure that the opposing side of the relationship is also updated i.e. - that the products collection of 'Orders' is also updated. My Order POCO entity has the following method to do the 'FixUp': private void FixupProducts(object sender, NotifyCollectionChangedEventArgs e) { if(e.NewItems != null) { foreach(Product p in e.NewItems) { p.Order.Add(this); } } } While profiling this scenario with EFProf and NHProf, I observed that the Entity Framework generates one more SQL statement than NHibernate, the cause of which seems to be this line: p.Order.Add(this); With Entity Framework, the above line causes a select to be executed on the database to return all the orders for the product 'p'. I don't expect this to happen, since I'm using lazy loading and don't actually want to access the products 'Order' collection. I just want to add an order to it. With NHibernate no attempt is made to load the products collection of orders unless I explicitly try to access it. For example, if I say: foreach(Order o in product.Orders) { Console.WriteLine(o.Id); } So ultimately my question is, why does Entity Framework generate the extra SQL statement? Is there a difference in the implementation of lazy loading for the two frameworks that I'm not aware of? ***EDIT TO ORIGINAL It seems that Entity Framework doesn't behave in a lazy fashion once a method of any kind is called on the collection. Any attempt to add or count (or presumably any other operation on the collection) results in that collection being loaded into memory. What's interesting is my NHibernate mapping (which is a bag of 'Products - shown below), appears to behave in an 'extra-lazy' fashion, even though my mapping is configured as just being lazy: <bag name="Products" cascade ="all" table="OrderProduct" mutable="true" lazy="true"> I can 'Add' to the collection without it being loaded into memory. I think that calling 'Count' will result in the orders being loaded unless I configure it as being 'extra-lazy'. Can anyone comment on whether this is correct? A: That is how EF POCO template and its FixUp methods behave. The only ways to avoid this are: * *Removing FixUp methods from POCO template *Turn off lazy loading temporarily when assigning Product to Order It is based on the way how lazy loading is implemented. Every access to property / collection itself triggers lazy loading despite of the operation you want to use on the collection. You will have to avoid build in lazy loading completely to fully avoid it. Here is example how to achieve it for Count method - you can think about similar approach for other methods. A: I think that calling 'Count' will result in the orders being loaded unless I configure it as being 'extra-lazy'. This is correct, calling Count as well as Contains will be optimized and will not load the whole collection in NHibernate. You may also find this EF vs NHibernate comparison interesting: Collection with lazy=”extra” – Lazy extra means that NHibernate adapts to the operations that you might run on top of your collections. That means that blog.Posts.Count will not force a load of the entire collection, but rather would create a “select count(*) from Posts where BlogId = 1” statement, and that blog.Posts.Contains() will likewise result in a single query rather than paying the price of loading the entire collection to memory. Adding a new item to an uninitialized lazy collection will not load the collection. It does not have to be mapped as extra lazy for this. Take a look at this article: Now, on collections mapped as lazy-loading, Add() operations are allowed even if the collection is not initialized (i.e. the collection just acts as a proxy). When adding an object to a collection in this state, a QueueAdd() method is called that stores the added object in a secondary collection. Once a lazy initialization is performed, this secondary collection is merged into the main one (I believe it’s the DelayedAddAll() method that does this). This can be hard to debug because lazy load is transparently triggered if you just touch the collection with the debugger (providing the session is connected at that moment), and everything gets initialized properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: POSIX regex in C is not working I want to match every thing in between two words GET and HTTP. I tried every thing I know. But it is not working. Any help appreciated. The pattern GET.*HTTP should match GET www.google.com HTTP. Here is the code Headers: #include <sys/types.h> #include <regex.h> #include <stdio.h> #include <stdlib.h> #include <string.h> Main: int main(int argc, char *argv[]) { regex_t regex; int reti; char msgbuf[100]; regmatch_t pmatch[1]; /* Compile regular expression */ reti = regcomp(&regex, "GET.*HTTP", REG_EXTENDED); if (reti) { fprintf(stderr, "Could not compile regex\n"); exit(1); } /* Execute regular expression */ reti = regexec(&regex, argv[1], 1, pmatch, 0); if (!reti) { puts("Match"); char *match = strndup(argv[1] + pmatch[0].rm_so, pmatch[0].rm_eo - pmatch[0].rm_so); printf("%s\n",match); } else if (reti == REG_NOMATCH) { puts("No match"); } else { regerror(reti, &regex, msgbuf, sizeof(msgbuf)); fprintf(stderr, "Regex match failed: %s\n", msgbuf); exit(1); } /* Free compiled regular expression if you want to use the regex_t again */ regfree(&regex); return 0; } Is there any thing I'm doing wrong here. A: Looks like my comment was the answer... The problem is that the command line argument was chopped into 3 strings, making argv[1] pointing to GET only. To pass the entire string to the program, you must use double quotes: $ ./regex GET www.google.com HTTP No match $ ./regex "GET www.google.com HTTP" Match GET www.google.com HTTP $
{ "language": "en", "url": "https://stackoverflow.com/questions/7540600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails how to validate file format? How do I validate my file fields for the correct format? I want the image field to validate that it is a .png, .jpg, .jpeg. And the flv that it has the ending .flv And the quicktime that it have the ending .mov And how do I create error messages to tell that the field is not valid. My simple_form_for: <%= f.input :name, :label => 'Navn', :required => true %><br /> <%= f.label :tekst %><br /> <%= f.text_area :text, :label => 'Text', :size => '12x12' %><br /> <%= f.label "Upload billede - kræves" %><br /> <%= f.input :image, :label => '', :required => true %><br /> <%= f.label "Upload flv - kræves" %><br /> <%= f.input :flv, :label => '', :required => true %><br /> <%= f.label "Upload Quicktime - kræves" %><br /> <%= f.input :quicktime, :label => '', :required => true %><br /> <%= f.button :submit, :value => 'Create movie' %> Update: I have figure out how to validate the .mov and .flv fields: validates_format_of :flv, :with => %r{\.flv$}i, :message => "file must be in .flv format" validates_format_of :mov, :with => %r{\.mov$}i, :message => "file must be in .mov format" I just don´t have found a solution to validate the image. My controller: def savenew @photographer = Photographer.new(params[:photographer]) @photographer.sort_order = Photographer.count + 1 if @photographer.save redirect_to :action => 'list', :id => params[:id] flash[:notice] = "Movie #{@photographer.name} is created" else render 'create', :id => params[:id] end end A: If you want to continue as with flv and mov, you could do: validates_format_of :image, :with => %r{\.(png|jpg|jpeg)$}i, :message => "whatever" but please be aware that this would only validate that the filename would end in a specific string. These don't validate that the actual file is a real PNG (or whatever format). So someone could still just upload a zipfile with extension ".png".
{ "language": "en", "url": "https://stackoverflow.com/questions/7540601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem in show value jQuery toolti I created a tooltip and i have problem with it, i want: When that mouseenter on hi show value into next div it value hi When that mouseenter on hello show value into next div it value hello But in following code, when that mouseenter on each tow hi & hello showing value hello, How can fix it? var tip = $('.tool_tip').closest('li').find('div').clone(); $('.tool_tip').mouseenter(function () { var $this = $(this), $div = '.'+$this.closest('li').find('div').attr('class'); $(this).attr('title', ''); $($div).hide().fadeIn('slow').children('.tipBody').html(tip); }).mousemove(function (e) { $('.tooltip').css('top', e.pageY + 10); $('.tooltip').css('left', e.pageX + 20); }).mouseleave(function () { $('.tooltip').hide(); }) Example: http://jsfiddle.net/dege4/2/ A: I was having a similar problem here: Can I add more after "this" in jQuery?. When referencing the parent li of your tooltip try using this code: $(".tooltip", $(this).closest("li")) A: var tip = $('.tool_tip').closest('li').find('div').clone(); $('.tool_tip').mouseenter(function () { var $this = $(this), $div = $this.closest('li').find('div'); $(this).attr('title', ''); $div.hide().fadeIn('slow'); }).mousemove(function (e) { $('.tooltip').css('top', e.pageY + 10); $('.tooltip').css('left', e.pageX + 20); }).mouseleave(function () { $('.tooltip').hide(); }) works @ http://jsfiddle.net/dege4/5/
{ "language": "en", "url": "https://stackoverflow.com/questions/7540602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory leak in IE8? http://jsfiddle.net/mplungjan/SyHFR/ Sorry for the messy code - I have modified a script not chosen by me and originally from Dynamic Drive - it is used by someone I am helping and rather that rewriting the whole thing from scratch, I agreed to the feature creep. The intended changes was to add a repeat after and a delay by vars Now I just want to understand where there could be a problem - I changed the code from using a date object every second to use it only when initialising. The code cdtime.prototype.updateTime=function(){ var thisobj=this; this.currentTime+=1000; // one second setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second } gives a Message: 'thisobj' is null or not an object after about 9 hours in IE8 on XP I am running it myself now on another box over the weekend, but was wondering if someone could enlighten me as to what could be the issue with IE. HMM - pasting the function right now, I see the settimeout is inside a prototype - that suddenly does not look right. Please also do feel free to point me to a better counter that can do what this one is doing, e.g. start after a delay, repeat after a given time and have more than one counter on the page styled by CSS. UPDATE Trying the setInterval makes the whole coundown very choppy http://jsfiddle.net/mplungjan/z2AQF/ A: If it is really a memory leak, try clearing the thisobj variable from the function passed to setTimeout: cdtime.prototype.updateTime = function () { var thisobj=this; this.currentTime+=1000; // one second setTimeout(function () { thisobj.updateTime(); thisobj = null; }, 1000); //update time every second }; If you look closer, this function is basically an interval, so the following would be more optimized since it does not stack up on old functions: cdtime.prototype.updateTime = function () { var thisobj = this; setInterval(function () { thisobj.currentTime += 1000; }, 1000); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7540604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to make a b2body move at a constant speed with box2d I am making a box2d game and have enemies fly in from the left side of the screen to the right side of the screen. If I apply a force in the tick method like shown below, the enemies increasingly move faster over time. I want the enemies to move at a constant pace instead of increasing their speed. How can I do this. I have tried impulses and forces, but they don't seem to keep a constant speed b2Vec2 forceA = b2Vec2(15, -b->GetMass() * world->GetGravity().y); b->ApplyForce(forceA, b->GetWorldCenter() ); A: Just create them with the speed you want: b2BodyDef bDef; ... bDef.linearVelocity = myVelocity; b2Body *b = world->createBody(&bDef); If no forces are applied to them they will preserve their speed according to Newton's first law. If you have gravity then each step apply force: b2Vec2 forceA = b2Vec2(0, -b->GetMass() * world->GetGravity().y); b->ApplyForce(forceA, b->GetWorldCenter() ); A: use b->SetLinearVelocity(b2Vec2(thisVel, 0));. If this constant velocity might eventually be changed for some other constant velocity, you could wrap this in a conditional such as if(b->GetLinearVelocity().x != 0){ b->SetLinearVelocity(b2Vec2(0, 0)); } So that you're not re-applying the same velocity each tick (although it's possible that box2d takes care of this for you, not sure about that). I ran into the same issue of how to make bodies move at a constant speed, and the one other thing I recommend is to make sure the surface/medium that your body is moving across is frictionless - that way they'll never slow down after you set their velocity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Button and Edittext styles differ between real phone (Galaxy S2) and emulator On the AVD, my buttons and edittexts look very nice with rounded corners and shaded backgrounds. Also in the gui editor of Eclipse, they look nice as it should be. But when I then install the app on my SGS2, the buttons and edittexts are basically just white rectangles. App is compiled for Android 1.6. SGS2 runs Android 2.3.3. -- As a newbie, I don't seem to be allowed to post the screen images, bummer, sorry about that -- Here is the XML. I didn't do any special formatting: <EditText android:id="@+id/from_account" android:layout_width="fill_parent" android:text="Checking"/> I thought it may be due to differences in screen resolution and density. But they are the same except xdpi and ydpi (see images). (Please ignore color of DisplayMetrics). A: That's because each manufacturer defines it's own default theme. Read more about themes. A: As @renam.antunes said - each manufacturer is free to customize the theme as they see like. If you want more control, then you'll need to style the components yourself - e.g. setting the background of image of a button. If you like the default Android style you can find the resources used for that in sdk/platforms/platform-X/data/res/
{ "language": "en", "url": "https://stackoverflow.com/questions/7540612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Reading dataset value into a gnuplot variable (start of X series) I originally thought this may be the same as gnuplot - start of X series - Stack Overflow - but I think this is slightly more specific. Since I'm interested in finding the "start of X series", so to speak - I'll try to clarify with an example; say you have this script: # generate data system "cat > ./inline.dat <<EOF\n\ 10.0 1 a 2\n\ 10.2 2 b 2\n\ 10.4 3 a 2\n\ 10.6 4 b 2\n\ 10.8 5 c 7\n\ 11.0 5 c 7\n\ EOF\n" # ranges set yrange [0:8] set xrange [0:11.5] plot "inline.dat" using 1:2 with impulses linewidth 2 If you plot it, you'll notice the data starts from 10 on x-axis: Now, of course you can adjust the xrange - but sometimes you're interested in "relative positions" which start "from 0", so to speak. Therefore, one would like to see the data "moved left" on the x-axis, so it starts at 0. Since we know the data starts at 10.0, we could subtract that from first column explicitly: plot "inline.dat" using ($1-10.0):2 with impulses linewidth 2 ... and that basically does the trick. But say you don't want to specify the "10.0" explicitly in the plot command above; then - knowing that it is the first element of the first column of the data which is already loaded, one would hope there is a way to somehow read this value in a variable - say, with something like the following pseudocode: varval = "inline.dat"(1,1) # get first element of first column in variable plot "inline.dat" using ($1-varval):2 with impulses linewidth 2 ... and with something like this, one wouldn't have to specify this "x offset" value, so to speak, manually in the plot command. So - to rephrase - is there a way to read the start of x series (the first value of a given column in a dataset) as a variable in gnuplot? A: Two ways: 1. Plot the function first and let gnuplot to tell the minimum x value: plot "inline.dat" using 1:2 with impulses linewidth 2 xmin = GPVAL_DATA_X_MIN plot "inline.dat" using ($1-xmin):2 with impulses linewidth 2 2. Use external script to figure out what is the minimum x value: xmin = `sort -nk 1 inline.dat | head -n 1 | awk '{print $1}'` plot "inline.dat" using ($1-xmin):2 with impulses linewidth 2 A: OK, I keep coming back to this - so I think I needed the following clarification here: Given that gnuplot, well, plots datasets as 2D plots - it's a given that it somehow deals with 2D structures or arrays. That is why someone coming from C, Perl, Python etc. would naturally think it is possible to somehow index the dataset, and be able to retrieve a value at a given row and column position; say, something like the following pseudocode: my_val = "inline.dat"[1][2] # get value in 1st row and 2nd column Or alternately, pseudocode: my_dataset = parse_dataset("inline.dat") my_val = get_value(my_dataset, 1, 2) And I spent a ton of time looking for something like this in gnuplot, and cannot find anything like that (a direct variable access to dataset values through row and column index). It seems that the only thing one can do, is plot the dataset - and possibly access values there, via function called in the using part. That means, that if I want to find some dataset values from gnuplot, I have to iterate through the dataset by calling plot - even if I need those values precisely to construct a proper plot statement :) And I kind of dislike that, thinking that the first plot may somehow screw up the second afterwards :) However, as finding maximum value in a data set and subtracting from plot - comp.graphics.apps.gnuplot | Google Groups points out, one can plot to a file, also stdout or /dev/null, and get a plain ASCII formatted table - so at least I can redirect the first call in that way, so it doesn't interfere with the actual plotting terminal of the second call to plot. So, below is another code example, where the first element of first column in the "inline.dat" dataset is retrieved via: # print and get (in _drcv) first value of first data column: eval print_dataset_row_column("inline.dat",0,1) # must "copy" the "return" value manually: first = _drcv ... so then the plot can be offset by first directly in the plot call. Note again that print_dataset_row_column calls plot (redirected via set table to /dev/null) -- and as such, each time you call it to retrieve a single value, it will cause iteration through the entire dataset! So if you need first element and last element (and possibly other stuff, like some basic statistics with gnuplot), it's probably better to rewrite print_dataset_row_column so it retrieves all of those in one go. Also a print_dataset_row_column rewrite would be needed if you use some special formats in your dataset and the using line. Note that in this example, the third column is a string - which is not by default accepted as a plot data column; and as such, calls to the print_dataset_* functions will fail if they have to deal with it (see also gnuplot plot from string).   So here is the example code - let's call it test.gp: # generate data system "cat > ./inline.dat <<EOF\n\ 10.0 1 a 2\n\ 10.2 2 b 2\n\ 10.4 3 a 2\n\ 10.6 4 b 2\n\ 10.8 5 c 7\n\ 11.0 5 c 7\n\ EOF\n" ### "dry-run" functions: # iterate through dataset by calling # `plot`, redirected to file output (via `set table`) # # note: eval (not print) cannot be inside a user-defined function: # a(b) = eval('c=3') ; print a(4) ==> "undefined function: eval" # nor you can make multistatement functions with semicolon: # f(x) = (2*x ; x=x+2) ==> ')' expected (at ';') # # so these functions are defined as strings - and called through eval # # through a single column spec in `using`: # (`plot` prints table to stdout) # print_dataset_column(filename,col) = "set table '/dev/stdout' ;\ plot '".filename."' using ".col." ;\ unset table" # # through two column spec in `using`: # (`plot` prints table to stdout) # print_dataset_twocolumn(filename,colA,colB) = "set table '/dev/stdout' ;\ plot '".filename."' using ".colA.":".colB." ;\ unset table" # # print value of row:column in dataset, saving it as _drcv variable # # init variable # _drcv = 0 # # create _drc helper function; note assign and "return" in # true branch of ternary clause # _drc(ri, colval, col) = (ri == _row) ? _drcv = colval : colval # # define the callable function: # print_dataset_row_column(filename,row,col) = "_row = ".row." ;\ set table '/dev/null' ;\ plot '".filename."' using (_drc($0, $".col.", ".col.")) ;\ unset table ;\ print '".filename."[r:".row.",c:".col."] = ',_drcv" # # ### end dry run functions # # test print_dataset_* functions: # eval print_dataset_column("inline.dat",0) eval print_dataset_twocolumn("inline.dat",0,0) # string column - cannot directly: # set table '/dev/stdout' ;plot 'inline.dat' using 3 ;unset table # ^ # line 69: warning: Skipping data file with no valid points # line 69: x range is invalid #~ eval print_dataset_column("inline.dat",3) eval print_dataset_column("inline.dat",1) eval print_dataset_twocolumn("inline.dat",1,2) eval print_dataset_row_column("inline.dat",4,1) eval print_dataset_row_column("inline.dat",4,2) # will fail - 3 is string column # line 82: warning: Skipping data file with no valid points # line 82: x range is invalid #~ eval print_dataset_row_column("inline.dat",4,3) # # do a plot offset by first element position # # print and get (in _drcv) first value of first data column: eval print_dataset_row_column("inline.dat",0,1) # must "copy" the "return" value manually: first = _drcv # ranges set yrange [0:8] set xrange [0:11.5] # plot finally: plot "inline.dat" using ($1-first):2 with impulses linewidth 2 When this script is called, the dataset in the OP is plotted moved, starting from 0 - and the following is output in terminal (the first few table printouts are the actual output from plot redirected via set table to stdout): gnuplot> load './test.gp' # Curve 0 of 1, 6 points # Curve title: "'inline.dat' using 0" # x y type 0 0 i 1 1 i 2 2 i 3 3 i 4 4 i 5 5 i # Curve 0 of 1, 6 points # Curve title: "'inline.dat' using 0:0" # x y type 0 0 i 1 1 i 2 2 i 3 3 i 4 4 i 5 5 i # Curve 0 of 1, 6 points # Curve title: "'inline.dat' using 1" # x y type 0 10 i 1 10.2 i 2 10.4 i 3 10.6 i 4 10.8 i 5 11 i # Curve 0 of 1, 6 points # Curve title: "'inline.dat' using 1:2" # x y type 10 1 i 10.2 2 i 10.4 3 i 10.6 4 i 10.8 5 i 11 5 i inline.dat[r:4,c:1] = 10.8 inline.dat[r:4,c:2] = 5.0 inline.dat[r:0,c:1] = 10.0 A: To read a single value from a data files consider the following user defined function: at(file, row, col) = system( sprintf("awk -v row=%d -v col=%d 'NR == row {print $col}' %s", row, col, file) ) file="delta-fps" ; row=2 ; col=2 print at(file,row,col) Of course, the input to awk has to be cleared of ignored/invalid input (blank lines, comments, etc). For example: at(file, row, col) = system( sprintf("grep -v '^#|^$' %s | awk -v row=%d -v col=%d 'NR == row {print $col}'", file, row, col) ) Still, this function will not allow reading any dataset, it is restricted to files. However, this limitation can be overcome by checking for the redirection character '<' in the file name argument and replacing it in a sensible way (see the ternary operator): at(file, row, col)=system( sprintf("%s | grep -v '^#\\|^$' | awk -v row=%d -v col=%d 'NR == row {print $col}'", (file[:1] eq '<') ? file[2:] :'cat '.file, row, col) ) A good point to define such a unction may be your .gnuplot init file. A: Hmmm... OK, I got something: initer(x) = (!exists("first")) ? first = x : first ; plot "inline.dat" using ($1-initer($1)):2 with impulses linewidth 2 ... but this looks more like "capturing" a variable, than reading it (as the function initer is being used to scan a stream of numbers, detect the first one, and return its value) :) Hope there is a better way of doing this ....
{ "language": "en", "url": "https://stackoverflow.com/questions/7540614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: jQuery Table Sorting by Attr e.g. Title Does anyone know of a jQuery plugin that allows table sorting when clicking on the header, but checks say the title of a cell and sorts by that before looking at the contents of the cell? I have some data in my cells such as 3h 5m and 5m, most sorting plugins get these in the wrong order as it sorts it alphanumerically because it doesn't understand the value. I am sure somewhere I have seem a plugin where you put the raw data in the title, and the plugin actually sorted based on that data rather than the info in the cell. Many thanks for your time, A: Using jQuery dataTables and the following custom sorting function (you may have to expand it if your "last seen" has more than just days/hours/minutes): jQuery.fn.dataTableExt.oSort['mytime-asc'] = function(a,b) { var regex = /\s*(?:(\d+)d)?\s*(?:(\d+)h)?\s*(?:(\d+)m)?\s*/; var m; m = a.match(regex); var x = (m[1] ? parseInt(m[1]) : 0) * 1440 + (m[2] ? parseInt(m[2]) : 0) * 60 + (m[3] ? parseInt(m[3]) : 0); m = b.match(regex); var y = (m[1] ? parseInt(m[1]) : 0) * 1440 + (m[2] ? parseInt(m[2]) : 0) * 60 + (m[3] ? parseInt(m[3]) : 0); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; jQuery.fn.dataTableExt.oSort['mytime-desc'] = function(a,b) { // Same function as above, except for the return value: return ((x < y) ? -1 : ((x > y) ? -1 : 0)); } And the associated jQuery dataTable call would look something like: $('#example').dataTable( { "aoColumns": [ null, null, null, { "sType": "mytime" }, null ] });
{ "language": "en", "url": "https://stackoverflow.com/questions/7540619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to detect mouse click on menuItem when added via addMouseListener Consider you want to close your java application using "Close application" menu item. 3 possible solutions are (using ActionListener or MouseAdapter or MouseListener): menuItemClose.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub System.exit(0); } }); menuItemClose.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.exit(0); } }); menuItemClose.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub System.exit(0); } }); 3 solutions, and only first one fires. What is the explanation of this? Does some other componenets have same behavior? How to properly handle events in such cases? A: In that example, you never register a KeyListener. Anyway, you should only register an ActionListener. For more information, see Handling Events from Menu Items. See also: * *Enabling Keyboard Operation A: Sounds like the developers of Java languare forget to propagate events from menuItems using addActionListener. No, the developers suggest that you use Action "to separate functionality and state from a component."
{ "language": "en", "url": "https://stackoverflow.com/questions/7540626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery listener click not working So I have this code that should listen for a click on #button but it won't work, and is driving me crazy! <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> $('#button').click(function() { alert('OK!'); }); </script> and the HTML: <input id="button" type="button" value="OK" /> This is strange. Any help is welcome! A: Here's what the code should look like: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script> <script type="text/javascript"> // Now that jquery is include, place the code to wire up the button here $(function(){ // Once the document.onload event fires, attach the click // event handler for the button $('#button').click(function() { alert('OK!'); }); }); </script> <input id="button" type="button" value="OK" /> Here's the jquery documentation that relates to this: http://docs.jquery.com/How_jQuery_Works A: Write your code inside document.ready function <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $('#button').click(function() { alert('OK!'); }); }); </script> OR <script type="text/javascript"> function on_click() { alert("OK !!"); } $(document).ready(function() { $("#button").click(on_click); }); </script> hope you get some idea from this
{ "language": "en", "url": "https://stackoverflow.com/questions/7540632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: same method, multiple return types. code organization Let´s say I a have an User class and I want to return all the users in my database. For that i have create a method called getAll(); I need to call the method in different parts of my application and return the data in different formats. I might need all users separated by commas to put in some "where in" condition, or in json format to make an api, or as array, for example. Whats is the best solution to organize my code? Possible solutions: 1.Pass a fetchMode variable to the getAll function so i can format the return value accordingly. 2. Create a proxy method "findAllAsArray", "findAllAsJson" etc, which calls the the original getAll method and formats the response. 3. Allways return the result in a standard format (ex: array) and then create some generic methods to convert between formats: ex: arrayToJson, arrayToCsv, etc and use them when I need the results in other format than the standard. The method 1 might make the getAll method too complex, if i have many formats needed. The method 2,might adding too many extra methods making my class more complex. The method 3, not sure but the data should be returned in the needed format from the model i think. Converting it in the controller, it´s probably not the best solution. A: Create a new class, e.g. "Users," which contains the raw data. Users is immutable: Once initialized, its state never changes. Now have getAll() return an instance of Users, initialized with the raw data that getAll() created. Result has, for each format, a public method which formats the raw data appropriately and returns it. In pseudo code: class User: method getAll: users = # fetch the users return Users.new(users) class Users method initialize(users) # Save users to a member variable method json: # Return users formatted as json method csv: # Return users formatted as csv To retrieve all users in json format: users.getAll.json To retrieve all users in csv format: users.getAll.csv
{ "language": "en", "url": "https://stackoverflow.com/questions/7540635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: obtain radio interface layer on mobile website not application I was using IP2location dlls to get the user's location but i realised that it doesn't work on mobile websites. I read about getting the users location through the cell ID information and i was wondering if this can be used through mobile website on a server level or it has to be on the device level in an application ? http://dalelane.co.uk/blog/post-images/080312-rilcode.cs.txt string cellid = RIL.GetCellTowerInfo(); A: As far as I know there is either * *mobile devices implementing the html5 location extensions (via javascript) *Network operators sending through the cellid in some HTTP header to certain sites. (Either yours or some site you redirect to to return you the info)
{ "language": "en", "url": "https://stackoverflow.com/questions/7540636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List files and sub directories Android What i want to do is to open a directory through android application and list all the files as well as directories present in that directory. I would also like to retrieve permissions and owner information of each file/directory. This can be achieved in java but how can i do the same in Android? A: The java.io package has been reimplemented within Android. You should be able to use the same mechanisms in Android as you do in Java. File f = new File("/your/file/path"); File[] files = f.listFiles();
{ "language": "en", "url": "https://stackoverflow.com/questions/7540641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add in TextView new data(1 textView = 1 name), from Data Base? in a cycle I have tableLayout with 3 textView in a TableRow. How to add in TextView new data(1 textView = 1 name), from Data Base? thats doesnt work: my cursor say: select * from TABLE_NAME Cursor cursor = database.query(TABLE_NAME, new String[] {"*"}, null, null,null,null,"_id"); cursor.moveToFirst(); try { if (!cursor.moveToFirst()) { return; } do { TextView textView = (TextView)findViewById(R.id.edit); textView.setText(cursor.getString(0)); } while (cursor.moveToNext()); } finally { cursor.close(); } My table: _id student 1 Said 2 Bill 3 John etc A: You are overwriting your TextView identified by edit each time you call setText(String). You may need to create new instances of TextView programatically. TableRow row = new TableRow(context); do { TextView textView = new TextView(context); textView.setText(cursor.getString(0)); row.addView(textView); //add each textview to your row } while (cursor.moveToNext()); myTableLayout.addView(row); //add your row to your table If you already have a TableLayout, you can add a TableRow to it using addView(View v). Add new instances of TextView to your TableRow and you should get what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate random bytes Cocoa? I need to generate some random data to append to my file for encryption. How would I go about doing this? Would it be sort of the same idea as generating a string of random characters? Something like: NSData *randomData = @"what should i put here?"; And then use the rand() function to randomize the data? Your help is greatly appreciated A: int SecRandomCopyBytes ( SecRandomRef rnd, size_t count, uint8_t *bytes ); For example: uint8_t data[100]; int err = 0; // Don't ask for too many bytes in one go, that can lock up your system err = SecRandomCopyBytes(kSecRandomDefault, 100, data); if(err != noErr) @throw [NSException exceptionWithName:@"..." reason:@"..." userInfo:nil]; NSData* randomData = [[NSData alloc] initWithBytes:data length:100]; As noted by Peter in the comments, you can also do this: NSMutableData* data = [NSMutableData dataWithLength:100]; err = SecRandomCopyBytes(kSecRandomDefault, 100, [data mutableBytes]); And as noted by Rob in the comments, you need to link Security.framework for SecRandomCopyBytes to be available. You also need to include SecRandom.h. A: On UNIX you can rely on /dev/random or /dev/urandom to obtain randomness of cryptographic quality. NSData *bytes = [[NSFileHandle fileHandleForReadingAtPath: @"/dev/random"] readDataOfLength: 100]; As it seems, it reads 100 bytes from /dev/random. Refer to man urandom for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Shift focus from one JTree node to another I need to shift focus from a JTree node to another node on the previous node being clicked. Example XML document: <br/> <'obo'><br/> <'term'><br/> <'id'>GO:0001<'/id'><br/> <'name'>candida... '<'/name'><br/> <'dbname'>' blah blah '<'/dbname'><br/> <'is_a'>'GO:0035'<'/is_a'><br/> <'/term'><br/> <'term'><br/> <'id'>'GO:0035'<'/id'><br/> <'name'>'candida... '<'/name'><br/> <'dbname'>' blah blah '<'/dbname'><br/> <'is_a'>'GO:00465'<'/is_a'><br/> <'/term'><br/> <'/obo'><br/> I have made this into a JTree. Now I need to shift focus to GO:0035 when the user clicks on GO:0001. I was trying to addTreeSelectionListener() but it doesn't not work in my Eclipse. I thought I could set a loop read each check if there is a corresponding , if there is a corresponding then get it's path, add a mouseListener to G0:0001 and setPath to GO:0035. I'm new to Java so I'm not particularly sure how to do this. Please help out!! :( A: It's not clear how you are constructing your JTree or TreeModel, but you can find examples in How to Use Trees. If you use the DefaultTreeModel, you can search from the node returned by the model's getRoot() method, and you can construct a TreePath to that destination node. Use the tree's setSelectionPath() method to select the node found. If you still have trouble, edit your question to provide an sscce that shows your usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: textarea as list Im trying to make 2 side by side text areas, with 2 buttons between them, one that adds an item from a selected line in the left textarea to the textarea on the right, the other to remove a selected item from the list on the right. Basically, a 'line selected' function is where Im failing. Any ideas? A: You can put each item in span/paragraph tag and use break line if necessary to keep each item on a separate line, then you can put a onclick event on the individual span tags. Would this help?
{ "language": "en", "url": "https://stackoverflow.com/questions/7540663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is the "Signals and Slots" concept reactive programming? As written in the title - is "Signals and Slots" a simple way of reactive programming? A: Signals/Slots is an implementation of the Observer Pattern . From the wiki on Reactive Programming: Reactive programming has principal similarities with the Observer pattern commonly used in object-oriented programming. However, integrating the data flow concepts into the programming language would make it easier to express them, and could therefore increase the granularity of the data flow graph. For example, the observer pattern commonly describes data-flows between whole objects/classes, whereas object-oriented reactive programming could target the members of objects/classes. They use the example of Excel cells / formulas in the Reactive Programming wiki, which is undoubtedly implemented using the observer pattern under the covers in the excel source code to make it actually happen. However, to the "excel programmer", it's Reactive Programming as they aren't having to implement the Observer Pattern themselves ... so it makes sense on that level. C++/C#/C/etc do not have this ability built in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google's website translator and content loaded via AJAX I am using Google's website translator on a website I am developing. In one section of the website I use AJAX to load new content into the page. I was hoping that there was a way to tell the Google translator to re-translate the loaded content (I could provide a DOM element that the content resides in). I can't find any documentation which suggests how to do this and it appears that the Google Translate API is becoming a paid service. Is it possible to use the Google translator in the way I require or do you need to use the paid service? A: You can call a function to re-translate the page in the same place you render the ajax content: $.getScript("//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"); Here's an example on jsFiddle http://jsfiddle.net/patridge/NQ4uE/
{ "language": "en", "url": "https://stackoverflow.com/questions/7540667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Help with list output I have this expression here $data = file_get_contents('groups.txt'); function links1($l1, $l2){echo "<a href='". $l1 ."'><img src='". $l2 ."'/></a>";} $parsed1 = get_string_between($data, "[Group1]", "[/Group1]"); $data = explode("\n", $parsed1); foreach($data as $string2){ list($l1, $l2) = explode(' ', $string2); links1($l1, $l2);}} I have a get_string_between defined as a function above that gets anything between "[Group1]" and "[/Group1]". The text file groups contains stuff: [Group1] aaa 1.png bbb 2.jpg [/Group1] The problem is that when I run this it outputs as <a href=''><img src=''/></a><a href='aaa'><img src='1.png'/></a><a href='bbb'><img src='2.jpg'/></a><a href=''><img src=''/></a> so I get these dummy two spaces i guess that are added to the front and back of anything thats between aaa 1.png bbb 2.jpg How can I fix that? Basicly gow can i remove the <a href=''><img src=''/> from start and back from the output? Thanks! edit: added the get_string_between function function get_string_between(){ $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); A: There are several problems with your get_string_between function. I've tried to clean it up here: function get_string_between($text, $start, $end) { $n1 = strpos($text, $start); if ($n1 === false) return ''; $n1 += strlen($start); $n2 = strpos($text, $end, $n1); if ($n2 === false) return substr($text, $n1); return substr($text, $n1, $n2 - $n1); } Hopefully this will help/lead you in the right direction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best practice to define multi-dimensional arrays in wsdl I'm developing a WebService with a function which returns a database result, which means an MxN array. My question is, what's the better way to define this in wsdl: * *Define a row as sequence of (string) columns, define the resultset as sequence of rows, put this resultset into a message *Define a row as sequence of (string) columns, put a sequence of such rows into the message directly So is it better/cleaner/nicer to wrap the rows into an own datatype and put this one into the response message or leave the own datatype and put the row-sequence directly into the message? Thank you! A: For the row you define an element which has as children elements coresponding to the columns of the result. <row> <field1>...</field1> <field2>...</field2> ... <fieldN>...</fieldN> </row> You then return a wrapped list of row elements. <rows> <row> ... </row> <row> ... </row> ... <row> ... </row> </rows> (I'm using row/rows here for simplicity. You can name the element whatever you want, normally a name that reflects the what the data in the row represents).
{ "language": "en", "url": "https://stackoverflow.com/questions/7540673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }