text
stringlengths
8
267k
meta
dict
Q: How to change child tag order in XML (Generated by PHP) I have one application in flash in which multiple users can log in and can upload images. when user log in he can view images uploaded by him and also can view images uploaded by other users(only allowed images). for that i am generating xml file through php. please check xml file. <images> <users user_name="Hardik"> <image image_id="1316683023140" image_title="water" image_desc="water" image_path="all_users/Hardik/1316683023140.jpg" image_like="false"/> <image image_id="1316683057577" image_title="sunset" image_desc="sunset" image_path="all_users/Hardik/1316683057577.jpg" image_like="false"/> <image image_id="1316683115124" image_title="hills" image_desc="hills" image_path="all_users/Hardik/1316683115124.jpg" image_like="false"/> <image image_id="1316683713159" image_title="sun" image_desc="sun" image_path="all_users/Hardik/1316683713159.jpg" image_like="false"/> <image image_id="1316684544200" image_title="sun" image_desc="sun" image_path="all_users/Hardik/1316684544200.jpg" image_like="false"/> <image image_id="1316686014899" image_title="sun" image_desc="sun" image_path="all_users/Hardik/1316686014899.jpg" image_like="false"/> <image image_id="1316600184214" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600184214.jpg" image_like="false"/> <image image_id="1316668356801" image_title="hello" image_desc="hello" image_path="all_users/Hardik/1316668356801.jpg" image_like="false"/> <image image_id="1316600221759" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600221759.jpg" image_like="false"/> <image image_id="1316600193960" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600193960.jpg" image_like="false"/> <image image_id="1316600172938" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600172938.jpg" image_like="false"/> <image image_id="1316600144316" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600144316.jpg" image_like="false"/> <image image_id="1316600173551" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600173551.jpg" image_like="false"/> <image image_id="1316600177792" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600177792.jpg" image_like="false"/> <image image_id="1316496700758" image_title="sunset" image_desc="sunset" image_path="all_users/Hardik/1316496700758.jpg" image_like="false"/> <image image_id="1316252181829" image_title="allow" image_desc="allow" image_path="all_users/Hardik/1316252181829.jpg" image_like="false"/> <image image_id="1316690195793" image_title="asasdas" image_desc="asdasd" image_path="all_users/Hardik/1316690195793.jpg" image_like="false"/> <image image_id="1316600153509" image_title="asd" image_desc="asd" image_path="all_users/Hardik/1316600153509.jpg" image_like="false"/> <image image_id="1316408901775" image_title="winter" image_desc="winter" image_path="all_users/Hardik/1316408901775.jpg" image_like="false"/> </users> <users user_name="raj"> <image image_id="1315996252734" image_title="abc" image_desc="abc" image_path="all_users/raj/1315996252734.jpg" image_like="false"/> </users> <users user_name="sandip"> <image image_id="1315996256153" image_title="abc" image_desc="abc" image_path="all_users/sandip/1315996256153.jpg" image_like="false"/> </users> </images> i have one logical issue with my XML file (that is generated by PHP). now i want to change child tag order. i want to have child tag of a user (that is logged in) in first position. say if sandip logins his child tag should come first instead hardik. you can check my php code here <?php require_once('connection.php'); header('Content-type: text/xml'); echo "<?xml version='1.0' encoding='UTF-8'?>"; echo "<images>"; $id=''; $count=0; $result_1 = ''; $query = "select ui.userId as 'UI userId', ua.userName as 'UI userName', ui.imageId as 'UI ImageId', ul.imageId as 'UL ImageId' , ui.imageRights, ui.imagePath, ui.imageTitle, ui.imageDesc from user_account ua, (select * from user_images where userId=".$_REQUEST['userId']." or imageRights='Allow') as ui left join (select * from user_likes where userId=".$_REQUEST['userId'].") as ul on ui.imageId = ul.imageId where ua.userId=ui.userId order by ui.userId"; $result_row = mysql_query($query); while($row = mysql_fetch_array($result_row, MYSQL_ASSOC)) { if($id != $row['UI userId']) { if($count == 0) { $result_1 .= "<users user_name='".$row['UI userName']."'>"; } else { $result_1 .= "</users>"; $result_1 .= "<users user_name='".$row['UI userName']."'>"; } $id = $row['UI userId']; } $result_1 .= "<image image_id='".$row['UI ImageId']."' image_title='".$row['imageTitle']."' image_desc='".$row['imageDesc']."' image_path='".$row['imagePath']."' image_like='"; if($row['UL ImageId']) $result_1 .= "true"; else $result_1 .= "false"; $result_1 .= "' />"; $count++; if($count == mysql_num_rows($result_row)) $result_1 .= "</users>"; } echo $result_1; echo "</images>"; ?> if you have any better solution please forward. A: I would like to suggest some fixes to your php script in addition to solving your problem: $num_of_rows = mysql_num_rows($result_row); // Don't call this every loop it's very slow $rows = []; while($row = mysql_fetch_array($result_row, MYSQL_ASSOC)){ if($id == $row['UI userId']){ // Print the logged in user's images } else { $rows[] = $row; } } // Print here the rest of the results foreach ($rows as $row) { if($id != $row['UI userId']) { if($count == 0) { $result_1 .= "<users user_name='".$row['UI userName']."'>"; } else { $result_1 .= "</users>"; $result_1 .= "<users user_name='".$row['UI userName']."'>"; } $id = $row['UI userId']; } $result_1 .= "<image image_id='".$row['UI ImageId']."' image_title='".$row['imageTitle']."' image_desc='".$row['imageDesc']."' image_path='".$row['imagePath']."' image_like='"; if($row['UL ImageId']) $result_1 .= "true"; else $result_1 .= "false"; $result_1 .= "' />"; $count++; if($count == $num_of_rows) $result_1 .= "</users>"; } echo $result_1; echo "</images>"; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7524950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can a WP7.1 app use UdpAnySourceMulticastClient to communicate with Android and iOS Can UdpAnySourceMulticastClient be used in a WP7.1 app to communicate with Android and iOS? If it is possible is there any limitations on the datasize that can be transferred? A: There is no restriction on the type of sender (or receiver) to receive the UDP datagram from. The API only gives the IP Address of the sender and not the type. There is usually limit on the size since it is a datagram, after all
{ "language": "en", "url": "https://stackoverflow.com/questions/7524953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UI Automation Tool Im new to Automation and I'm involved in developing an Automation Tool which can be used to Automate and Record all the current Process that are handled in a machine using .NET. Is it possible to automate all those process and thier controls using a Tool. Please help me with this. Please refer me some Tools which already doing this kind of work. A: I believe you want to automate your tests on your application, rather than 'developing a Automation Tool'. That said, you should be able automate your application (web/windows/swing/...). There are many tools out in the market. Visual Studio 2010, TestComplete, Quick Test Professional are some of the commercial tools. For open source tools, you can check Selenium, Watin (for .NET) , Watir (for Ruby).
{ "language": "en", "url": "https://stackoverflow.com/questions/7524954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: zoom controller not working in webview in android I am suffering from a strange problem in order to implement WebView in android. I am trying to load html5 supported web page in my WebView, but the problem is default zoom controller is not working in WebView. i tried with the following code. webview.getSettings().setBuiltInZoomControls(true); webview.invokeZoomPicker(); Can any body help regarding this. A: Add this line also WebSettings setting = wView.getSettings(); setting.setBuiltInZoomControls(true); setting.setSupportZoom(true); if work or not please reply
{ "language": "en", "url": "https://stackoverflow.com/questions/7524957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Persistance storage for UIVIew I am creating dynamically some "n" number of UIView Object in my application.I can able to drag, drop these objects to any position in the screen & chenge change their some of property .Now i want to save all these details with persistance storage ,so that whenever i launched the application nest time, i can able to see those already created object. So what is the best solution for this? Also is their any sample application available for this form which i can take reference? A: I think you can do it this way. // Create an array to store the properties NSMutableArray *viewProperties = [NSMutableArray array]; // Loop through all the views for (UIView *view in views) { // Create a dictionary for each view NSMutableDictionary *dict = [NSMutableDictionary dictionary]; // Store the properties in the dictionary [dict setValue:NSStringFromCGRect(view.frame) forKey:@"ViewFrame"]; ... // Add the dictionary to the array [viewProperties addObject:dict]; } // Finally add the array to persistence [userDefaults setValue:viewProperties forKey:@"ViewProperties"]; Later you can get the array from persistence and create the views with the properties. NSMutableArray *viewProperties = [userDefaults valueForKey:@"ViewProperties"]; for (NSDictionary *dict in viewProperties) { UIView *view = [[UIView alloc] init]; NSString *frameAsString = [dict valueForKey:@"ViewFrame"]; view.frame = CGRectFromString(frameAsString); // Get other properties from dictionary and set it to view }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sort an array with respect to sorting of an another array iphone sdk I have a situation here, I have two arrays,array1 and array2 and one tableview. I have loaded array1 to the table view. So here, I'm sorting array2, I've done that, but how can I sort array1 with respect to the change in array2 and to reload array1 in tableview. That is I need to sort array1 automatically when I sort array2. Any ideas? Please share your thoughts. Thanks :) A: The logical advice, would be that, if the objects are sorted together, then they're related somehow, and both pieces of data should conform a new object (A dictionary, an NSObject, whatever). I mean, if array1 is [1, 5, 4, 3, 2] and array2 is ["hello", "world", "big", "little", "my"], then the mixed array would be: [(1, "hello"), (5, "world"), (4, "big"), (3, "little"), (2, "my")]. Sorting this is trivial, and it makes sense if the data is correlated (no way to tell since you didn't specify this). Objective-C example Custom Object (CustomObject.h) that holds both name/number (using a number as a trivial example): @interface CustomObject : NSObject @property (nonatomic,retain) NSString *name; @property (nonatomic,assign) NSInteger number; + (id)customObjectWithName:(NSString*)name andNumber:(NSInteger)number; @end CustomObject.m: #import "CustomObject.h" @implementation CustomObject @synthesize name, number; + (id)customObjectWithName:(NSString*)name andNumber:(NSInteger)number { CustomObject *customObject = [[CustomObject alloc] init]; customObject.name = name; customObject.number = number; return customObject; } - (NSString *)description { return [NSString stringWithFormat:@"(Number:%d, Name:%@)", self.number, self.name]; } - (void)dealloc { [name release]; [super dealloc]; } @end Using these objects together with sorting: NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: [CustomObject customObjectWithName:@"Hello" andNumber:1], [CustomObject customObjectWithName:@"gentlemen?" andNumber:5], [CustomObject customObjectWithName:@"you" andNumber:4], [CustomObject customObjectWithName:@"are" andNumber:3], [CustomObject customObjectWithName:@"how" andNumber:2], nil]; [array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [(CustomObject*)obj1 number] - [(CustomObject*)obj2 number]; }]; NSLog(@"Results: %@", array); The output looks like: 2011-09-23 03:27:14.388 Test[5942:b303] Results: ( "(Number:1, Name:Hello)", "(Number:2, Name:how)", "(Number:3, Name:are)", "(Number:4, Name:you)", "(Number:5, Name:gentlemen?)" A: Would need more info (source code or psudo) to determine how/when/where the sorting of array2 takes place to answer how array1 can be sorted; but once array1 does get sorted, you can reload the values into the table with: [myTable reloadData]; And it will reload each row and cell, reading array1's values in their sorted order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: skip the screenlock protected void onPause() { super.onPause(); // If the screen is off then the device has been locked PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); boolean isScreenOn = powerManager.isScreenOn(); //screen locked if (!isScreenOn) { boolean pressed = onKeyDown(26, null); //power button pressed if(pressed){ //remove keyguard getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); //start intent Intent i = new Intent(this, VoiceRecognitionActivity.class); startActivity(i); } } } the above code does is when power button is pressed, the keyguard will be dismissed and the activity onpaused will be resumed. However, the keyguard is not dimissed when i pressed the power button, and i have to unlock manually. When i pressed the power button, the window of my activity flashed for a second and the keyguard window is shown. A: If you want to prevent phone from turning screen off (and locking the phone in result) you should use WakeLock. You can use PowerManager.newWakeLock() with FLAG_KEEP_SCREEN_ON or even FULL_WAKE_LOCK. A: This code snippet may help: final Window win = getWindow(); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); // Turn on the screen unless we are being launched from the AlarmAlert // subclass. final boolean screenOff = getIntent().getBooleanExtra(SCREEN_OFF, false); if (!screenOff) { try { // API 8+ win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON); } catch (final Throwable whocares) { // API 7+ win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating subdomains and Sharing authentication on 2 different project/solution/application I am trying to create a website with subdomains in asp.net mvc. But I am not sure how to do this. When setting up this new solution in visual studio is it best to have a different project for each subdomain or have one project? There are obviously some immediate advantages to this such as publishing updates to one subdomain without touching the others. Here is the specification: 1)I have many applications , each have their own subdomain, e.g. App1, App2, App3. The user will login through the Main domain with login page, and this authentication will be passed down to the applications. 2) I need the domain to authenticate the user and pass the authentication to the subdomain. The subdomain will only allow access to authenticated users. ASP.NET allows the authentication to be passed to subdomains. What I need to know is how to set the projects so that the subdomian knows that the authentication is being passed this way. 3) I've decided to go down the subdomain route. http://App1.domain.com/ http://App12.domain.com/ 4)I'm also thinking about reusable code. Is there any way to share masterpage,usercontrols etc over the three different subdomains? A: Separate web applications and in the web.config of each set the domain property to the top level domain: <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" domain="domain.com" /> </authentication> This way when a user authenticates on one of the applications, the authentication cookie will contain the domain property and it will be sent along to other applications in this domain and sub-domains and the user will be automatically authenticated on the other applications as well. A: Thought about a similar situation a few days ago. I found two options for doing the "on the fly subdomain registration" * *A subdomain registration tooks no time when root domain is registered! *Rewrite the URL In case 1 I'd forward *.mydomain.com to the webserver (IIS) in that case and use the IIS Administration API to redirect myuser.mydomain.com to the physical path such as www.mydomain.com/myuser/ In case 2 I'd simply rewrite www.mydomain.com/myuser/* to myuser.mydomain.com/* Authentication should not be the problem, I would use the a Filter or something like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery.post refreshes my page? I have the following code with a form on my page. But when I click submit, it seemed like my page refreshes. form: <form action='#' method='post'> <div><input type='text' name='name' /></div> <div><input type='submit' value='Save' /></div> </form> JS: <script type='text/javascript'> $(document).ready(function() { $('form').bind('submit',function() { var str = $('form').serialize(); $.post("save.php", { formString: str }, function(data) { alert("Saved: " + data); } ); }); }); </script> Thanks a lot for any help! A: set a return false; to your form (for example on the onSubmit). Your form is sended by both jQuery ($.post) and the page itself, because you do not stop it to do that. Another option (works the same) is to let the jquery-part disable the default behaviour of your form: //your code $('form').bind('submit',function() { // more of your code return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jQuery Box Area Problem I have a problem - I have 2 or 3 boxes and I am trying to fit them perfectly into a bigger square box of max-width 445px. All boxes should be sized to fill the bigger box. I don't know what any of the box widths or heights will be and therefore the second two boxes should be sized relative to the first ? The aspect ratio of the first box can also change [i.e. be long or be wide] and so the second two boxes should fill. Any ideas ? A: make sure about the boxes size, including the padding and margin. i think you can log out the width and height of the inner boxes by user jQuery.outerHeight(), jQuery.outerWidth()
{ "language": "en", "url": "https://stackoverflow.com/questions/7524973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ERD - Entity relationship diagram - complex and tricky relations Here is the scenario. Two completely different Entities are independently related to the third entity in the same way. How do we represent it in the ERD? or (Enhanced ER) Ex: * *Student "BORROWS" BOOK (from the library) *DEPARTMENT "BORROWS" BOOK (from the same library). If I define 'BORROWS' relationship twice, it would be awkward and clumsy in terms of appearance in the diagram, and increase the complexity of implementation as well. At the same time, I can not declare a ternary relationship since STUDENT and DEPARTMENT are not inter-related in a relationship-instance. However, I couldn't find a better way. How do I solve it? A: If Wikipedia is to be believed, Enhanced ER permits inheritance. Why don't you have a BORROWER entity (with the appropriate relationship), and have STUDENT and DEPARTMENT subclass that? A: I've been having a similar issue - where a company or a person can order a product. You've got an order, that can belong to either a person, or a company - so what do you link the relationship to? I'm thinking orders will have a companyId, and a personId foreign key, but how do you make them exclusive? The data returned won't necessarily be the same - a company doesn't have a first name / last name field for example. I guess it could be done by having a name returned, and in the case of a person build the string out of firstname / lastname, and in the case of a company use the companyname field .
{ "language": "en", "url": "https://stackoverflow.com/questions/7524974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adobe Acrobat converting data entered into fdf How can i convert the data entered in Adobe Acrobat form fields (using submit button) to a fdf file? Anybody has any ideas.? A: You can convert HTML to PDF very simply - i use this http://code.google.com/p/wkhtmltopdf/
{ "language": "en", "url": "https://stackoverflow.com/questions/7524979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to write a Gradle task that can be customised from the command line? I want to provide defaults for my properties, but allow them to be overridden from the command line in a relatively easy way. I'm using Gradle 1.0 Milestone 3. This is what I've got, it works pretty much the way I want but it's quite verbose. It just doesn't seem very Gradle-ish - as opposed to the actual work I'm doing, where 150-odd lines of Java code have compressed down to about 2 lines of gradle script. task sbtCopyTask { fromProp = "defaultCopyFrom" toProp = "defaultCopyTo" overrideFromProp = System.getProperty('fromSysProp') if( overrideFromProp != null && !overrideFromProp.trim().empty ){ fromProp = overrideFromProp } doLast { println "copying ${fromProp} to ${toProp}" } } executing $GRADLE_HOME/bin/gradle sbtCopyTask results in: copying defaultCopyFrom to defaultCopyTo and executing $GRADLE_HOME/bin/gradle sbtCopyTask -DfromSysProp="wibble" results in: copying wibble to defaultCopyTo * *I know there's a copy task build into Gradle - the question I'm asking is "how do I write a build script that is customisable from the command line". *I tried the "-P" command line option - doesn't seem to do what I want. *I want to be able to do this from the command line, properties files or environment variables would be inconvenient. Edit: Doh, 10 seconds after posting - this seems kind of obvious. So, this works fine and is completely good enough for me (unless there's a better way?) fromProp = System.getProperty('fromProp', 'defaultFromProp')
{ "language": "en", "url": "https://stackoverflow.com/questions/7524986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Disable Warning 1591 message in VS 2010 How to disable Warning #1591 message in VS 2010? Now I get Error List filled up wore than 200 such messages. I would like not to have them here. I use XML comment on some of class properties. A: Go into the project properties, the Build tab and in the "Suppress warnings" text box, enter 1591. See this blog post for more details (and a screenshot, albeit from VS2005) of exactly this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android : click link in a page within web view I have included a web application within android web view , and there is a link in the webpage which opens some other site , when the link is clicked it works fine for the first click, however when clicked for the second time the website is not found , the code is : @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("some site ")) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(i); return true; } else { view.loadUrl(url); return false; } } @THelper and @mikegr, thanks for the reply, Actually in my case i have a modal panel (JSF) in my web application which contains some buttons, on clicking the button i am opening some other site using javascript window.open() method which works fine in desktop browser, however, when i wrap this web application within android webview, everything works fine except when i first click this button i'm able to open the other site using the external browser, however on second click the webview tries to open this othersite within the webview instead of the external browser and i get website not found with the entire URL of the other site, this happens even when i logout and login again as the application launched is still running. also in my case after sometime when the application is idle i get the black screen. i surfed through the net and found simillar issue but that didn't help either , here is the link: http://groups.google.com/group/android-for-beginners/browse_thread/thread/42431dd1ca4a9d98 handling links in a webview , any help and ideas would be very helpful for me, this is taking too long for me, since i'm trying to display my web application in the web view, i have only one activity, which contains code like this @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { // so that when launcher is clicked while the application is // running , the application doesn't start from the begnining } else { requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); // Show the ProgressDialog on this thread this.progressDialog = ProgressDialog.show(this, "Pleas Wait..", "Loading", true); browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { Log.i(TAG, "Finished loading URL: " +url); if (progressDialog.isShowing()) { progressDialog .dismiss(); } } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.contains("some site")) { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(i); return true; } else { view.loadUrl(url); return true; } } }); browser.loadUrl("mysite"); } } A: I had the experience that shouldOverrideUrlLoading() is not called in certain circumstances. There are a few bugs about this topic on http://code.google.com/p/android/issues like bug number 15827, 9122, 812, 2887 As a workaround try to add the method onPageStarted() and check if you get this call. For me this method is always called even if shouldOverrideUrlLoading() was not called before. A: onPageStarted worked for me. Had to tweak it a bit, as that method is called when the webview is first rendered too, and I wanted to only execute it on the onClick of the banner's javascript. I was simulating a banner with a custom page, so when the ad.html was being rendered, I avoided the startActivity. Otherwise, it launches the new browser window. WebViewClient newWebClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); if(!url.equals("http://xxxx.ad.html")) view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } }; A: Try to append the System parameter pattern in url before you load that, something like. String url = "http://xxxx.ad.html?t="+System.nanoTime(); and in your shouldOverrideUrlLoading() method remove the query part (in a very first line). int idx; if ((idx = url.indexOf("?")) != -1) { url = url.substring(0, idx); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7524990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: asp.net handle page early? In my Application_BeginRequest I have a list of things I check for rewriting purposes. At the very end I rewrite all paths to default.aspx which then simply has the following <%@ Page Language="C#" EnableSessionState="False"%> <%@ Import Namespace="MyWebsite"%> <% PageRequest.WritePage();%> There probably no (aka nearly nonexistent) overhead but I'll ask anyways. Instead of rewriting, can I just call WritePage instead? A: It depends on what PageRequest.WritePage does and whether you care about the page lifecycle. BeginRequest is just the first event in the page lifecycle. If you are rendering the entire page in this method, and have no controls then just call Response.End afterwards. Keeping the code in the default.aspx has the advantage that you can still use output caching. If you have a lot of logic in WirtePage and this content is cachable, then this will be a significant performance gain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FastCGI/Python thread/timing issue? I'm using the Pyramid framework on a shared server on which mod_wsgi isn't supported. Once I deployed the project, I started getting 500 errors with no really helpful error messages: [Thu Sep 22 21:40:52 2011] [warn] [client IP] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server [Thu Sep 22 21:40:52 2011] [error] [client IP] Premature end of script headers: dispatch.fcgi [Thu Sep 22 21:40:53 2011] [warn] [client IP] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server [Thu Sep 22 21:40:53 2011] [error] [client IP] Premature end of script headers: dispatch.fcgi I wasn't overly sure what was going on, and in a (partial) accident I copied over my app's .ini file with another that used a sqlite connection rather than a postgres connection. Suddenly, my app was up and running. However, I noticed that it seemed like the response was being suddenly cut off (the end of the response wasn't being flushed to the client). I've been banging my head against my keyboard trying to figure out what's going on, so I'm hoping that someone else has encountered similar symptoms and has figured out a solution. My fcgi entry looks like this (in case it helps at all): app = "/dir" inifile = "production.ini" import sys, os sys.path.insert(0, app) from paste.deploy import loadapp wsgi_app = loadapp("config:%s/%s" % (app, inifile)) if __name__ == "__main__": from flup.server.fcgi import WSGIServer WSGIServer(wsgi_app).run() I remember coming across a post somewhere that suggested launching the WSGI server in a separate thread, sleeping the main thread for a period of time, but that seemed like a horrible hack to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7524995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP ADODB with MySQL: ADODB object not working within functions Given a file called index.php which contains: $db = NewADOConnection($db_dsn); if (!$db) die("Connection failed"); $arrpage = $db->GetArray("SELECT * FROM somewhere"); include("functions.inc.php"); details("SELECT * FROM somewherelse"); The $arrpage contains the expect information Then in the functions.inc.php file: function details($query) { global $db; //should check to make sure it exists $options_array = $db->GetArray($query); The $options_array is empty even though it should contain data. var_dump($db) shows the DB object is all there. var_dump($options_array) is blank. * *PHP 5.3.4 *MySQL 14.14 *ADODB 5.14 A: try: $options_array = $db->GetAll($query); A: Well after a lot of troubleshooting, all I needed to do was get up, have a pint of good beer and come back to it another time. The short of it is: the system uses caching and upon close inspection of my error logs I noticed that the the cache files weren't being written to the cache folder because of folder permission issues. I therefore fixed the folder permissions and now that the cache files can be saved, the DB query has something to refer to. Thanks for the help anyways, I do appreciate it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem Retrieving Data from SQL Server using C# and ADO.Net window form I took an video from you tube to Retrieving Data from SQL Server using C# and ADO.Net http://www.youtube.com/watch?v=4kBXLv4h2ig&feature=related I Do the same as him in the video... I want to show data from an sql database in a DataGridView. I get an error whit da.Fill(dg); dg.DataSource = dg.Tables[0]; I name my DataGridView dg... Complete code using System.Data.SqlClient; namespace SQLconnection { public partial class Form1 : Form { SqlConnection cs = new SqlConnection("Data Source=FRANK-PC\\SQLEXPRESS; Initial Catalog=Forc#; Integrated Security=TRUE"); SqlDataAdapter da = new SqlDataAdapter(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { da.InsertCommand= new SqlCommand ("INSERT INTO tblContacts VALUES (@FirstName,@LastName)", cs ); da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text; da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastname.Text; cs.Open(); da.InsertCommand.ExecuteNonQuery(); cs.Close(); } // Display data in dg private void button2_Click(object sender, EventArgs e) { da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs); da.Fill(dg); dg.DataSource = dg.Tables[0]; } } } A: you should open the connection before filling the table with the data adapter, add this: cs.Open(); DataSet ds = new DataSet(); da.Fill(ds); cs.Close(); dg.DataSource = ds.Tables[0]; note that this is anyway a bad practice, there are trillions of examples here in SO on how to handle the SQLConnections, you should use a using block so that it gets closed and disposed immediately after usage and do not have connections or adapters or data tables or sqlcommand global to all form but create them only when/where needed. You should actually move out all data access logic from the UI to a separated class, Business Logic or Data layer. Edit: you should do something like this: using(SQLConnection conn = 'connection string here') { using(SQLCommand cmd = new ('sql query', conn)) { //execute it blah blah } } check out this question: Closing SqlConnection and SqlCommand c# A: The Fill method open/close connection implicitly but the problem is in name of dataGrdiView and DataTable/DataSet reference variable - dg private void button2_Click(object sender, EventArgs e) { da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs); DataTable dt=new DataTable(); da.Fill(dt); dg.DataSource = dt; } A: I'm guessing since you didn't include the exception you are receiving, but you need to open your SqlConnection prior to using it: private void button2_Click(object sender, EventArgs e) { da.SelectCommand = new SqlCommand("SELECT * FROM tblContacts", cs); cs.Open(); da.Fill(dg); cs.Close(); dg.DataSource = dg.Tables[0]; } A: Try it this, but is important know what kind of exception throws. private void button2_Click(object sender, EventArgs e) { cs.Open(); using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM tblContacts", cs)) { DataTable t = new DataTable(); a.Fill(t); dg.DataSource = t; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing mutex in a user level thread library I am developing a user level thread library as part of a project. I came up with an approach to implement mutex. I would like to see ur views before going on with it. Basically, i need to implement just 3 functions in my library mutex_init, mutex_lock and mutex_unlock I thought my mutex_t structure would look something like typedef struct { int available; //indicates whether the mutex is locked or unlocked queue listofwaitingthreads; gtthread_t owningthread; }mutex_t; In my mutex_lock function, i will first check if the mutex is available in a while loop. If it is not, i will yield the processor for the next thread to execute. In my mutex_unlock function, i will check if the owner thread is the current thread. If it is, i will set available to 0. Is this the way to go about it ? Also, what about deadlock? Should i take care of those conditions in my user level library or should i leave the application programmers to write code properly ? A: This won't work, because you have a race condition. If 2 threads try to catch the lock at the same time, both will see available == 0, and both will think they succeeded with taking the mutex. If you want to do this properly, and without using an already-existing lock, You must access hardware operations like TAS, CAS, etc. There are algorithms that give you mutual exclusion without such hardware support, but they make some assumptions that are many times false. For more details about this, I highly recommend reading Herlihy and Shavit's The art of multiprocessor programming, chapter 7. You shouldn't worry about deadlocks in this level - mutex locks should be simple enough, and there is some assumption that the programmer using them should use care not to cause deadlocks (advanced mutexes can check for self-deadlock, meaning a thread that calls lock twice without calling unlock in the middle). A: Not only that you have to do atomic operations to read and modify the flag (as Eran pointed out) you also have to watch that your queue is capable to have concurrent accesses. This is not completely trivial, sort of hen and egg problem. But if you'd really implement this by spinning, you wouldn't even need to have such a queue. The access order to the lock then would be mainly random, though. Probably just yielding would also not be enough, this can be quite costly if you have threads holding the lock for more than some processor cycles. Consider using nanosleep with a low time value for the wait. A: In general, a mutex implementation should look like: Lock: while (trylock()==failed) { atomic_inc(waiter_cnt); atomic_sleep_if_locked(); atomic_dec(waiter_cnt); } Trylock: return atomic_swap(&lock, 1); Unlock: atomic_store(&lock, 0); if (waiter_cnt) wakeup_sleepers(); Things get more complex if you want recursive mutexes, mutexes that can synchronize their own destruction (i.e. freeing the mutex is safe as soon as you get the lock), etc. Note that atomic_sleep_if_locked and wakeup_sleepers correspond to FUTEX_WAIT and FUTEX_WAKE ops on Linux. The other atomics are probably CPU instructions, but could be system calls or kernel-assisted userspace function code, as in the case of Linux/ARM and the 0xffff0fc0 atomic compare-and-swap call. A: You do not need atomic instructions for a user level thread library, because all the threads are going to be user level threads of the same process. So actually when your process is given the time slice to execute, you are running multiple threads during that time slice but on the same processor. So, no two threads are going to be in the library function at the same time. Considering that the functions for mutex are already in the library, mutual exclusion is guaranteed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting the size of some rows in a MySQL-Table I need to get the physical size of some rows in a MySQL-Table. There are some solutions how to read out the size of a whole table over the information scheme, e.g. this article. Is there a way to get the size of a subset of a table? Of course I could manually read out every field in every tuple and get the bytes of the stored word. But I hope there is a better/faster solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delphi: How to wait all info to be read from socket using thread I have Delphi lib which must return information read via socket. function GetBufferInfo(Address: PChar): PChar; export; stdcall; var BD: TBufferData; begin BD := TBufferData.Create; Result := PChar(TBufferData.GetData); BD.Free; end; TBufferData class has a method ReadData which is being called when socket Read event fires. So it can be called several times until all info is read. The problem is how to wait while information is being read and don't go out of GetBufferInfo method. I thought about threads but don't know how exactly it can be done. I created a small example which demonstrates the issue: program Project1; {$APPTYPE CONSOLE} uses SysUtils, Classes, Windows; type TBufferData = class private FResult: string; public constructor Create; procedure ReadData(Sender: TObject; Buf: string; var Size: Integer); function GetData: string; end; { TBufferData } var BD: TBufferData; s: string; { TBufferData } constructor TBufferData.Create; begin FResult := 'Some text received via socket'; end; function TBufferData.GetData: string; begin Result := FResult; end; procedure TBufferData.ReadData(Sender: TObject; Buf: string; var Size: Integer); begin //info is being received from socket FResult := FResult + Buf; end; begin BD := TBufferData.Create; s := BD.GetData; Writeln(s); BD.Free; Readln; end. Thanks in advance Yura A: Only the code that is reading the socket will know when the data is finished. Until it detects that condition, it should not be storing any data for GetBufferInfo() to access yet. Only when the data is finished should GetBufferInfo() then be able to return it. So you need to re-write your code to do that. A: Application.ProcessMessages for console would look like this. State flag will be set outside. while State <> stDone do begin ... ProcessMessages; end; procedure ProcessMessages; var Msg: TMsg; begin if PeekMessage(Msg,0,0,0,0) then begin GetMessage(Msg,0,0,0); DispatchMessage(Msg); end; Sleep(10);//sleep to avoid 25% processor decrease end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7525012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bare minimum of learning in c++ (or what can I skip) I'm currently cramming up on c++ in order to complete a specific task for my 3rd year Applied Computing degree project. Im by no means a programmer but I am going top have to program an App. My most comfortable language is c# so this is what I will be using for the bulk of the logic in my app, however I will need to create a c++ DLL to get the values I need to work with in the app. So, my question is, to save me having to go through everything from beggining to end in a begginners c++ book (as I am currently) what do i need to learn and what can I skip to be able to get values from 'wlanapi' (and by extension any other native api/library/dll) and make them available to my c# program? As it stands I've been at it for a week and all i've covered is Declarations, Variables, Input/Output, Arithmetic Operators and am currently trudging through 'bitwise operators' (which I know i will never use). edit Ok, I'll be specific. What would be the c++ equivalent of of querying WMI classes in c# using ManagementObjectSearcher? In particular I wish to use the WlanAPI to get the RSSI and SSID's of multiple wireless AP's. Many Thanks A: The WINAPI was originally designed for C. Because of this, you can skip over a lot of the C++ specific parts of C++. Big stuff to skip: * *Objects *Templates *Anything in the STL (Standard Template Library) * *Iterators *IO Streams *C++ Strings Big stuff to focus on: * *Dynamic vs Static memory allocation *Pointers *Arrays *C-strings * *WINAPI provides safe alternatives for unsafe methods in <cstring> *WINAPI uses unicode, not ASCII. *Structs To be honest, there is no reason you should even be using C++. You should probably be using C for this instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Programatic navigation in Visual SourceSafe Maybe this is a very simple problem, but I just can't figure it out. Is there any way to navigate to a certain folder in MS Visual SourceSafe from an external application? Maybe some sort of command line parameter? (of course that would only work if VSS is closed). Or is there a solution that would also work if VSS is already opened? (COM?) Thanks! A: Here is VBS sample code to start programmatically control VSS: const SS_INI_PATH = "с:\db\vss\srcsafe.ini" const SS_LOGIN = "login" const SS_PASSWORD = "password" set obj = CreateObject("SourceSafe") obj.Open SS_INI_PATH, SS_LOGIN, SS_PASSWORD set objPrj = obj.VSSItem("$/project1") ' call below any objPrj methods Help on object interfaces you can find here: http://msdn.microsoft.com/en-US/library/microsoft.visualstudio.sourcesafe.interop(v=vs.80).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7525015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Float to Real in SQL Server I am attempting to use Entity Framework and have a contact database that has Longitude and Latitude data from Google Maps. The guide says that this should be stored as float. I have created my POCO entity which includes Longitude as a float and Latitude as a float. I have just noticed that in the database, these both come up as real. There is still a lot of work to be done before I can get any data back from Google, I am very far away from testing and I was just wondering if anyone can tell me if this is going to be a problem later on? A: Nope, that should be fine. Note that you may not get the exact same value back as you received from Google Maps, as that would have been expressed in decimal-formatted text. However, this is effectively a physical quantity, and thus more appropriate as a float/double/real/(whatever binary floating point type you like) than as a decimal. (Decimals are more appropriate for man-made quantities - particularly currency.) If you look at the documentation for float and real you'll see that real is effectively float(24) - a 32-bit floating binary point type, just like float in C#. EDIT: As noted in comments, if you want more than the significant 7-8 digits of accuracy provided by float, then you probably want double instead in C#, which would mean float(53) in SQL Server. A: This link: http://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspx explains that, in SQL Server, real is a synonym for float(24), using 4 bytes of data. In .NET a Single precision floating point number also uses 4 bytes, so these are pretty much equivalent: http://msdn.microsoft.com/en-us/library/47zceaw7(v=vs.71).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7525021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Standard string behaviour with characters in C++ I have a problem which I do not understand. I add characters to a standard string. Whe I take them out the value printed is not what I expected. int main (int argc, char *argv[]) { string x; unsigned char y = 0x89, z = 0x76; x += y; x += z; cout << hex << (int) x[0] << " " <<(int) x[1]<< endl; } The output: ffffff89 76 What I expected: 89 76 Any ideas as what is happening here? And how do I fix it? A: The string operator [] is yielding a char, i.e. a signed value. When you cast this to an int for output it will be a signed value also. The input value cast to a char is negative and therefore the int also will be. Thus you see the output you described. A: Most likely char is signed on your platform, therefore 0x89 and 0x76 become negative when it's represented by char. You've to make sure that the string has unsigned char as value_type, so this should work: typedef basic_string<unsigned char> ustring; //string of unsigned char! ustring ux; ux += y; ux += z; cout << hex << (int) ux[0] << " " <<(int) ux[1]<< endl; It prints what you think should print: 89 76 Online demo : http://www.ideone.com/HLvcv A: You have to account for the fact that char may be signed. If you promote it to int directly, the signed value will be preserved. Rather, you first have to convert it to the unsigned type of the same width (i.e. unsigned char) to get the desired value, and then promote that value to an integer type to get the correct formatted printing. Putting it all together, you want something like this: std::cout << (int)(unsigned char)(x[0]); Or, using the C++-style cast: std::cout << static_cast<int>(static_cast<unsigned char>(x[0])) A: The number 0x89 is 137 in decimal system. It exceeds the cap of 127 and is now a negative number and therefore you see those ffffffthere. You could just simply insert (unsigned char) after the (int) cast. You would get the required result. -Sandip
{ "language": "en", "url": "https://stackoverflow.com/questions/7525026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WAMP PHP says it's deprecated | =& I'm using WAMP2 with PHP 5.3.4 When I use =& in my code it says it's deprecated. Why? Is there any alternative? Thanks A: If you're using it with objects - then it's superfluous since php 5.0, as long as objects always are passed by reference. So just replace your =& with = and behaviour will not change.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to check if a javascript checkbox array element is checked or not? What is want is - when the checkbox is checked option no. 5 in select list will be selected and when the checkbox is unchecked option no. 0 will be selected in the select list. The select list and the checkboxes are generated dynamically in the php code as below : echo "<select name='coupons".$i."' id='coupons".$i."'>"; ------- All Options -------- echo "</select>"; <input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode("myCheckbox[]",<?php echo $i;?>)'> ----------------------------------------------------------------------------- Solved the second requirement on my own now ..... thanks to all for your inputs just added the following line in the checkAll() within the for loop setCCode(children[i],i+1); The javascript function : function setCCode(checkbox_name,i) { var form_object = document.getElementsByName(checkbox_name+"["+i+"]"); var selname = document.getElementsByName("coupons"+i)[0]; if(form_object.checked) { selname.selectedIndex = 5; } else { selname.selectedIndex = 0; } } The above issue is solved....... thanks to all Now what i need to do is when a user checks a checkbox to select or deselect all the dynamically generated checkboxes on the form the above logic should work. <input type='checkbox' name='checkall' onChange="checkAll(this, 'myCheckbox[]')"> <span class="chkall">Check / Uncheck All</span> <input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'> The javascript code i am using to select/deselect all checkboxes on form is as below : function checkAll(parent, field) { var children = document.getElementsByName(field); var newValue = parent.checked; for (i = 0; i < children.length; i++){ if (children[i].disabled == false) { children[i].checked = newValue; } } } function setCCode(Sender,i) { document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0; } A: getElementsByName returns an array of objects. Replace the line with: var form_object = document.getElementsByName(checkbox_name+"["+i+"]")[0]; A: If you have a reference to the form that the checkbox is in, and it has a unique name in the form, then you can access it as: form_object = form.elements[ checkbox_name + "[" + i + "]" ]; and you can also use the ternary operator to make the code more concise: selname.selectedIndex = form_object.checked? 5 : 0; Edit Sorry, missed the obvious. If you pass a refereference to the checkbox in the handler, then you can also get the form (all form controls have a form property that references the form they are in). So as Jan Pfeifer suggested (abbreviated markup): <input ... onclick='setCCode(this, <?php echo $i;?>)'> then the script is just: function setCCode(checkbox, i) { checkbox.form.elements['coupons' + i].selectedIndex = checkbox.checked? 5 : 0; } A: You can pass refference to the checkbox itself as a parameter <input type='checkbox' name='myCheckbox[]' value='<?php echo $i."_".$row->id; ?>' onclick='setCCode(this,<?php echo $i;?>)'> function setCCode(Sender,i) { document.getElementsByName("coupons"+i)[0].selectedIndex = Sender.checked ? 5 : 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copying unmanaged memory to Managed byte array I need to read unmanaged memory into a managed byte array. For this I have an IntPtr reference to unmanaged memory and a length which represents the size of the unmanaged memory that is of interest to me. I use the following code to read that into a managed byte array. byte[] pixelDataArray = new byte[pixelDataLength]; for (int i = 0; i < pixelDataLength; i++) { pixelDataArray[i] = Marshal.ReadByte(pixelData, i); } However this results in very poor performance. Calling this method 1000 times with 256KB of unmanaged memory, takes more than 7 seconds. I think there must be a more efficient way of doing this. I could not use Marshal.PtrToStructure because i would not know the size of the memory that need to read upfront. Any ideas on how the performance of this function can be improved? A: Instead of looping try copying the entire chunk: Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataLength); A: Use Marshal.Copy(). byte[] pixelDataArray = new byte[pixelDataLength]; Marshal.Copy(pixelData, pixelDataArray, 0, pixelDataArray.Length);
{ "language": "en", "url": "https://stackoverflow.com/questions/7525047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Random string avoiding words in array behaving incorrectly I found some unexpected behavior in my code, so made two examples to demonstrate what was happening and couldn't figure things out from there. What I found was odd to me, and perhaps I'm missing something. Goal: Create a random string and avoid anything specified in an array. In the examples below, I have two methods of testing this. First I have a function that creates a random string from specified characters ($characters) and then I have an array ($avoid) (here with double letters specified) which then loops and informs you if the code worked and it indeed found what was specified in the array. This seems to work, however then I modified the second function to attempt to generate a new random string if the same trigger happened. This to avoid having a string with anything in the array. This part doesn't seem to work.. I'm not sure how else to modify it from here, but I must be missing something. Running the code works, but it catches some things and misses other times.. which I wouldn't expect from code. function getrandom($loopcount) { $loopcount++; $length = 20; $characters = 'abc'; $string = ''; for ($p = 0; $p < $length; $p++) $string.= $characters[ mt_rand( 0,strlen($characters) ) ]; $avoid = array( 'aa', 'bb', 'cc' ); foreach ($avoid as $word) if ( stripos($string,$word) ) $string = 'Double '.$word.' Detected:'.$string; return '<h1 style="color:blue;">'.$string.'<h1>'; } echo getrandom(0); echo getrandom(0); echo getrandom(0); function getrandom2($loopcount) { $loopcount++; $length = 20; $characters = 'abc'; $string = ''; for ($p = 0; $p < $length; $p++) $string.= $characters[ mt_rand( 0,strlen($characters) ) ]; $avoid = array( 'aa', 'bb', 'cc' ); foreach ($avoid as $word) if ( stripos($string,$word) ) $string = getrandom2($loopcount); return '<h1 style="color:green;">'.$string.'<h1>'; } echo getrandom2(0); echo getrandom2(0); echo getrandom2(0); A: I used this one function randomToken($length) { srand(date("s")); $possible_charactors = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $string = ""; while(strlen($string)<$length) { $string .= substr($possible_charactors, rand()%strlen($possible_charactors),1); } return($string); } A: You need to check stripos() with a tripple operator, otherwise your if will interpret the occurrence at position 0 as false (1) foreach ($avoid as $word){ if ( stripos($string,$word) !== FALSE){ $string = getrandom2($loopcount); } } (1) http://php.net/manual/en/language.operators.comparison.php A: The following worked for me: print gen_rand_str_avoid('abc', 20, array('aa', 'bb', 'cc')); function gen_rand_str($chars, $length) { $str = ''; for ($i = 0; $i < $length; $i++) { $str .= $chars[mt_rand(0, strlen($chars) - 1)]; } return $str; } function gen_rand_str_avoid($chars, $length, array $avoids) { while (true) { $str = gen_rand_str($chars, $length); foreach ($avoids as $avoid) { if (stripos($str, $avoid) !== false) { continue 2; } } break; } return $str; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Controlling an embedded user interface I am busy with a small project that allows for the controlling of an embedded hardware user interface to be moved from state charts and simple constructs as if .. else to a more visual representation. I would now like to begin testing on a real project. I am looking for an open source hardware project. I've searched around but I have not been able to find anything that meets my requirements. 1/ hardware and software publicly available (i'm don't mind having to buy something) 2/ written in C/C++ 3/ has graphical user interface Any ideas? Thank you A: You might take a look at the open source QP state machine frameworks, which are also supported by the free graphical modeling tool called QM (state-machine.com). QP run on many embedded MCUs, including Arduino and mbed rapid prototyping platforms. The webstie contains a lot of information, including using statecharts for embedded GUIs. A: This is not C++ but free with sources and might give you an idea: If made to work on Linux, it may be combined with fpGUI on ARM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Imagehack and paperclip how to create a thumb and define path and filename? I am trying to create a thumb with and uploaded image. I also want to resize the uploaded image to 672x378 and the thumb is should be 219x123. The path for the thumb should be photographer/image/:id/thumb:Filename I have installed imageshack (gem 'Rmagick') and intstalled the program on my pc. My model: has_attached_file :image, :storage => :s3, :bucket => 'mybucket', :path => '/photographer/image/:id/:filename', :s3_credentials => { :access_key_id => 'mykey', :secret_access_key => 'mykey' } A: It looks like you want to attach images to photographers. So in that case I would include this code on the photographer model. has_attached_file :image, :styles => { :original => "672>x378>", :thumb => "219>x123>" }, # width x height :storage => :s3, :bucket => "mybucket", :path => "photographers/:id/images/:style/:basename.:extension", :s3_credentials => { :access_key_id => 'mykey', :secret_access_key => 'mykey' } Not that the > after the size of the images will restrict the width from exceeding the value, but still keep the image in proportion. So, the image can't go larger than the height or width. You can remove those if you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Localization using ultrasonic sensors I don't know if this is the right place to ask this question. I am working on a project in which I have to use ultrasonic sensors only to do "simultaneous localization and mapping" of robot. I have 8 such sensors. Assume that i have enough computation power and the limited sensing(8 ultrasonic sensor) capability. What would be an appropriate algorithm to use in this case? A: I found SLAM for Dummies to be very helpful. A: According to your question, the algorithm to use is SLAM. There are many possible SLAM implementations. http://openslam.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7525053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can i create executable apple .app file from my java .jar file? I have created an executable java Swing .jar application. It works fine on Windows. The application hierarchy is : application.jar images(Folder) .......... Contains all images the application uses. libraries(Folder) ....... Contains all external jar libraries the application uses. bundles(Folder) ......... Contains all bundle files the application uses. database(Folder) ........ Contains the database files the application uses. All the above folders exist outside the jar file. Now i am trying to create a Mac executable file (.app) from "application.jar" to run it on Mac so i used the "Jar Bundler" as specified here but when i run the output application.app file nothing happens, nothing runs and i can't even debug it. I think the main reason is that it can't see the external folders. So is it impossible to create a .app file if the application has external folders ? And is there a way to debug the .app file to see what's going on ? A: Nothing runs, and i can't even debug it. Diagnostic output from the launch process may be obtained as follows: $ export JAVA_LAUNCHER_VERBOSE $ ./YourApplication.app/Contents/MacOS/JavaApplicationStub There's a related example here. A: Most likely the problem is your working directory. * *When you run an executable JAR file by double-clicking it, the working directory is the parent directory of the JAR file. *By default, the working directory of an application bundle is its parent directory. If you package the external folders into the application bundle they will be located under $APP_PACKAGE/Contents/Resources. So the assumption about the working directory that you make for an executable JAR file does not hold for an application bundle. In order to set the working directory to the resources directory, add <key>WorkingDirectory</key> <string>$APP_PACKAGE/Contents/Resources</string> to the Info.plist file of your bundle. In case you know nothing about application bundles, please read this document. A: This might help: AppBundler by Josh Marinacci A: I am not sure about your exact directory hierarchy. But on a Mac with Xcode installed is an application called "Jar Bundler". It exist for exact that purpose you are asking for. BTW, Mac application use the suffix .app, that is right. But they are not files. Thery are directories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make "Enter" Key Behave like Submit on a JFrame I'm Building a Client/Server application. and I want to to make it easy for the user at the Authentication Frame. I want to know how to make enter-key submits the login and password to the Database (Fires the Action) ? A: One convenient approach relies on setDefaultButton(), shown in this example and mentioned in How to Use Key Bindings. JFrame f = new JFrame("Example"); Action accept = new AbstractAction("Accept") { @Override public void actionPerformed(ActionEvent e) { // handle accept } }; private JButton b = new JButton(accept); ... f.getRootPane().setDefaultButton(b); A: Add an ActionListener to the password field component: The code below produces this screenshot: public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Test"); frame.setLayout(new GridLayout(2, 2)); final JTextField user = new JTextField(); final JTextField pass = new JTextField(); user.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pass.requestFocus(); } }); pass.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = user.getText(); String password = pass.getText(); System.out.println("Do auth with " + username + " " + password); } }); frame.add(new JLabel("User:")); frame.add(user); frame.add(new JLabel("Password:")); frame.add(pass); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to remove the Username field from the UserCreationForm in Django I want my user registration page to display email and password field, and no username. I have created this Register Form: class RegisterForm(UserCreationForm): email = forms.EmailField(label = "Email") #fullname = forms.CharField(label = "First name") class Meta: model = User fields = ("email", ) def save(self, commit=True): user = super(RegisterForm, self).save(commit=False user.email = self.cleaned_data["email"] if commit: user.save() return user But the username still appears. Do I need to override something else? A: You can pop out the username from the form's fields like so: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) # remove username self.fields.pop('username') ... But then you would need to fill-in some random username before saving like so: from random import choice from string import letters ... class RegisterForm(UserCreationForm): ... def save(self): random = ''.join([choice(letters) for i in xrange(30)]) self.instance.username = random return super(RegisterForm, self).save() There are other considerations to take when you hack it this way, like making sure your LoginForm would pull the username later on when it is needed: class LoginForm(AuthenticationForm): email = forms.EmailField(label=_("E-mail"), max_length=75) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['email'].required = True # remove username self.fields.pop('username') def clean(self): user = User.objects.get(email=self.cleaned_data.get('email')) self.cleaned_data['username'] = user.username return super(LoginForm, self).clean() A: Found it. This is exactly what I wanted to do: http://www.micahcarrick.com/django-email-authentication.html A: Add that field to the Meta class's exclude: class RegisterForm(UserCreationForm): email = forms.EmailField(label = "Email") #fullname = forms.CharField(label = "First name") class Meta: model = User exclude = ['username',]
{ "language": "en", "url": "https://stackoverflow.com/questions/7525062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: The apk must be signed with the same certificates as the previous one I am trying to upgrade my previous version app into the Android market,but it shows an error as "The apk must be signed with the same certificates as the previous one". I am also having previous version apk file.but dont know how to solve this certificate issue..Can someone pls guide me the steps on how to upgrade this new version app? A: You should definitely read this: http://developer.android.com/guide/publishing/app-signing.html When you published the app the first time you must have used a certificate - it's mandatory. To upgrade the app you must use the same certificate to sign the upgraded app. If you lost the certificate, there is no way to perform upgrade. You will need to remove app from market and add a new one. This will not upgrade the app for existing users. A: For upgrading any application certificate must be same as before or you can do by installing whole application and again reinstall A: Just use the same keytool that you used for previus app...
{ "language": "en", "url": "https://stackoverflow.com/questions/7525065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accesing a strict private field using the RTTI consider this simple code {$APPTYPE CONSOLE} uses Rtti, SysUtils; type {$M+} TFoo = class strict private class var Field1 : Integer; field2 : Integer; private field3 : Integer; class var Field4 : Integer; end; Var ctx : TRttiContext; f : TRttiField; begin try ctx:=TRttiContext.Create; for f in ctx.GetType(TFoo).GetFields do Writeln(f.Name); Writeln('Done'); readln; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. When you run this, only the field3 is listed. it seems which the RTTI does not support fields which are strict private or class var, So the questions are Is possible access a strict private field of a delphi class using Rtti or another method? and I read the documentation of the RTTI.TRttiType.GetFields method but does mention these restrictions, Exist any paper or article which mentions such limitations? A: I can't try it right now, but what you seem to need could be GetDeclaredFields instead of GetFields. This should give all (instance) fields of a class but not those of an ancestor class. If you need those too, you'll have to recursively go up the inheritance chain. As I said, I can't try it right now, so you'll have to see for yourself if it gives you access to strict private fields as well. Update Note that in your declaration of TFoo, even you probably didn't intend it, both Field1 and Field2 are class variables!. Just reformat your declaration, and you'll see what I mean: TFoo = class strict private class var Field1: Integer; Field2: Integer; private // etc... Everything that comes after class var is a class variable, until the compiler encounters var, strict, private, protected, etc. Try this, and you'll also see Field2 being written: TFoo = class strict private class var Field1: Integer; var Field2: Integer; // etc... Alternatively try: TFoo = class strict private Field2: Integer; class var Field1: Integer; // etc... This means that GetFields and GetDeclaredFields don't have any problems with strict private fields. They just don't return class variables. That makes sense, IMO. Class variables are not members of the object being investigated. A: Access to strict private members of a class is possible with Class Helpers. See access-a-strict-protected-property-of-a-delphi-class for a working example. Related is also how-can-access-the-value-of-a-class-var-using-the-address-of-the-class-and-a-offset-to-the-variable, where class helpers is used to access a strict private class var. A: By definition, strict private is only visible in the scope of the class itself. They should still be accessible with Hallvard's hack #5, though (except for class fields, I think).
{ "language": "en", "url": "https://stackoverflow.com/questions/7525071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Php Managing online / offline? I wonder if this is a good solution for a medium size social site. Its about managing online/offline indications of users. My solution is to include a script on each page that first of all updates the "last activity" field of the current user with a timestamp, then i select all users that havent been active within the session expire time(but is still online accordingly to the table) and sets the online flag(in db) to false. Is this a solution that is commonly used or will the sever load be to much when a bigger amount of users are navigating throug the site? Is there any better solution? Be aware that im not only intrested in the amount of online users but also names, therefore a session based script seems to complicated and inaccurate. Thanks in advance! A: It is good enough but better you could store this information in activity table: for any active user insert/update a row with his user_id and for inactive for more than N minutes one - remove rows. A: A table that stored sessions should contain a field called "LAST_ACTIVITY_DATE", TIMESTAMP. So whenever they load a new page or you update something with AJAX, just update LAST_ACTIVITY_DATE with current_timestamp. Then when you need to get online users, get those who have last_activity_date within 5 minutes from Current_timestamp. Easy as!
{ "language": "en", "url": "https://stackoverflow.com/questions/7525073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use Virtualizer in a web aplication? In my application i am using Jasper reports to generate the report in various formats. Now i am trying to generate a report for a huge resultset. When i went through the net, found that we can to use virtualizers in order to handle huge data. I am using JRSwapFileVirtualizer, the problem is when is create the JRSwapfile it is throwing File not found exception. I am providing the real path of the folder which i have created in the server, I am using WAS 6.0 server Please let me know what i am doing wrong. My Code JRSwapFile swapFile = new JRSwapFile("http://localhost:9080/contextPath/reports", 2048, 1024); JRSwapFileVirtualizer virtualizer = new JRSwapFileVirtualizer(3,swapFile, true); The Exception net.sf.jasperreports.engine.JRRuntimeException: java.io.FileNotFoundException: http:\localhost:9080\context-path\reports\swap_864564104_1316758806309 (The filename, directory name, or volume label syntax is incorrect.) A: Get the absolute contextPath from session: HttpSession session = request.getSession(false); ServletContext context = session.getServletContext(); ServletContextResource context = new ServletContextResource(context,"/reports"); Your code: JRSwapFile swapFile = new JRSwapFile(context.getFile().getAbsolutePath(), 2048, 1024);
{ "language": "en", "url": "https://stackoverflow.com/questions/7525075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sitemesh or XSLT for layout I am designing a layout for my crm project now. Now i am ended with 2 options one is sitemesh to define the layout or XSLT to define a layout. Sitemesh will run at runtime from the server , it wont cause any issue if the number of request is high? I guess XSLT will run at the browser based on the Xpath , is this correct? Which one is better to use? Please help me Thanks A: You can run XSLT either in the browser or at the server. The advantage to running it at the server is that the HTML you generate will be the same regardless of what browser the user has. If you run it in the web browser, users with different browsers might get slightly different results, because different XSLT transformation engines have different quirks, kind of like different web browsers do when rendering the same HTML and CSS. I've designed and taught a corporate 1-day intro to XSLT class. I love the way XSLT works. That said, it has been criticized for running slowly and being hard to learn. I've just started using SiteMesh 2.0, and I really like it. If you are not familiar with XSLT coding, you may be more comfortable with SiteMesh, because it simply wraps your content with a header/footer you create. You don't have to write and debug XSLT code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proper SQL query command with SQL Compact is failing I've got a function that stores temporary information generated for every user authenticated in the system. This 'session ID' is a string stored in a Sessions table, along the original ID of the user which authenticated and was given said session identifier. The function to remove/deauthenticate/invalidate an existing session first checks if the user exists through another method implemented as follows: int userId = 0; SqlCeCommand cmd = new SqlCeCommand(); SqlCeParameterCollection sqlParams = cmd.Parameters; sqlParams.AddWithValue("@User", userName); cmd.Connection = this.conn; cmd.CommandText = "SELECT Id FROM Users WHERE (Username = @User)"; userId = (int) cmd.ExecuteScalar() cmd.Dispose(); Afterwards it tries to find an existing session for that user, which is to be removed (via a different method again): SqlCeCommand cmd = new SqlCeCommand(); SqlCeParameterCollection sqlParams = cmd.Parameters; sqlParams.AddWithValue("@SID", mysession); sqlParams.AddWithValue("@UID", myuserid); cmd.Connection = this.Connection; cmd.CommandText = "SELECT Id FROM UserSessions WHERE (SessionID = @SID) AND (User_Id = @UID)"; int foo = cmd.ExecuteNonQuery(); ...which fails. No exception is raised unfortunately. So I added an insecure equivalent using a non parametrized query string: cmd.CommandText = String.Format("SELECT Id FROM UserSessions WHERE (SessionID = '{0}') AND (User_Id = {1})", mysession, myuserid); cmd.Prepare(); int bar = cmd.ExecuteNonQuery(); Added a breakpoint, paused, copy pasted the query into the Visual Studio Query tool and voila, it indeed worked. But after continuing, that query in the code failed as well. I'm unable to find the culprit of this annoying issue since no exception is raised and everything seems correct. The data exists, the parameters are provided in proper types (string and int) and I'm out of things to check. The connection is open and so forth. Any clues from anyone around? Thanks! Update: Mea culpa, missed the fact that the function used ExecuteScalar until I modified it for testing. It does use ExecuteScalar and returns null, just in case. A: You're using ExecuteNonQuery: int foo = cmd.ExecuteNonQuery(); ... but you're clearly trying to execute a query (a SELECT)! Use ExecuteScalar again, as you did in the first code, or ExecuteReader and look through the results appropriately. If you stick with ExecuteScalar, you should first check whether the result is null to indicate no results. ExecuteNonQuery returns the number of rows affected by an UPDATE/INSERT/DELETE command - which is what it's intended for. I suspect it's returning -1 for you, as documented: For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1. (Emphasis mine.) A: Use set [] to avoid ambiguity with database keyword. cmd.CommandText = "SELECT [Id] FROM [Users] WHERE ([Username] = @User)"; and use ExecuteScalar() or ExecureReader() method when working with SELECT statements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: htaccess regular expression syntax I want redirect url http://www.domain.com/category/abc-xyz-zzz-2010-150857.html to http://www.domain.com/category/150857-abc-xyz-zzz-2010.html But if http://www.domain.com/category/150857-abc-xyz-zzz-2010.html not redirect this is my htaccess but not work RewriteRule ^([^.]+)/([A-Za-z]+)-([0-9]+).html$ $1/$3-$2.html [L,R=301] Pleas help me fix it I fixed RewriteRule ^([^.]+)/([A-Za-z]*)-([^.]+)-([0-9]+).html$ $1/$4-$2-$3.html [L,R=301] A: Try this: RewriteRule ^([^.]+)/([0-9]+)-([A-Za-z0-9]+).html$ $1/$3-$2.html [L,R=301] A: RewriteRule ^category/([a-zA-Z]*)-([a-zA-Z]*)-([a-zA-Z]*)-(\d+)-(\d+).html$ category/$5-$1-$2-$3-$4.html [L] A: ^([^.]+)/([A-Za-z]+)-([0-9]+).html$ $1/$3-$2.html Your problem here is that you don't take the dashes or even the second group of numbers into account. This one should work: ^(.+)/([A-Za-z\-]+)-([0-9]+)-([0-9]+)\.html$ $1/$4-$2-$3.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7525098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Change the URL in partial post back I am developing a shopping site where user can search products using different criteria. On checked_changed event of check box i want to change URL, but condition is that my page does not make full post back.. A: This answer will help you...... You need HTML5-able browser and some JavaScript. Here is the demo of HTML5 history feature. GitHub implemented that feature for tree browsing. And there is screencast in railscast.com. Original answer is : change url without making page postback -- mvc A: Perhaps this is the solution http://www.asual.com/jquery/address/ - asual provides the functionality for easily changing addresses on the fly A: What I can see there is the same functionality where we link an anchor tag to a div in the same page by appending #. You can see the the URL is changing by just appending the #!gender=men/page=1 to the end. Also there is no checkbox. I saw that portion in firebug. Its just an image. But we can achieve it through checkbox as well on the onclick event but just appending the #[your params] to the URL. Thanks, Sayed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: getting a user-inputed variable in django template wihtout using forms I have a django template which also has a div element that takes in a user_inputed value. When the value is entered, I call a javascript function say onSubmit(user_input) <input type="text" class= "inputtext" onKeyPress="return onSubmit(this.value)"> Now in this onSubmit() function which now has the user-inputted value user_input, I want to be able to use url patterns to a direct to a view, like function onSubmit(user_input) {window.location = "{% url myview user_input %}";} The problem here is that since user_input is empty when the template is loaded, the url-view reverse lookup gives an error. Is there a way to trigger this lookup only when the onSubmit function is called. I know form is an alternative, but it just feels like it'll be an overkill for this situation. A: You can get the URL via AJAX: views.py: def get_url(request): name = request.GET.get('name') args = reguest.GET.get('args', []) kwargs = request.GET.get('kwargs', {}) try: url = django.core.urlresolvers.reverse(name, args=args, kwargs=kwargs) except NoReverseMatch: url = None return django.http.HttpResponse(url) urls.py #... ('^url$', get_url) #... js: function onSubmit(user_input) { var args = [user_input]; jQuery.get('/url', {'args': args}, function(data) { var url = data; if (url) { window.location = url; } else { alert('fail'); } }); } Alternatively, if your URL rule is simple enough, you can use some placeholder when resolving and URL, and before submitting the form you should replace it with real input: var fakeUrl = '{% url myview "%s%" %}'; function onSubmit(user_input) { window.location = fakeUrl.replace('%s%', user_input); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ROR + Unable to install tiny_tds Here I am trying to fetch data from MS-SQL Server 2008 to my Rails application on Ubuntu 10. But I am unable to install tiny_tds. I follow the step given at github. But no response. Please guide me to setup correctly. Used gem command :: gem install tiny_tds This command as well :: gem install tiny_tds –with-freetds-include=/usr/local/include/freetds –with-freetds-lib=/usr/local/lib Error : Installing tiny_tds (0.4.5) with native extensions /home/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/rubygems/installer.rb:483:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError) /home/.rvm/rubies/ruby-1.9.2-p180/bin/ruby extconf.rb looking for library directory /home/.rvm/gems/ruby-1.9.2-p180@rails3/lib ... no looking for library directory /home/.rvm/gems/ruby-1.9.2-p180@rails3/lib/freetds ... no looking for library directory /home/.rvm/gems/ruby-1.9.2-p180@global/lib ... no looking for library directory /home/.rvm/gems/ruby-1.9.2-p180@global/lib/freetds ... no looking for library directory /home/.rvm/rubies/ruby-1.9.2-p180/lib ... yes checking for main() in -lsybdb... no looking for library directory /home/.rvm/rubies/ruby-1.9.2-p180/lib/freetds ... no looking for library directory /home/.rvm/lib ... yes checking for main() in -lsybdb... no looking for library directory /home/.rvm/lib/freetds ... no looking for library directory /home/lib ... no looking for library directory /home/lib/freetds ... no looking for library directory /usr/local/lib ... yes checking for main() in -lsybdb... no looking for library directory /usr/local/lib/freetds ... no looking for library directory /usr/lib ... yes checking for main() in -lsybdb... no ----- Can not find FreeTDS's db-lib or include directory. ----- *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/home/.rvm/rubies/ruby-1.9.2-p180/bin/ruby --enable-iconv --disable-iconv --enable-iconv --disable-iconv --with-freetds-dir --without-freetds-dir --with-freetds-include --without-freetds-include=${freetds-dir}/include --with-freetds-lib --without-freetds-lib=${freetds-dir}/lib --enable-lookup --disable-lookup --with-sybdblib --without-sybdblib --with-sybdblib --without-sybdblib --with-sybdblib --without-sybdblib --with-sybdblib --without-sybdblib looking for library directory /usr/lib/freetds ... no looking for library directory /usr/local/ruby/lib ... no looking for library directory /usr/local/ruby/lib/freetds ... no Gem files will remain installed in /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/tiny_tds-0.4.5 for inspection. Results logged to /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/tiny_tds-0.4.5/ext/tiny_tds/gem_make.out from /home/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/rubygems/installer.rb:486:in `block in build_extensions' from /home/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/rubygems/installer.rb:446:in `each' from /home/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/rubygems/installer.rb:446:in `build_extensions' from /home/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/rubygems/installer.rb:198:in `install' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/source.rb:101:in `block in install' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/rubygems_integration.rb:78:in `preserve_paths' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/source.rb:91:in `install' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/installer.rb:58:in `block (2 levels) in run' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/rubygems_integration.rb:93:in `with_build_args' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/installer.rb:57:in `block in run' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/spec_set.rb:12:in `block in each' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/spec_set.rb:12:in `each' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/spec_set.rb:12:in `each' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/installer.rb:49:in `run' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/installer.rb:8:in `install' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/cli.rb:222:in `install' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/vendor/thor/task.rb:22:in `run' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/vendor/thor.rb:246:in `dispatch' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/lib/bundler/vendor/thor/base.rb:389:in `start' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/gems/bundler-1.0.15/bin/bundle:13:in `<top (required)>' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/bin/bundle:19:in `load' from /home/.rvm/gems/ruby-1.9.2-p180@rails3/bin/bundle:19:in `<main>' A: As ar3 says, the answer above is correct. For those on CentOS, the RPM is freetds-devel, not freetds-dev (in case you're as soft with sysadmin as I am). yum install freetds-devel A: Did you install freeTDS prior to install the gem? sudo apt-get install freetds-dev Then gem install tiny_tds A: The answer above is correct, this is just an additional note for those mac folks that prefer homebrew It command is essentially the exact same: brew install freetds A: For mac users first install freetds by gem install tiny_tds then get the freetds path by ls /opt/homebrew/Cellar/freetds my version is 1.3.10 then gem install tiny_tds -- --with-freetds-dir=/opt/homebrew/Cellar/freetds/1.3.10 A: Try with this, Download freetds from following link and install it freetds download link Install with following instructions: cd /home/user/Downloads/ tar -zxvf freetds-1.00.23.tar.gz Then cd freetds-1.00.23/ ./configure make sudo make install After freetds installation complete, try with bundle install This will solve freetds dependency issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Unable to Uninstall yahoo messenger from system Hi i've installed Yahoo messenger on my system. Now i want to uninstall. But i can't able to uninstall through Control Panel\Programs and Features. When i click uninstall button, a dialog alert displayed as "An error occurred while trying to uninstall yahoo messenger. It may have already been uninstalled. Would you like to remove Yahoo!messenger for the programs and features list?" But unable uninstall. My system os is windows server - service pack 1. Pls help me, how to uninstall the yahoo messenger from my system. A: Try another uninstalling software such as Revo Uninstaller. Btw, you could have a look at these links frome Lifehacker, they can help you: * *http://lifehacker.com/373120/completely-uninstall-programs-with-appcleaner *http://lifehacker.com/276797/uninstall-programs-with-apptrap *http://lifehacker.com/282337/completely-remove-programs-with-revo-uninstaller
{ "language": "en", "url": "https://stackoverflow.com/questions/7525111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this JSON, How do I parse this JSON? {suggestion:[{query:"Cakung, Djakarta, Jakarta Capital Region, Indonesia",interpretation:{term:[{start:0,end:6,feature_type:"",feature_id:"0x2e698b10568c13a1:0x400c5e82dd4c010",matched:1,target:1,term_start:0,term_end:1,type:9938},{start:8,end:16,feature_type:"",feature_id:"0x2e69f3e945e34b9d:0x5371bf0fdad786a2",type:37},{start:18,end:40,feature_type:"",feature_id:"0x2e69f3e945e34b9d:0x100c5e82dd4b820",type:545},{start:42,end:51,feature_type:"",feature_id:"0x2c4c07d7496404b7:0xe37b4de71badf485",type:33}]},operation:2,target_type:9938,confidence:0.016646922403780989},{query:"Churches",interpretation:{term:[{start:0,end:8,feature_type:"",feature_id:"0x1000000000000000:0x225176c87865ce94",matched:1,target:1,term_start:0,term_end:1,type:856337}]},operation:2,target_type:856337,confidence:0.0085971010172646231},{query:"Canada",interpretation:{term:[{start:0,end:6,feature_type:"",feature_id:"0x4b0d03d337cc6ad9:0x9968b72aa2438fa5",matched:1,target:1,term_start:0,term_end:1,type:33}]},operation:2,target_type:33,confidence:0.0085105111169293587},{query:"California, United States",interpretation:{term:[{start:0,end:10,feature_type:"",feature_id:"0x808fb9fe5f285e3d:0x8b5109a227086f55",matched:1,target:1,term_start:0,term_end:1,type:545},{start:12,end:25,feature_type:"",feature_id:"0x54eab584e432360b:0x1c3bb99243deb742",type:33}]},operation:2,target_type:545,confidence:0.006658654709552795},{query:"Cafe",interpretation:{term:[{start:0,end:4,feature_type:"",feature_id:"0x1000000000000000:0x848050558421ac48",matched:1,target:1,term_start:0,term_end:1,type:856337}]},operation:2,target_type:856337,confidence:0.0058785606823066935},{query:"Colleges",interpretation:{term:[{start:0,end:8,feature_type:"",feature_id:"0x1000000000000000:0xdb6190dc25a99356",matched:1,target:1,term_start:0,term_end:1,type:856337}]},operation:2,target_type:856337,confidence:0.0053999922318009111},{query:"China",interpretation:{term:[{start:0,end:5,feature_type:"",feature_id:"0x31508e64e5c642c1:0x951daa7c349f366f",matched:1,target:1,term_start:0,term_end:1,type:33}]},operation:2,details:[{value:"中国",interpretation:{term:[{start:0,end:2,feature_type:"",feature_id:"0x31508e64e5c642c1:0x951daa7c349f366f",matched:1,target:1,term_start:0,term_end:1,type:33}]}}],target_type:33,confidence:0.0044838706757038835},{query:"Clubs",interpretation:{term:[{start:0,end:5,feature_type:"",feature_id:"0x1000000000000000:0x3897b0017192e20d",matched:1,target:1,term_start:0,term_end:1,type:856337}]},operation:2,target_type:856337,confidence:0.0039399659782221796},{query:"Chinese Restaurant",interpretation:{term:[{start:0,end:18,feature_type:"",feature_id:"0x1000000000000000:0x60920a49a18e016a",matched:1,target:1,term_start:0,term_end:1,type:856337}]},operation:2,target_type:856337,confidence:0.0039022718761534195},{query:"Cinema",interpretation:{term:[{start:0,end:6,feature_type:"",feature_id:"0x1000000000000000:0xb29dbbe5e89f763f",matched:1,target:1,term_start:0,term_end:1,type:856337}]},operation:2,target_type:856337,confidence:0.0037837480879625448}],probability_sum:[2.293141542524348e-06]} Notice that dictionary pattern is like JSON but there is no quote in query:, etc. SBJSON fail because of this. A: That is not JSON JSON should have the keys in quotation marks. {"suggestion":[{"query"... etc. A: This was probally, as there are not quotes around query, just made to be used with JavaScript's eval, which is not great. You will have to either look for another reader or put the query in quotes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: HTML email text alignment & image issues I an having a problem with my HTML email. My email is working correctly in most cases, the problem arises when I send to windows live mail. 1) opening the email in widoew live mail in IE all of the text becomes centered even though I have used the 'style="text-align:left;"' and the 'align="left"' options, I have tried them together and tried them seperate. 2)opening in windows live mail in anything other than IE the images have spacing below them. I have used the 'display:block;' and 'border-collapse:collapse;' and set the margin and padding to zero. I used firebug in firefox to have a look and see what the problem is, it shows either a span tag or a p tag wrapping the img tags. I have no idea why it is doing this or how to fix it! If anyone can help i'd be really greatful. Thanks no the align="left" doesn't work, If I use the align="justify" or align="right" it seems to work but not align="left". I have realised that I am only getting these problems when I send through outlook, I am using outlook 2007. after some studying with firebug it seems to me that outlook is adding its own classes to the email. it seems to be adding either or around all of my images with classes that seem to belong to outlook. I know outlook is not the best program in the world but on some occasions it is the only way I can send emails. is there any way I can get into the code that outlook is producing and change it, I know that sounds a bit drastic but it would be really good if I could. thanks for all the help guys, really appreciate. A: A lot of mail clients support only older versions of html. gmail for example will not respect any css file (more information on email on acid) so you are restricted in what you can do with styling. You can test how your email will look in various clients using online services such as email on acid or litmus. I would suggest keeping the design very basic and using an old style table based layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to view old Sybase sql (.db) database data and convert into Sql server I got a .db database file which one of my friend created through PowerBuilder 6 in Win98. Later I wanted to test that database file, but was not able to view or open it in any of common db viewer and not able to get any data out of it. please help.. I am using Win7 and do have xp(virtual). A: The problem with your description is that PowerBuilder is database-agnostic, so it could be any type of database if it was being used with a PowerBuilder application. However, if you want to go with probabilities (and I'm not sure this is how PB is used most; at one point the most popular database used by PowerBuilder was Oracle), PowerBuilder shipped with a run time license for SQL Anywhere, a database that was originally Watcom, acquired by Powersoft, which was acquired by Sybase, which was acquired by SAP. Supposing the database you have in hand is SQL Anywhere, you need to get a SQL Anywhere engine. Probably the first thing I'd try is downloading the Developer version of SQL Anywhere and just try to open up a copy with that, see if the software will migrate it to the current version. (My bet is that it will, or will at least provide you with a means.) Another way to get a current version of SQL Anywhere (I think; I haven't tried this in ages) is to download a trial version of PowerBuilder 12.5, which I think comes with SQL Anywhere (the paid version does). If you get that up and running, then you can use a pipeline object in PowerBuilder to pretty easily move data from one database to another. And, for kicks, you can migrate up your PB6 app to see if it still runs. (My bet is that it will take a few tweaks, but fewer than you're probably imagining.) Good luck, Terry. A: Your .db file is probably a Sybase SQL-Anywhere database. You need to know which version of the engine was used to create the database and then you need the ODBC driver to access that database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should i have to put the copy protection to my Application if i have given Android Licensing to my Application? I have added the Android Licensing to my Application. to check for the application licensing. There is also one option like copy protection during uploading the application on Android Market. So if i have Implemented the Android Licensing to My apps, then should i have to give it to copy protection ? Is it necessary to give copy protection ? If i have not given copy protection and have given Android Licensing to My Application, then user can be able to copy it to anoter device. But should it be able to install in to another device ? I have to know about it.. So Please let me know what steps i have to take ? Should i have to give copy protection on if i have given Licensing or not ? Thanks in advance. A: Taken from here: Replacement for Copy Protection Android Market Licensing is a flexible, secure mechanism for controlling access to your applications. It effectively replaces the Copy Protection mechanism offered on Android Market and gives you wider distribution potential for your applications. * *A limitation of the legacy Copy Protection mechanism on Android Market is that applications using it can be installed only on compatible devices that provide a secure internal storage environment. For example, a copy-protected application cannot be downloaded from Market to a device that provides root access, and the application cannot be installed to a device's SD card. *With Android Market licensing, you can move to a license-based model in which access is not bound to the characteristics of the host device, but to your publisher account on Android Market and the licensing policy that you define. Your application can be installed and controlled on any compatible device on any storage, including SD card. Although no license mechanism can completely prevent all unauthorized use, the licensing service lets you control access for most types of normal usage, across all compatible devices, locked or unlocked, that run Android 1.5 or higher version of the platform. A: Google's "app filtering" is VERY buggy... and getting worse. Many of our apps are listed "not available on this device"... even when the OS version is ok... the device is NOT on our "exclude list"... the device has absolutely NO screen-size or screen-resolution limits. Google still claims "not available on this device". I'm RUNNING the apps... as we speak... right on several of the "forbidden devices". They install and run 100% fine. But they are forever listed as "not for this device" in the store. Great way to sell apps. Users can't download them on 100 different fully legal devices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make the entire row in a table clickable as a link, except the last column? I managed to get the rows in my table to be clickable and linked to the href attribute of the <a> element. However I started to have issues when I made the selector only select the rows except the last column. With the below code the clickable row is only active for the entire row except the last cell which is what I require as I have administrative links in this cell (links to activate, edit, delete etc rows). The only problem is that no matter which row you click on it sends you to the link in the very top row. I think this has something to do with my selector for the find('td a') but I can not figure it out. $('#dataTable tr td:not(:last-child)').click(function () { location.href = $('#dataTable tr').find('td a').attr('href'); }); The hover works great and only changes the pointer if the mouse is over any cell except the last column. $('#dataTable tr td:not(:last-child)').hover( function() { $(this).css('cursor','pointer'); }, function() { $(this).css('cursor','auto'); } ); A: It is because you are getting all the tr's in the table and then the first anchor that is found will be returned, try changing it like this: $('#dataTable tr td:not(:last-child)').click(function () { location.href = $(this).parent().find('td a').attr('href'); }); what it means is it will get the clicked element $(this) as a jquery object, and then go to its parent. (the row element). A: $('#dataTable tr td:not(:last-child)').click(function () { location.href = $(this).parent().find('td a').attr('href'); }); I think this should work. Your code always takes the href from the first "td a" it finds inside your dataTable. This code takes the a it finds in the specific td you are looking for. A: Alternative answer. HTML: <table> <tbody> <tr data-href="#"> <td>first</td> <td>second</td> <td> <div class="dropdown">...</div> </td> </tr> </tbody> </table> JS: jQuery(document).ready(function ($) { $("tbody").on('click', 'tr td:not(:last-child)', function () { window.location = $(this).parent().data("href"); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7525120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: First element in a div is off-center (this line is because SO was chopping parts off...) Dear element-in-a-div, Why oh why must you be ever so maddeningly off center? I'm using the following stylesheet: body { font-family: Helvetica, Arial, sans-serif; } a { text-decoration: none; } a:hover { text-decoration: underline; } #tags { margin: auto; } .tag { margin: auto; } The greyish words are of the tag class, and the (invisible) box around them has the id tags. I can't for the life of me think why "est", in this case, would be ever so slightly off center - any help much appreciated! Thanks. The picture: Why oh why must you be ever so maddeningly off center? I'm using the following stylesheet: body { font-family: Helvetica, Arial, sans-serif; } a { text-decoration: none; } a:hover { text-decoration: underline; } #tags { margin: auto; } .tag { margin: auto; } The greyish words are of the tag class, and the (invisible) box around them has the id tags. I can't for the life of me think why "est", in this case, would be ever so slightly off center - any help much appreciated! Thanks. The picture: A: It is necessary to have a specific width for elements to center them. From the code you supplied, it looks like you haven't specify the width of the div or the image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: call back of completion of iteration is not getting called using https://github.com/caolan/async struggling for getting run the loop by async so finding end of execution of loop is handled . and results=[] async.forEach(nfiles, function(item ){ console.log(item); results.push(item); }, function(err){ /// result call back console.log('in last'); }); why console is not coming in result call back ? suppose nfiles is an array and on each iteration put the item in results so at the end of iteration it should console the inlast in console but not doing this. A: The second argument of your forEach -- the iterator function -- needs to take in a callback as an argument and call it when it executes (to indicate it is done). You need to call the callback like this: results=[] async.forEach(nfiles, function(item, callback){ console.log(item); results.push(item); callback(null, item); }, function(err){ /// result call back console.log('in last'); }); (untested)
{ "language": "en", "url": "https://stackoverflow.com/questions/7525129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which python web framework has hassle-free development and deployment? I have written a web API in BaseHTTPServer. It is meant to be used only on localhost. It returns JSON objects on GET/POST operations. http://localhost:8888/operation?param and code is like def do_GET(self): if self.path=="operation": self.wfile.write("output") But I am worried about keep-alive mechanisms (read: a webserver that can respawn workers), lack of multi-threading, and PITA-ful maintenance. And like I said, I am looking at the development and deployment issues for choosing this web framework. Development The web interface is currently 250 lines and has very simple features. I am looking for something that lends itself well to clean maintenance and deployment. I dont want the framework's MVC, ORM, templating and other features messing my learning curve. UrL patterns that redirect to appropriate module is nice. Deployment It should deploy on a mature server with a WSGI module with minimum fuss. And such a setup has hot-deploy (for want of a better word), installing a new application or updating the code means copying the files to the www-root in the filesystem. CherryPy and Flask seem interesting. Django and Web2Py seem too comprehensive. A: The recommended way of deploying wsgi is as a long-running-process, either embedded or daeomonized, and not as a cgi script. Either way, its going to be a little different than just uploading files like in php, restarting the server/process by touching the config file is normally the closest you get to "hot-deployment" using wsgi. Needless to say, the framework itself does not impose any kind of deployment restraints if it is wsgi compliant. Take your pick depending on your needs: apache+modwsgi, gunicorn, cherry.py, paste. None of them offer "hot-deployment" (afaik), you will still need to create a wsgi script and reload the processes. The filesystem layout is normally of no concern and that's good. You don't usually get autoreload either. I know werkzeug and cherry.py do, and werkzeug offers some really cool debugging tools too. Please note that tornado/werkzeug* itself offers an autoreload option, but is actually considered for development and not deployment, and not compatible with the wsgi module. But no matter how painful or painless the deployment is, it is recommended to use something like fabric to automate your deployments, and setting up a wsgi web server isnt that that hard. Choice of the framework itself is kind of tricky, and depends on what level you want to work in. Tornado, werkzeug are popular low level frameworks, (but also include higher level tools, and many are frameworks+webserver), but you could also work with webob directly and just plugin whatever else you need. You have the microframeworks like flask or bottle, then the lightweight frameworks, like web2.py, or maybe pyramid (the lines on how heavy a framework are kind of blurry). Then you have the "full-stack" django, grok, turbogears, etc... And then you have zope, which has been on a diet but still very heavy. Note that you can pretty much do anything with all of them (just depends how much you want to bend them), and in many cases you can swap components rather easily. I'd start try out a microframework like bottle or maybe flask (you don't have to use ORM's or templating, but are easily available once you do), but also take a look at webob. *comment: added werkzeug to the not really autoreload camp. A: For what you describe, id go with: Tornado Web Server This is the hello world: import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() It's highly scalable, and I think it may take you 10 minutes to set it up with your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create dynamic hibernate criteria query with subcriteria I have a Java class which has some field annotated with @SearchCriteria(criteria = "class1.class2.field"). criteria parameter inside annotation means for with class this field should be set as hibernate criteria, it mean that, if field marked for example: @SearchCriteria(criteria = "class1.class2.field") private String value; I want dynamicly create hibernate criteria with looks like DetachedCriteria hibernateCriteria = forClass(Class.class); hibernateCriteria.createCriteria("class1").createCriteria("class2").add(eq("field", value)); Problem is than I can not set another criteria to already added, it mean I should check annotation criteria option. switch (annotationCriteria.length - 1) { case 0: hibernateCriteria.add(isNull(annotationCriteria[0])); case 1: hibernateCriteria.createCriteria(annotationCriteria[0]).add( Restrictions.isNull(annotationCriteria[annotationCriteria.length - 1])); case 2: hibernateCriteria.createCriteria(annotationCriteria[0]).createCriteria(annotationCriteria[1]).add( Restrictions.isNull(annotationCriteria[annotationCriteria.length - 1])); } I want to remove this "swith". It is possible to get already added criteria by, I dont now, for example by "name" and that add new subcriteria for it. A: No, it's not possible. Detached Criteria API does not - for better or worse - allow for discovery, so you won't be able to ask it for "existing" criteria. What you can do, however, is maintain your own map of nested criteria by association path. In pseudo-code: Map<String, DetachedCriteria> criteriaMap = ...; for ( ) { // loop over annotation criteria's "elements" DetachedCriteria existing = criteriaMap.get(fullPath); if (existing==null) { existing = parentCriteria.createCriteria(pathElement); criteriaMap.put(fullPath, existing); } existing.add(whateverCondition); } A: I find out more "nice" solution for this issue. First of all create some searchCriteria class, for example: public class SearchCriteria { @SearchCriteria(path = "someclass.someclass.id") private Integer someId; public Integer getSomeId() { return someId; } public void setSomeId(Integer someId) { this.someId= someId; } } And custom annotation: @Target(value = { ElementType.FIELD }) @Retention(RUNTIME) public @interface SearchCriteria { String path() default ""; boolean optional() default true; } And in DAO class: @Override public Collection<SomeClass> find(SearchCriteria criteria) { DetachedCriteria hibernateCriteria = forClass(SomeClass.class); for (Field field : criteria.getClass().getDeclaredFields()) { Annotation annotation = field.getAnnotation(SearchCriteria.class); if (annotation == null) { continue; } List<String> elements = Arrays.asList(StringUtils.split(((SearchCriteria) annotation).path(), ".")); field.setAccessible(true); Object fieldValue = null; try { fieldValue = field.get(criteria); } catch (IllegalArgumentException e) { LOG.error("while trying to get private field value of entity " + SearchCriteria.class, e); } catch (IllegalAccessException e) { LOG.error("while trying to get private field value of entity " + SearchCriteria.class, e); } for (String element : elements) { if (elements.indexOf(element) == elements.size() - 1) { hibernateCriteria = hibernateCriteria.add(eq(element, fieldValue)); } else { hibernateCriteria = hibernateCriteria.createCriteria(element); } } } return getHibernateTemplate().findByCriteria(hibernateCriteria); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to programmatically determine if the class is a case class or a simple class? How to programmatically determine if the given class is a case class or a simple class? A: Currently (2011), you can use reflection to find out if the class implements the interface scala.Product: scala> def isCaseClass(o: AnyRef) = o.getClass.getInterfaces.find(_ == classOf[scala.Product]) != None isCaseClass: (o: AnyRef)Boolean scala> isCaseClass(Some(1)) res3: Boolean = true scala> isCaseClass("") res4: Boolean = false This is just an approximation - you could go further and check if it has a copy method, if it implements Serializable, if it has a companion object with an appropriate apply or unapply method - in essence, check for all the things expected from a case class using reflection. The scala reflection package coming in one of the next releases should make case class detection easier and more precise. EDIT: You can now do it using the new Scala Reflection library -- see other answer. A: Using new Scala reflection API: scala> class B(v: Int) defined class B scala> case class A(v: Int) defined class A scala> def isCaseClassOrWhat_?(v: Any): Boolean = { | import reflect.runtime.universe._ | val typeMirror = runtimeMirror(v.getClass.getClassLoader) | val instanceMirror = typeMirror.reflect(v) | val symbol = instanceMirror.symbol | symbol.isCaseClass | } isCaseClassOrWhat_$qmark: (v: Any)Boolean scala> class CaseClassWannabe extends Product with Serializable { | def canEqual(that: Any): Boolean = ??? | def productArity: Int = ??? | def productElement(n: Int): Any = ??? | } defined class CaseClassWannabe scala> isCaseClassOrWhat_?("abc") res0: Boolean = false scala> isCaseClassOrWhat_?(1) res1: Boolean = false scala> isCaseClassOrWhat_?(new B(123)) res2: Boolean = false scala> isCaseClassOrWhat_?(A(321)) res3: Boolean = true scala> isCaseClassOrWhat_?(new CaseClassWannabe) res4: Boolean = false A: If you mean: Can I determine whether a class is a case class or a non-case class programmatically, the answer is no, but you can do an approximation. Case classes are just a compiler hack, they tell the compiler to create certain methods etc. In the final bytecode, there is no difference between normal classes and case classes. From How does a case class differ from a normal class? * *You can do pattern matching on it, *You can construct instances of these classes without using the new keyword, *All constructor arguments are accessible from outside using automatically generated accessor functions, *The toString method is automatically redefined to print the name of the case class and all its arguments, *The equals method is automatically redefined to compare two instances of the same case class structurally rather than by identity. *The hashCode method is automatically redefined to use the hashCodes of constructor arguments. So you can actually create a case class by just defining the correct methods & companion objects yourself. For an idea as to how to find out if a class could be a case class, look at the answer from axel22.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Assign value in integer returned from stored procedure + Sybase I am calling a stored procedure from another stored procedure. That stored procedure is returning an integer value always so I am accepting that value in one integer variable. EXEC @IsBusinessDay = LiteIsWorkingDay @ExecutionStart But even if stored procedure returning 1 value of the @IsBusinessDay is 0. Code block SELECT @ExecutionStart = CONVERT(VARCHAR, GETDATE(), 107) EXEC @IsBusinessDay = LiteIsWorkingDay @ExecutionStart IF(@IsBusinessDay = 0) BEGIN IF(CONVERT(VARCHAR,@InterMediateStartDate,108) > CONVERT(VARCHAR,GETDATE(),108)) BEGIN INSERT INTO TbJobQueue (JobId, ScheduleId, DueDate, Status, ExpiryDate, ProcessingDate, InputUser, InputTime, LastModifiedBy, LastModifiedTime) VALUES (@JobId, @ScheduleId, @InterMediateStartDate, 'NQUE', NULL, NULL, 'Scheduler', GETDATE(), NULL, NULL) END END Please Help. Thanks A: If you want the value of the stored procedure in a variable you have to make something like this: * *Declare output parameter in the LiteIsWorkingDay stored procedure create procedure LiteIsWorkingDay @ExecutionStart varchar(20), @IsBusinessDay int output *In LiteIsWorkingDay stored procedure you have to select a value for the @IsBusinessDay output parameter. *In the stored procedure that calls LiteIsWorkingDay you need to do something like this to get its value: declare @ExecutionStart varchar(20) select @ExecutionStart = convert(varchar, getdate(), 107) declare @IsBusinessDay int exec LiteIsWorkingDay, @IsBusinessDay output And that's all. Now the variable @IsBusinessDay will have the value that you want :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7525146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drag an Image in XNA I am working on an app in which images are flying on the Screen. I need to implement: * *Hold onto any of the flying images on Tap *Drag the image to certain position of the user's choice by letting the user hold it. A: Here is another easy way to do dragging. Just draw your image (Texture2d) with respect to a Rectangle instead of Vector2. Your image variables should look like this Texture2d image; Rectangle imageRect; Draw your image with respect to "imageRect" in Draw() method. spriteBatch.Draw(image,imageRect,Color.White); Now in Update() method handle your image with single touch input. //Move your image with your logic TouchCollection touchLocations = TouchPanel.GetState(); foreach(TouchLocation touchLocation in touchLocations) { Rectangle touchRect = new Rectangle (touchLocation.Position.X,touchLocation.Position.Y,10,10); if(touchLocation.State == TouchLocationState.Moved && imageRect.Intersects(touchRect)) { imageRect.X = touchRect.X; imageRect.Y = touchRect.Y; } //you can bring more beauty by bringing centre point //of imageRect instead of initial point by adding width //and height to X and Y respectively and divide it by 2 A: There's a drag-and-drag example in XNA here: http://geekswithblogs.net/mikebmcl/archive/2011/03/27/drag-and-drop-in-a-windows-xna-game.aspx A: When you load your image in, you'll need a BoundingBox or Rectangle Object to control where it is. So, in the XNA app on your phone, you should have a couple of objects declared for your texture. Texture2D texture; BoundingBox bBox; Vector2 position; bool selected; Then after you load your image content, keep your bounding box updated with the position of your image. bBox.Min = new Vector3(position, 1.0f); bBox.Max = new Vector3(position.X + texture.Width, position.Y + texture.Height, 0f); Then also in your update method, you should have a touch collection initialized to handle input from the screen, get the positions of the touch collection, loop through them and see if they intersect your boundingbox. foreach (Vector2 pos in touchPositions) { BoundingBox bb = new BoundingBox(); bb.Min = new Vector3(pos, 1.0f); bb.Max = new Vector3(pos, 0f); if (bb.Intersects(bBox) { if (selected) { //do something } else { selected = true; } } } From there, you have whether your object is selected or not. Then just use the gestures events to determine what you want to do with your texture object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JTextField's setText method doesn't work from a KeyListener I'm puzzled as to why a JTextField doesn't seem to just "clear out" by using the setText("") method on it, when this is coming from a KeyListener. It works fine from an ActionListener, except that, most amazingly, if the KeyListener method tries to invoke the ActionListener method, with a dummy action event (created on the fly as a simple test), it still leaves the typed text in place. In other words, when you run it from the command line, if you type, for example, a "3" into the field, you will see the setText("test") method does not wipe out the 3, as I would expect and desire, but rather leaves it in place. You will then see "test3" in the display. I have noted this line with a comment. Clicking the JButton will wipe out the text properly. The JButton and JLabel will change text properly. but the JTextField won't. If you then press the button, you will see that the action event clears out the JTextField properly. Now, if you toggle the commented out line, you can see an attempt to invoke the actionPerformed method from the KeyTyped method!!! And still, when you type a "3" into the text field, it will not get wiped out. I would expect the setText("") method to clear it out, which it won't. And this is even when the keyTyped() method is invoking the same actionPerformed() method as the JTextButton. Motivation here may help a little. I have a need to trap one particular hot-key which will clear out the JTextField at the moment it is typed, just as if you pressed the "clear" button. And this doesn't seem to work. I haven't done that much with Swing before, but this is quite puzzling. My SSCCE code follows: import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class P2 implements KeyListener, ActionListener { JTextField fld; JButton btn; JLabel lbl; P2() { JFrame frm = new JFrame("Test"); fld = new JTextField(10); JPanel pnl = new JPanel(); btn = new JButton("Clear it out"); lbl = new JLabel("This is a test"); fld.addKeyListener(this); btn.addActionListener(this); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(400,400); frm.setLayout(new FlowLayout() ); pnl.add(fld); pnl.add(btn); pnl.add(lbl); frm.getContentPane().add(pnl); frm.setVisible(true); } public void keyPressed(KeyEvent ke) {} public void keyReleased(KeyEvent ke) {} public void keyTyped(KeyEvent ke) { System.out.println("got a pressed key"); //this is the setText method that ought to wipe clean the field comments: this.fld.setText("test"); this.btn.setText("try again"); this.lbl.setText("got a presseed key"); //toggle this comment to see the invocation of the action event: // this.actionPerformed(new ActionEvent( new Object(), 2, "test") ); } public void actionPerformed(ActionEvent ae) { fld.setText(""); fld.selectAll(); } public static void main(String[] args) { SwingUtilities.invokeLater ( new Runnable() { public void run() { new P2(); } } ); } } A: This behavior is due to the fact that the KeyEvent will be processed by the field after your KeyListener was fired. You can circumvent it by consuming the event via ke.consume(); inside your method keyTyped. Depending on your requirements another way would be to encapsulate the clearing calls inside a SwingUtilities.invokeLater which will be processed after your current event and thus clear the field after it was updated. A: Here's a code snippet using key bindings to wipe out all text on pressing 'a', implemented to use actions already registered in the field's action map (note that you still need to wrap the code into SwingUtilities.invokeLater - as Howard already suggested - that guarantees it to be processed after the fields internal processing) JTextField normal = new JTextField("just a normal field", 10); final Action selectAll = normal.getActionMap().get("select-all"); final Action cut = normal.getActionMap().get("cut-to-clipboard"); Action combine = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { selectAll.actionPerformed(e); cut.actionPerformed(e); } }); } }; normal.getActionMap().put("magic-delete-all", combine); normal.getInputMap().put(KeyStroke.getKeyStroke("A"), "magic-delete-all");
{ "language": "en", "url": "https://stackoverflow.com/questions/7525154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Translating route segments with ZF's gettext adapter I want to try out the route translations in Zend Framework, but I'm using the gettext adapter and the most tutorials have PHP translate adapter, so I'm having problems to make it work. In the main Bootstrap.php I have the method in which I set the routes: $front = Zend_Controller_Front::getInstance(); $router = $front->getRouter(); $translator = Zend_Registry::get('Zend_Translate'); Zend_Controller_Router_Route::setDefaultTranslator($translator); $routerRoute = new Zend_Controller_Router_Route('@about', array( 'module' => 'default', 'controller' => 'index', 'action' => 'about' ) ); $router->addRoute('about', $routerRoute); This works for /about path. I'll paste the code in which I set Zend_Translate, but it basically loads a *.mo file depending on current session language: $langParam = $this->getSessionLang(); $localeString = $languages[$langParam]; $locale = new Zend_Locale($localeString); $moFilePath = $langFolder . $langParam . '.mo'; if (!file_exists($moFilePath)) { throw new Zend_Exception('File does not exist: ' . $moFilePath); } $translate = new Zend_Translate( array( 'adapter' => 'gettext', 'content' => $moFilePath, 'locale' => $locale, 'ignore' => array('.'), // ignore SVN folders 'disableNotices' => ('production' === APPLICATION_ENV) // disable notices in Production ) ); Zend_Registry::set('Zend_Translate', $translate); Zend_Registry::set('Zend_Locale' , $locale); This, ofc, it's called prior to routing. My question: can gettext be used as a translation adapter for a route, because I can't figure out how can I catch the @about string with, let's say, poEdit? It can? Hooray! How? A: Well, my mo's were all messed up. So there's no problem with the code. Here's how you edit your mo files so that the route can translate it (I'm presume you have your ZF i18n working - Translate, Locale and the like): 1. Remember this? $routerRoute = new Zend_Controller_Router_Route('@about', array( 'module' => 'default', 'controller' => 'index', 'action' => 'about' ) ); 2. See that '@about' string? That's the soon-to-be-translated path. So how do you translate a string so that poEdit will catch it? Well, you don't; not with poEdit anyway. You manually edit the .po file: #ro.po msgid "about" msgstr "despre" #en.po msgid "about" msgstr "about" The msgid should match your path string (minus the '@' string, ofc). 3. Now go open your po file with poEdit. You'll see a new string (surprised, huh?). Compile this po to get a new shiny mo file that ZF can use. 4. Now my site.com/about or site.com/despre paths work. More info here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How mvc works in Zend framework Thanks for previous replies.. I am trying to print Hello_world using zend framework. I wrote php file in model folder and return string value as a "Hello_world". In controller i access the value of PHP like this $value = new TextReturner(); $this->view->setValue = $value->hello_world(); . i dont know how to access the value from controller to the view php file. I am new to zend framework. I already go through the outline structure of zend framework, i dont know how to access through codings. If anyone have idea of how to print hello_world through MVC pls guide me. A: in view you can access your variable like this: <?php echo $this->setValue;?> A: You are trying to use class $value = new TextReturner(); but your controller doesn't see that class. Set this in your Bootstrap file that will help: protected function _initAutoLoad() { // Add autoloader empty namespace $autoLoader = Zend_Loader_Autoloader::getInstance(); $resourceLoader = new Zend_Loader_Autoloader_Resource( array( 'basePath' => APPLICATION_PATH, 'namespace' => '', 'resourceTypes' => array( 'model' => array( 'path' => 'models/', 'namespace' => 'Model_' ), ), ) ); return $resourceLoader; } This will be autoload all of your model class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Allegro 4.2.4 in palette mode on Windows7 corruption I have problem with Allegro 4.2.4 running palette mode (256 colors) in Windows 7. I found over Internet solution of killing explorer and it's working indeed, however it would be ridiculous to expect that end user will kill explorer when trying to play game. Then I found solution to replace DDraw.dll with hacked version, but it doesn't work either - DDHack just results in no screen being shown at all after application launch. Then I found solution of adding registry hack: Windows Registry Editor Version 5.00 ;This file has been created with DirectDraw Compatibility Tool (http://crappybitter.livejournal.com/tag/ddc_tool) [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\DirectDraw\Compatibility\MyApp] "Name"="MyApp.exe" "ID"=dword:4E7B8A88 "Flags"=hex:00,08,00,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\DirectDraw\Compatibility\MyApp] "Name"="MyApp.exe" "ID"=dword:4E7B8A88 "Flags"=hex:00,08,00,00 But sadly it won't work either, the palette keeps flickering with all rainbow colors. Do I have any other solution other than porting entire application to different programming lib? Is it possible to fix DDraw problem on Vista/W7 without touching palettes? If not, what library will give me palette programming (I am doing game that requires palettes) without such problems on Vista/W7? I know of one more solution - I can compile Allegro 4.2.4 application as DOS application and run in DosBox. Sadly, but that's all I can think of now... Thanks in advance for other solutions! A: First off, there's no such version 4.2.4. I assume you mean 4.4.2. True palettes are a dying thing. Setting 8-bit color depths just isn't supported very well on modern operating systems. Regarding Allegro 4.4, you could do this: set_color_depth(8); set_gfx_mode(GFX_GDI, w, h, 0, 0); It will give you a windowed mode, and the most compatible palette support on Windows that Allegro 4.4 offers. If you really must have full screen mode, you could try this patch: * *http://www.allegro.cc/forums/post/862649 It fixes a problem with corrupted palettes while in the game. It may help with the issue you describe. Or you could try using 32-bit color depth for the screen, and use an 8-bit bitmaps for sprites and buffers: set_color_depth(desktop_color_depth()); set_gfx_mode(GFX_AUTODETECT, w, h, 0, 0); BITMAP *buffer = create_bitmap_ex(8, w, h); Of course you would have to blit the bitmap to the screen again after changing the palette, so if you need very fast real time effects, it might not work. Alternatively, Allegro 5.1 (i.e., unreleased SVN version) has a palette addon that works via shaders. It's probably undocumented and likely to change. (Note that the 5 series is not source compatible with the 4 series.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7525168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to COUNT a field not directly related to the where expression on ORACLE I am trying to find out How many students are enrolled in all units, that are associated with a particular course. I have tried. SELECT COUNT(studentID) AS Expr1 FROM Course CROSS JOIN Enrolment WHERE (Course.courseCode = 'S4000') But i am getting 3 , each time for the different course codes. It should be 1 for S4000. I have 3 students in total. A: You didn't tell us columns names, so I create: SELECT cu.courseCode, COUNT(e.StudentID) AS tot_Students FROM COURSEUNIT cu INNER JOIN ENROLMENT e ON cu.unitCode = e.couseCode GROUP BY cu.courseCode A: Its because of what happens in cross join each record in 1st table is get related other record 2nd table .in your case suppose there are 3 student and 3 courses Student table Id | Name 1 | abc 2 | pqr 3 | xyz Courses Code | Name S4000 | c1 S4001 | c2 S4002 | c3 Cross join table Student.Id | Student.Name | Courses.code |courses.name 1| abc| S4000 | c1 2 | pqr| S4000 | c1 3 | xyz| S4000 | c1 1| abc| S4001 | c2 2 | pqr| S4001 | c2 3 | xyz| S4001 | c2 1| abc| S4002 | c3 2 | pqr| S4002 | c3 3 | xyz| S4002 | c3 Now you can see their are 3 records created for each courses so you are getting 3 answer each time. so in your query you should have same common field to get required records such as there will Fourier key relationship you add common field in where clause like SELECT COUNT(studentID) AS Expr1 FROM Course CROSS JOIN Enrolment WHERE (Course.courseCode = 'S4000') and Course.studentID=Enrolment.studentID OR you can use inner join on common field
{ "language": "en", "url": "https://stackoverflow.com/questions/7525169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Load the iphone app automatically when phone boots I am doing a tracking kind of application for internal use of an organization and do not wish to submit it to app store. What I am doing in the application is I am tracking the phone calls, messages etc. My app runs in background once I start the app manually and keeps on running in the background until I close the app or the phone is switched off. The thing that I want to add to my app is, I want to load the app automatically when the phone is switched on again. Any idea or guidance will help. Suggestion for use of private apis is also welcome. A: In private api, in file SBApplication.h there are all methods that you need. In particular: [...] -(BOOL) _shouldAutoLaunchOnBoot:(BOOL)boot; -(void) autoLaunchIfNecessaryOnBoot:(BOOL)boot; -(void) _cancelAutoRelaunch; -(void) _relaunchAfterExit; [...] etc, etc... hope this helps. A: As far as I can understand you can do it by registering your app for significant location changes. If an app registers for significant location changes, as soon as your cellular phone moves to a new tower, app receives an update. If the application is suspended when an update occurs, the system wakes it up in the background to handle the update. So if you close the app and turn of your phone, as soon as your phone will restart it should get an update and it will force your app to run in background mode. For more info read iOS programming guide: http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7525171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: how to change image each touch I would like to change an image each time the user touches the screen. I would like to have user tap the screen and the image changes each time and at the 5th touch it would loop back to the original image with added text. I have looked at How would I set an ImageButton to change only when my finger is touching it I have tried both IUevents and StateListdrawable. I couldn't figure out how to actually change the image after each touch (anywhere in the screen). A: you need to create the Custom class which extends the ImageView now display this imageview to whole screen. > First store the path/location of images into an array/list etc. > In custom class implement the onTouch event. > create the counter object in this custom class. > now in onTouch check in down event that check the counter value with array size if counter==array.length()-1 then set counter as 0 otherwise increment in counter object. > now get the path of the image and set into the imageview as background A: And why can't you use the normal ImageView? Do this: ArrayList<Integer> picList = new ArrayList<Integer>(); // populate the list with the int value of the pictures in drawable. picList.add(R.drawable.apple); picList.add(R.drawable.horse); //etc int touches = 0; int loop = 0; ImageView picture = (ImageView) findViewById(R.id.your_picture); picture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (touches < 4) v.setBackgroundDrawable(picList.get(touches)); touches++; } else { touches = 0; loop = 1; v.setBackgroundDrawable(picList.get(touches)); } if (loop = 1){ // Create a TextView and set the text or make it in the xml with Visible="Gone" and make is visible here. } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7525176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to zip file using "ZipArchive library" in iphone ? I want to implement ZipArchive in my project. Using this library I want to archive files like images into zip file. How can I do that ? A: try my code Zipcode : NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* dPath = [paths objectAtIndex:0]; NSString* txtfile = [dPath stringByAppendingPathComponent:@"test.txt"]; NSString* zipfile = [dPath stringByAppendingPathComponent:@"test.zip"]; ZipArchive* zip = [[ZipArchive alloc] init]; BOOL ret = [zip CreateZipFile2:zipfile]; ret = [zip addFileToZip:txtfile newname:@"test.txt"];//zip if( ![zip CloseZipFile2] ) { zipfile = @""; } [zip release]; NSLog(@"The file has been zipped"); Unzipcode: NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* dPath = [paths objectAtIndex:0]; NSString* zipfile = [dPath stringByAppendingPathComponent:@"test.zip"] ; NSString* unzipto = [dPath stringByAppendingPathComponent:@"test"] ; ZipArchive* zip = [[ZipArchive alloc] init]; if([zip UnzipOpenFile:zipfile] ) { BOOL ret = [zip UnzipFileTo:unzipto overWrite:YES]; if(NO == ret) { } [zip UnzipCloseFile]; } [zip release]; NSLog(@"The file has been unzipped"); A: This code will work perfectly to zip a file. ZipArchive *zip = [[ZipArchive alloc] init]; if(![zip UnzipOpenFile:fileToZipPath]) { //open file is there if ([zip CreateZipFile2:newZipFilePath overWrite:YES]) { //zipped successfully NSLog(@"Archive zip Success"); } } else { NSLog(@"Failure To Zip Archive"); } } To unzip, if([zip UnzipOpenFile:zipFilePath]) { //zip file is there if ([zip UnzipFileTo:newFilePath overWrite:YES]) { //unzipped successfully NSLog(@"Archive unzip Success"); zipOpened = YES; } } else { NSLog(@"Failure To Open Archive"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linking a webcam in a flex application i am having a very strange problem while linking a webcam i xperience following error ArgumentError: Error #2126: NetConnection object must be connected. at flash.net::NetStream/ctor() at flash.net::NetStream() Following is my code in main.mxml <fx:Script> <![CDATA[ import flash.media.Camera; import flash.media.Video; import flash.net.NetConnection; import mx.core.UIComponent; import com.kahaf.plutay.* ; private var inVideo:Video; private var outVideo:Video; private var inVideoWrapper:UIComponent; private var camera:Camera; private var mic:Microphone; private var inStream:NetStream; private var outStream:NetStream; private function defaultVideoMode(): void { VideoPanel.width = 726; VideoPanel.height = 494; inVideo.width = 726; inVideo.height = 494; } private function showInComingVideo():void { inVideo = new Video(VideoPanel.width,VideoPanel.height); inVideo.attachNetStream(inStream); inVideoWrapper = new UIComponent(); inVideoWrapper.addChild(inVideo); VideoPanel.addElement(inVideoWrapper); defaultVideoMode(); } private function setupVideo(event:MouseEvent): void { camera = Camera.getCamera(); mic = Microphone.getMicrophone(); mic.setLoopBack(false); mic.setUseEchoSuppression(true); camera.setMode(640,480,20); camera.setQuality(65536,90); var conn:NetConnection = Connection.getConnection().conn; inStream = new NetStream(conn); inStream.play(conn); showInComingVideo(); } ]]> <s:Group x="283" y="330" width="234" height="149" id="VideoPanel" > </s:Group> <s:Button x="447" y="151" label="Click Me." click="setupVideo(event)"/> here is the code of my connection class : import flash.net.NetConnection; public class Connection extends NetConnection { public static var conObj:Connection; public var conn:NetConnection; public var target:Object; public var selector:Function; public function Connection() { conn = new NetConnection; target = null; selector = null; conn.client = this; } public static function getConnection():Connection { if(conObj == null) { conObj = new Connection(); } return conObj; } } A: This the correct order when handling NetConnection and NetStreams: * *Create and establish the NetConnection (NetConnection.connect()) *Wait for the NetConnection.Connect.Success event (NetStatusEvent.NET_STATUS) *Create your NetStream and attach the connected NetConnection to it *Publish/play your stream
{ "language": "en", "url": "https://stackoverflow.com/questions/7525183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to set a binding in Code? I have the need to set a binding in code. I can't seem to get it right tho. This is what i have tried: XAML: <TextBox Name="txtText"></TextBox> Code behind: Binding myBinding = new Binding("SomeString"); myBinding.Source = ViewModel.SomeString; myBinding.Mode = BindingMode.TwoWay; myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding); ViewModel: public string SomeString { get { return someString; } set { someString= value; OnPropertyChanged("SomeString"); } } The property is not updating when i set it. What am i doing wrong? A: Replace: myBinding.Source = ViewModel.SomeString; with: myBinding.Source = ViewModel; Example: Binding myBinding = new Binding(); myBinding.Source = ViewModel; myBinding.Path = new PropertyPath("SomeString"); myBinding.Mode = BindingMode.TwoWay; myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding); Your source should be just ViewModel, the .SomeString part is evaluated from the Path (the Path can be set by the constructor or by the Path property). A: In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event: private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason). // To work around this, we create the binding once we get the viewmodel through the datacontext. var newViewModel = e.NewValue as MyViewModel; var executablePathBinding = new Binding { Source = newViewModel, Path = new PropertyPath(nameof(newViewModel.ExecutablePath)) }; BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding); } We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call: BindingOperations.ClearBinding(myText, TextBlock.TextProperty); to clear the binding of the old viewmodel (e.oldValue in the event handler). A: You need to change source to viewmodel object: myBinding.Source = viewModelObject; A: Example: DataContext: class ViewModel { public string SomeString { get => someString; set { someString = value; OnPropertyChanged(nameof(SomeString)); } } } Create Binding: new Binding("SomeString") { Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
{ "language": "en", "url": "https://stackoverflow.com/questions/7525185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "112" }
Q: call procedure syntax error? Give the following stored procedure : DELIMITER $$ DROP PROCEDURE IF EXISTS ric_forn$$ CREATE PROCEDURE ric_forn (IN nome_forn VARCHAR(100) , OUT msg VARCHAR(100)) BEGIN DECLARE num_rec INT; IF (nome_forn = '') THEN SET msg = "Attenzione il nome inserito non è valido !"; END IF; SELECT COUNT(*) INTO num_rec FROM Fornitori WHERE Des_Fornitore = nome_forn; IF num_rec = 0 THEN SET msg = "Nessun record trovato !"; ELSE SELECT Id_Fornitore, Des_Fornitore, Ind_Fornitore FROM Fornitori WHERE Des_Fornitore = nome_forn; SET msg = "Records trovati:"; END IF; END$$ DELIMITER ; How do I run it? I tried : call ric_forn (Des_Fornitore,msg); call ric_forn (nome_forn ,msg); call ric_forn ('' ,msg); call ric_forn ('EAN srl' ,msg); 'EAN srl'is a value But I always get errors like Unknown column nome_forn or nknown column Des_Fornitore..etc A: Try to run SP in this way - SET @nome_forn = 'nome_forn'; --set your value SET @msg = 'msg'; --set your value CALL ric_forn(@nome_forn, @msg); SELECT @msg; -- output
{ "language": "it", "url": "https://stackoverflow.com/questions/7525189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to append additional text with existing html content in android? I am Developing an application.In which i am appending a text to existing text which is stored in .html file, the location for the .html file is in my application's "assets" folder. I know how to load html with URL but my problem is to append the text. following is my java code public class LoadWeb extends Activity { WebView wv; private Handler handler = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); wv=(WebView)findViewById(R.id.webView1); handler = new Handler(); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setBuiltInZoomControls(true); wv.addJavascriptInterface(this, "contactSupport"); wv.getSettings().setSupportZoom(true); wv.setWebViewClient(new Callback()); // String title=wv.getTitle(); // Log.e("nitin", "msg"+title); setTheme(Color.CYAN); // wv.setInitialScale(100); wv.loadUrl("file:///android_asset/style.html"); } void loadTime() { String TESTSTRING = "'<div style='color:blue; border:1px solid red;'>YO!</div>'"; // TODO Auto-generated method stub Log.e("mitiiiiiii", ""+TESTSTRING); wv.loadUrl("javascript:appendText("+TESTSTRING+")"); } private class Callback extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { return(true); } @Override public void onPageFinished(WebView view, String url) { loadTime(); super.onPageFinished(view, url); } } public String deleteContact(final String contactId){ Toast.makeText(getBaseContext(),contactId ,Toast.LENGTH_LONG).show(); handler.post(new Runnable() { public void run() { Toast.makeText(getBaseContext(),contactId ,Toast.LENGTH_LONG).show(); } }); Log.i("nitin" ,""+contactId); return "http://google.com"; } } and following is my javascript code <html> <head> <script type="text/javascript"> var extraStr; function appendText(extraStr) { document.getElementById('question')[0].innerHTML = document.getElementById('question')[0].innerHTML + extraStr; contactSupport.deleteContact(); } function getUsed() { var total = ""; $(".boxWord.boxWordUsed").each(function (i){ total = total + this.getAttribute('index_no') + ":"; }); return total; } </script> <link href="style.css" media="all" rel="stylesheet" type="text/css" /> </head> <body> <div id="question" class='question' > </div> Can any body tell me why it is not working Thanks in advance. A: Appending to HTML (concatenation) as String joining is not a good solution, but you can try this approach which will ensure that the html document's sanctity is not broken. Since you have the HTML document with you, it signifies you have control over that document and hence you should be able to do this which I am mentioning below. 1) Create a function in HTML function appendText(extraStr) { document.getElementsByTagName('body')[0].innerHTML = document.getElementsByTagName('body')[0].innerHTML + extraStr; } 2) On WebView load call this function myWebView.loadUrl("javascript:appendText('extra text or html here')"); 3) Don't forget to add this myWebView.getSettings().setJavaScriptEnabled(true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7525196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: YouTube video fails to load with iOS UIWebView W're developing an iPad app (iOS 4.3.5) that uses UIWebView to load YouTube videos. About once in five times a YouTube video will fail to load and I only see the following blank screen with YouTube's logo: Looking in the debug logs I can only see the following warnings: warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/System/Library/Internet Plug-Ins/QuickTime Plugin.webplugin/QuickTime Plugin (file not found). warning: No copy of QuickTime Plugin.webplugin/QuickTime Plugin found locally, reading from memory on remote device. This may slow down the debug session. I've read about this warning (https://stackoverflow.com/questions/7149593/warning-while-playing-a-video-link-in-my-app) and don't think it effects this problem. Does anyone know how to fix this? A: Try with video tag of HTML 5. I have done the same thing with video tag and its working perfect with my application. Below is the sample code for the same... <html><head><video controls=\"controls\"><source src=\"%@\" type=\"video/mp4\" height=\"%0.0f\" width=\"%0.0f\"/></video></body></html> A: (Answering my own questions) OK. I'm pretty sure I figured this out. Some videos don't have a mobile player. You can look at the JSON output here: http://gdata.youtube.com/feeds/api/videos/TWfph3iNC-k?v=2&alt=jsonc And here: http://gdata.youtube.com/feeds/api/videos/cd4jvtAr8JM?v=2&alt=jsonc Notice how the second video (cd4jvtAr8JM) doesn't have the mobile player link. I guess this means that YouTube hasn't encoded it yet for mobile. Or it's restricted for mobile. Regardless, these type of videos all won't play for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set more than one alarm for calendar events in android? I have already worked on calendar events and for each event the alarm should ring with notification. The problem i face is, If i set more than one event, the last set event is alone notifying the user with alarm. But all the other events doesn't ring alarm. Any Help is appreciated and thanks in advance... A: If you create the alarm with the Single Intent instant you need to pass the different Request code into the getService() method. Or if you elsewhere you can create multiple instant of the intent and with different request code you can set it here snippet of code updated AlarmManager alarms = (AlarmManager)context.getSystemService( Context.ALARM_SERVICE); Intent i = new Intent(MyReceiver.ACTION_ALARM); // "com.example.ALARM" i.putExtra(MyReceiver.EXTRA_ID, id); // "com.example.ID", 2 PendingIntent p = PendingIntent.getBroadcast(context, requestcode, i, 0); here the second parameter of getService was request code you need to set the different request for multiple alarm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help for routing in asp.net webform i want to achieve few redirection like when user will type this www.mysite.com/label/uk or www.mysite.com/label.aspx/uk then my labeluk.aspx will load or when user will type this www.mysite.com/label/us or www.mysite.com/label.aspx/us then my labelus.aspx will load or when user will type this www.mysite.com/label/fr or www.mysite.com/label.aspx/fr then my labelfr.aspx will load. so please tell me how do i define pattern for routing like RouteTable.Routes.MapPageRoute("Source1", "label/{ID}", "~/labeluk.aspx"); RouteTable.Routes.MapPageRoute("Source1", "label/{ID}", "~/labelus.aspx"); i am not being able to figure out how to achieve it by routing. please help me to form the maproute. thanks A: You can look into URL Rewriting on the web or SEO Urls http://www.codeproject.com/KB/aspnet/URL-Rewriting-in-ASPNET.aspx A: you could do something like this.. keep one route (in Global) as RouteTable.Routes.MapPageRoute("Source", "label/{ID}, "~/label.aspx"); so all will resolve /label.aspx, then on label.aspx check ID param e.g. Page.RouteData.Values.ContainsKey("ID") and depending on whether it's uk, fr or us do HttpContext.Current.RewritePath("/labeluk.aspx", false); alternatively not even need to have /label.aspx just check ID param in Global and do RewritePath there
{ "language": "en", "url": "https://stackoverflow.com/questions/7525205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: select Case with subqueries select and using Top Hi i want to retrive the list of browsers used by user id Table Contains UserID int BrowserName nvarchar(40) here is my Query select browser = CASE WHEN ( PATINDEX('%IE%',BrowserName) IS not null) THEN SUBSTRING(BrowserName,PatIndex('%IE%',BrowserName),8) WHEN (PATINDEX('%Firefox%',BrowserName) IS not null) THEN SUBSTRING(BrowserName,PatIndex('%Firefox%',BrowserName),8) WHEN (PATINDEX('%Chrome%',BrowserName) IS not null) THEN SUBSTRING(BrowserName,PatIndex('%Chrome%',BrowserName),6) END from tableBrowsers where UserId =21 But how to select only top 1 substring in this query . eg : after when in case statement i n need only one row returned for that case, i tried this, but not getting idea how to implement in case THEN select top 1 SUBSTRING(BrowserName,PatIndex('%IE%',BrowserName),8) from browsertable output will be like this IE FIREFOX CHROME if the user used three browsers A: Just add DISTINCT: SELECT DISTINCT browser = CASE WHEN ( PATINDEX('%IE%',BrowserName) IS not null) THEN SUBSTRING(BrowserName,PatIndex('%IE%',BrowserName),8) WHEN (PATINDEX('%Firefox%',BrowserName) IS not null) THEN SUBSTRING(BrowserName,PatIndex('%Firefox%',BrowserName),8) WHEN (PATINDEX('%Chrome%',BrowserName) IS not null) THEN SUBSTRING(BrowserName,PatIndex('%Chrome%',BrowserName),6) END FROM tableBrowsers where UserId =21
{ "language": "en", "url": "https://stackoverflow.com/questions/7525207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent CSS inline style when Browser Zoom in? When using Safari or Chrome, I have a problem when using the Zoom-in view tool. On an image slider it forces to add inline style of a DIV element and specifically its height (which obviously overrides any other styles). The div should be set at 340px, but automatically changes the value to 387px, then 459px etc... incrementally based on zoom level. Also note that the images within the image slider don't change size, and other elements don't change either. The issue can be seen here the troubling re-dimension... After opening the page zoom in 1 or 2 levels then hit refresh while zooming. When I inspect(with firebug) the element Safari and Chrome adds inline styles: <div id="djslider-loader40" class="djslider-loader" style="background-image: none; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: initial; height: 387px; background-position: initial initial; background-repeat: initial initial; "> How do I prevent this behavior from the browser? A: try using this code <div id="djslider-loader40" class="djslider-loader" style="background: none;height: 387px !important;"> A: I had similar kind of issue. One of my div element had an inline style height based on its contents. Hence, if i expand the content from JScript, the content would get hidden. Thanks to the example. When I apply height:100% !important, it worked like a charm! Thanks again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use a batch file to write txt to another file How would i add this text to a file because it seems to get confused with the other greater than less than signs thanks echo >> C:\docs\thisdoc.txt A: If I've got you right, you want to write the text "echo >> c:\docs\thisdoc.txt" in a file? Then you need to escape the ">"characters with "^": echo echo ^>^> C:\docs\thisdoc.txt > mybatch.cmd
{ "language": "en", "url": "https://stackoverflow.com/questions/7525211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to "scale" a numpy array? I would like to scale an array of shape (h, w) by a factor of n, resulting in an array of shape (h*n, w*n), with the. Say that I have a 2x2 array: array([[1, 1], [0, 1]]) I would like to scale the array to become 4x4: array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]]) That is, the value of each cell in the original array is copied into 4 corresponding cells in the resulting array. Assuming arbitrary array size and scaling factor, what's the most efficient way to do this? A: To scale effectively I use following approach. Works 5 times faster than repeat and 10 times faster that kron. First, initialise target array, to fill scaled array in-place. And predefine slices to win few cycles: K = 2 # scale factor a_x = numpy.zeros((h * K, w *K), dtype = a.dtype) # upscaled array Y = a_x.shape[0] X = a_x.shape[1] myslices = [] for y in range(0, K) : for x in range(0, K) : s = slice(y,Y,K), slice(x,X,K) myslices.append(s) Now this function will do the scale: def scale(A, B, slices): # fill A with B through slices for s in slices: A[s] = B Or the same thing simply in one function: def scale(A, B, k): # fill A with B scaled by k Y = A.shape[0] X = A.shape[1] for y in range(0, k): for x in range(0, k): A[y:Y:k, x:X:k] = B A: You should use the Kronecker product, numpy.kron: Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first import numpy as np a = np.array([[1, 1], [0, 1]]) n = 2 np.kron(a, np.ones((n,n))) which gives what you want: array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]]) A: You could use repeat: In [6]: a.repeat(2,axis=0).repeat(2,axis=1) Out[6]: array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]]) I am not sure if there's a neat way to combine the two operations into one. A: scipy.misc.imresize can scale images. It can be used to scale numpy arrays, too: #!/usr/bin/env python import numpy as np import scipy.misc def scale_array(x, new_size): min_el = np.min(x) max_el = np.max(x) y = scipy.misc.imresize(x, new_size, mode='L', interp='nearest') y = y / 255 * (max_el - min_el) + min_el return y x = np.array([[1, 1], [0, 1]]) n = 2 new_size = n * np.array(x.shape) y = scale_array(x, new_size) print(y)
{ "language": "en", "url": "https://stackoverflow.com/questions/7525214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Routing error for GET] "/firstapp" I was trying to write my first program after installation, but I got an error like below: Routing Error No route matches [GET] "/firstapp" I've tried to change my config/routes.rb file but nothing changed. This is my config/routes.rb Firstapp::Application.routes.draw do resources :apptables # The priority is based upon order of creation: # first created -> highest priority. # continues with default `config/routes.rb` explanations... end How can I configure the config/routes.rb to make it run properly? A: Just saying resources :apptables sets up the standard seven routes: GET /apptables GET /apptables/new POST /apptables GET /apptables/:id GET /apptables/:id/edit PUT /apptables/:id DELETE /apptables/:id There is no /firstapp in that list so that route won't work. If you want a GET on /firstapp to work then you can set up that route manually: match '/firstapp' => 'firstapp#some_method', :via => :get That would route GET /firstapp to FirstappController#some_method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data api ga, how to get data for multiple pages? I'm using Data api of google to get data in my filters, I'm getting data for page path for single page and I'm stuck at multiple pages. I followed document and passed following query to filters, $filter = 'ga:pagePath=~/about_us.htm,ga:pagePath=~/index.htm'; Is there anything wrong in it? Can someone please help in it. A: You need to add $dimensions='ga:pagePath' to individually query the two pages. A: I don't see anything wrong with it but it's always good to run your data api calls through the Data Feed Query Explorer. It will show you if it is getting results and show you the proper url-encoded query. I ran a query using the Data Feed Query Explorer on my site that was similar to yours and had no problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to write a simple makefile for c I need to write a simple make file for my.c, and so after make then my program can be run by ./my my.c can be compiled by this: gcc cJ/cJ.c my.c -lcrypto -o my -lm Thanks I put this in my makefile all:my my: cJ.o my.o gcc cJ.o -lcrypt my.o -o my cJ.o: cJ/cJ.c gcc -c cJ/cJ.c my.o: my.c gcc -c my.c -lm help please A: Well, makefiles are just kind of special scripts. Every is unique, for such simple task this would be sufficient: Makefile: CC=gcc CFLAGS=-lm -lcrypto SOURCES=my.c cJ/cJ.c all: my my: $(SOURCES) $(CC) -o my $(SOURCES) $(CFLAGS) Later you may want to use some other options such as wildcards %.c to compile in multiple files without having to write them in. Alternatively: CC=gcc CFLAGS=-lm -lcrypto MY_SOURCES = my.c cJ/cJ.c MY_OBJS = $(patsubst %.c,%.o, $(MY_SOURCES)) all: my %o: %.c $(CC) $(CFLAGS) -c $< my: $(MY_OBJS) $(CC) $(CFLAGS) $^ -o $@ Note that lines following each target ("my:", ...) must start with tab (\t), not spaces. A: Just a minor correction: put the -lm to the linking step, and there after all object files. all: my my: cJ.o my.o gcc cJ.o my.o -o my -lcrypt -lm cJ.o: cJ/cJ.c gcc -c cJ/cJ.c my.o: my.c gcc -c my.c And then, you could work more with automatic variables: all: my my: cJ.o my.o gcc $^ -o $@ -lcrypt -lm cJ.o: cJ/cJ.c gcc -c $^ my.o: my.c gcc -c $^ where $@ is the target of the current rule and $^ are the prerequisites. See also http://www.gnu.org/software/make/manual/make.html. A: simple make file for your program is build : gcc /your_full_path_to_c_file/cJ.c my.c -lcrypto -o my -lm just copy this in one file keep name of that file as makefile then run as make build
{ "language": "en", "url": "https://stackoverflow.com/questions/7525219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use javascript to monitor a change in a div value? I have a page with a countdown in a DIV with id ="count" I would like to monitor this div value so, when it reaches 0, a alert pops up. I've gono so far as if(parseInt(document.getElementById('count').innerHTML) < 2){} But I don't know how to "listen" for the div changes Can anyone help me? Btw: it needs to be in pure javascript, with no such things as jquery. Update: I have no say so in the original code. It's an external page and I'm trying to run this code at the address bar A: Presumably you have a function running based on setInterval or setTimeout. Have that function call your function when it gets to zero. If you can't do that, you can try optimised polling - use setInterval to read the value, estimate when it might be near zero, check again and estimate when it might be zero, etc. When it is zero, do your thing. There are DOM mutation events, but they are deprecated and were never well or widely supported anyway. Also, they are called when content changes so probably too often for your scenario anyway. A: If you are changing the value of #count yourself then call the alert from that place. If not use: window.setInterval(function(){ if(parseInt(document.getElementById('count').innerHTML) < 2) alert('Alarm!'); },1000); // 1s interval UPDATE To clear that interval: var timer = window.setInterval(function(){ if(parseInt(document.getElementById('count').innerHTML) < 2) { alert('Alarm!'); window.clearInterval(timer); } },1000); // 1s interval //or by using non-anonymous function function check(){ if(parseInt(document.getElementById('count').innerHTML) < 2) { alert('Alarm!'); window.clearInterval(timer); } } var timer = window.setInterval(check,1000); A: The only efficient way to monitor this is to go to the code that is actually changing the div and modify it or hook it to call a function of yours whenever it updates the contents of the div. There is no universal notification mechanism for anytime the contents of div changes. You will have much more success looking into modifying the source of the change. The only option I know of besides the source of the change would be using an interval timer to "poll" the contents of the div to notice when it has changed. But, this is enormously inefficient and will always have some of inherent delay in noticing the actual change. It's also bad for battery life (laptops or smartphones) as it runs continuously. A: You don't listen for the div to change. The div is just there for a visual representation of the program's state. Instead, inside whatever timing event is counting down the number, use a condition such as... if (i < 2) { // ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visible elements in a WPF canvas I have a WPF Canvas and a lot of Shapes (StreamGeometry / Path) added to it. I have ScaleTransform defined to zoom into specific region. I have zoomed into a arbitrary space in the canvas and the Shapes are scaled. Now, is it possible to get the Shapes that are in the visible region of the Canvas. Thanks for any pointers. A: You can use HitTest to perform a hit test against the Canvas's bounding rectangle. For details, see Hit Testing in the Visual Layer and refer to the sample for hit testing with DrawingVisuals. A: Should this help? Iterate thru all children shapes of canvas and check the following for each myShape .... hitArea = new EllipseGeometry( new Point(Canvas.GetLeft(myShape), Canvas.GetTop(myShape)), 1.0, 1.0); VisualTreeHelper.HitTest( myShape, null, new HitTestResultCallback(HitTestCallback), new GeometryHitTestParameters(hitArea)); public HitTestResultBehavior HitTestCallback(HitTestResult result) { if (result.VisualHit == myShape) { //// This shape is on the visible area. } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7525222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Find whether a particular date is an Option Expiration Friday - problem with timeDate package I am trying to write a simple function that (should) return true if the parameter date(s) is an Op-Ex Friday. require(timeDate) require(quantmod) getSymbols("^GSPC", adjust=TRUE, from="1960-01-01") assign("SPX", GSPC, envir=.GlobalEnv) names(SPX) <- c("SPX.Open", "SPX.High", "SPX.Low", "SPX.Close", "SPX.Volume", "SPX.Adjusted") dates <- last(index(SPX), n=10) from <- as.numeric(format(as.Date(min(dates)), "%Y")) to <- as.numeric(format(as.Date(max(dates)), "%Y")) isOpExFriday <- ifelse( isBizday( timeDate(as.Date(dates)), holidayNYSE(from:to)) & (as.Date(dates) == as.Date( format(timeNthNdayInMonth(timeFirstDayInMonth(dates), nday=5, nth=3))) ), TRUE, FALSE) Now, the result should be [1] "2011-09-16". But instead I get [1] "2011-09-15": dates[isOpExFriday] [1] "2011-09-15" Am I doing something wrong, expecting something that timeDate package is not doing by design or is there a bug in timeDate? A: I am guessing it's a timezone problem. What happens if you use this: format(dates[isOpExFriday], tz="UTC") On second look, you probably need to put the 'tz=' argument inside the format call inside the as.Date(format(...)) call. The format function "freezes" that dates value as text. EDIT: On testing however I think you are right about it being a bug. (And I sent a bug report to the maintainer with this response.) Even after trying to insert various timezone specs and setting myFinCenter in RmetricsOptions, I still get the which stems from this error deep inside your choice of functions: timeNthNdayInMonth(as.Date("2011-09-01"), nday=5, nth=3) America/New_York [1] [2011-09-15] I suspect it is because of this code since as I understand it Julian dates are not adjusted for timezones or daylight savings times: ct = 24 * 3600 * (as.integer(julian.POSIXt(lt)) + (nth - 1) * 7 + (nday - lt1$wday)%%7) class(ct) = "POSIXct" The ct value in seconds is then coverted to POSIXct from second since "origin" simply by coercion of class. If I change the code to: ct=as.POSIXct(ct, origin="1970-01-01") # correct results come back My quantmod and timeDate versions are both current per CRAN. Running Mac with R 2.13.1 in 64 bit mode with a US locale. I have not yet tried to reproduce with a minimal session so there could still be some collision or hijacking with other packages: > sessionInfo() R version 2.13.1 RC (2011-07-03 r56263) Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) locale: [1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] grid splines stats graphics grDevices utils datasets [8] methods base other attached packages: [1] quantmod_0.3-17 TTR_0.20-3 xts_0.8-2 [4] Defaults_1.1-1 timeDate_2130.93 zoo_1.7-4 [7] gplots_2.10.1 KernSmooth_2.23-6 caTools_1.12 [10] bitops_1.0-4.1 gdata_2.8.1 gtools_2.6.2 [13] wordnet_0.1-8 ggplot2_0.8.9 proto_0.3-9.2 [16] reshape_0.8.4 plyr_1.6 rattle_2.6.10 [19] RGtk2_2.20.17 rms_3.3-1 Hmisc_3.8-3 [22] survival_2.36-9 sos_1.3-0 brew_1.0-6 [25] lattice_0.19-30
{ "language": "en", "url": "https://stackoverflow.com/questions/7525226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I have a class where data of strings have been stored I have a class where data of strings have been stored. void testCallback(char *data) { NSLog(@"%s", data); } in the log it displays the following output, 1.00 2.00 3.00 4.00 5.00 6.00 But i need the output in the following manner, 2.00,3.00 5.00,6.00 so i want to remove first character and i want to replace the space between the 2nd and 3rd with the comma(,).How can i do this. A: Already i answered Link Here void testCallback(char *data) { NSString *str=[NSString stringWithFormat:@"%s",data]; NSArray *split = [str componentsSeparatedByString:@" "]; NSString *replacevalue=@" "; for(int i=1;i<[split count];i++) { if([replacevalue isEqualToString:@" "]) replacevalue=[NSString stringWithFormat:@"%@",[split objectAtIndex:i]]; else replacevalue=[NSString stringWithFormat:@"%@,%@",replacevalue,[split objectAtIndex:i]]; } NSLog(@"%@",replacevalue); } A: Conver you Char *array to the NSString. than you can use the method for replacing ReplaceWithAccrunce: and you can concate with NSStrings Method,also..
{ "language": "en", "url": "https://stackoverflow.com/questions/7525236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there a function or unit sames as TIniFiles that will not save to file? I have a project that use Inifile for reading the data configuration. I decided to save the configuration to the resource. i would like to ask help if is there a Unit or function that same as Tinfile or related that saving the data config is optional. any suggestions aside from extraction? thanx. A: There is a class named TMemIniFile that only saves the changes to the inifile when you call UpdateFile. Is that good enough for you? A: TMemIniFile (descendant of TCustomIniFile) will not save unless you tell it to UpdateFile; A: TMemIniFile is what you need and should always be preferred to TIniFile. You choose whether or not to save to file. What you can't do directly is initialize it from a resource, but it's not too hard to put it together yourself. * *Use a resource stream to extract your resource. *Create a string list and call load your resource stream into the string list. *Create a TMemIniFile and call SetStrings passing the string list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Maven 2: eclipse-plugin to generate EAR's dependent projects to .project file I'm trying to generate eclipse-project files using Maven2 eclipse-plugin for RAD7.5. All is going well except for the dependencies in the EAR's .project file. When I run mvn eclipse:eclipse on a clean maven project, I come up with an EAR such as this: <projectDescription> <name>MyEAR</name> <comment>The .project file of MyEAR</comment> <projects/> <buildSpec> <buildCommand> <name>org.eclipse.wst.common.project.facet.core.builder</name> </buildCommand> <buildCommand> <name>org.eclipse.wst.validation.validationbuilder</name> </buildCommand> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> </buildCommand> <buildCommand> <name>com.ibm.etools.validation.validationbuilder</name> </buildCommand> <buildCommand> <name>com.ibm.sse.model.structuredbuilder</name> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.wst.common.project.facet.core.nature</nature> <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature> <nature>org.eclipse.jem.workbench.JavaEMFNature</nature> </natures> </projectDescription> BUT I want to be coming out with something like this: <projectDescription> <name>MyEAR</name> <comment>The .project file of MyEAR</comment> <projects> <project>MyProjectConnector</project> <project>MYProjectEJB</project> <project>MyProjectDependents</project> <project>MyProjectLOG</project> </projects> ... </projectDescription> RAD7.5 don't understand the project structure unless the dependent projects are listed in the < projects >. But how do I do that with the eclipse-plugin? Where in the pom do I list the dependent projects, so they appear in the .project-file as < projects >? Edit>> Here's the maven-eclipse-plugin config of my pom-file <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.6</version> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>false</downloadJavadocs> <wtpversion>1.5</wtpversion> <packaging>ear</packaging> </configuration> </plugin> </plugins> <finalName>${project.artifactId}-${project.version}-r${buildNumber}</finalName> </build> < EDIT2: I must add that the projects builds ok, i.e. mvn clean install works fine, so basically the problem is with the eclipse plugin configuration. EDIT3: The maven-project is built in the following fashion: MyEAR-reactor-build |-- pom.xml |-- MyEAR | |-- pom.xml |-- MYProjectEJB | |-- pom.xml `-- . . . ALL HELP GREATLY APPRECIATED!!! (thanks for reading this far :) A: Have you declared your modules and dependent projects as dependencies in your EAR's POM? <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>ear</packaging> <groupId>so.com</groupId> <artifactId>MyEAR</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>so.com</groupId> <artifactId>MYProjectEJB</artifactId> <scope>runtime</scope> <type>ejb</type> </dependency> . . . </dependencies> . . . A: You may need to create a module reactor build - MyEAR-reactor-build |-- pom.xml |-- MyEAR | |-- pom.xml |-- MYProjectEJB | |-- pom.xml `-- . . . The reactor build POM would look something like this - <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>so.com</groupId> <version>1.0-SNAPSHOT</version> <artifactId>MyEAR-reactor-build</artifactId> <packaging>pom</packaging> . . . <modules> <module>MyEAR</module> <module>MYProjectEJB</module> . . . </modules> </project> A: Ahh...thanks everybody for the help. The problem turned out to be that higher in the pom hierarchy, another developer had introduced the eclipse-plugin with the element: <useProjectReferences>false</useProjectReferences> For some reason having set this to true in my pom didn't override the parent setting. A bug at the eclipse-plugin, perhaps? Anyway, after setting this to true at the parent pom, all worked out. Thanks everybody for help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7525238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Set file permissions- Android I have a doc file on sdcard. I want to open it in read-only mode. Also I don't want the document viewer to save the file. The intent to open the file is as follows: Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); File file = new File("/sdcard/test.doc"); file.setReadOnly(); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION ); intent.setDataAndType(Uri.fromFile(file), "application/msword"); startActivity(intent); But when the file opens in quickOffice, the file is still editable. Please suggest how should I make the file ready-only to any document viewer and how should I prevent file from saving. A: It is probably because your app does not have root access. File permissions can be changed by root access only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to separate lines of a text file using MATLAB.like first 1-3(modes) in one group next 1-3 in second group and so on I would like to separate the parts of the following text file using MATLAB:like first 1-3(modes) in one group next 1-3 in second group and so on... edit: the file format has been edited since the initial post (modes) (-x) (y) 1 -4177 3764 2 -4177 3763 2 -4177 3760 2 -4173 3758 2 -4171 3757 2 -4170 3758 2 -4171 3754 2 -4176 3749 2 -4176 3752 2 -4179 3758 2 -4182 3769 2 -4195 3785 2 -4221 3803 2 -4251 3833 2 -4276 3866 2 -4302 3899 2 -4321 3926 2 -4341 3949 2 -4360 3961 2 -4375 3965 2 -4384 3965 2 -4389 3962 2 -4386 3959 2 -4389 3958 2 -4390 3956 2 -4390 3958 2 -4387 3962 2 -4392 3965 2 -4381 3955 3 -12851 -12851 1 -4396 3779 2 -4396 3778 2 -4398 3775 2 -4396 3775 2 -4396 3778 2 -4393 3787 2 -4387 3796 2 -4371 3808 2 -4338 3832 2 -4297 3866 2 -4257 3902 2 -4225 3934 2 -4207 3950 2 -4195 3959 2 -4192 3959 2 -4189 3956 2 -4189 3955 2 -4192 3949 2 -4188 3949 2 -4183 3949 2 -4183 3949 3 -12851 -12851 How should I go about doing this? Thanks. A: Answer to the original text file of the format 1 -4177 3764 2 -4177 3763 2 -4177 3760 2 -4173 3758 2 -4171 3757 Assuming your file is called 'text.txt' and located on drive C, do: [col1, col2, col3] = textread('C:\text.txt', '%d %d %d'); all your entries from the text file will be in the corresponding variables col1, col2 and col3. EDIT: cells = cell(1, numel(col1)); for j = 1 : numel(col1) cells{j} = [col1(j) col2(j) col3(j)]; end This will group your values as follows: * *cells{1}: 1 -4177 3764 *cells{2}: 2 -4177 3763 A: Here is an example code using the TEXTSCAN function. It read the file, then it separates every 3 lines using MAT2CELL and put the result in a cell-array. Note that in your case, you have 52 lines of data (plus one header line ignored), which are not divisible by 3, thus the last entry will only have one line. %# read file fid = fopen('file.dat','r'); C = textscan(fid, '%f %f %f', ... 'Delimiter',' ', 'HeaderLines',1, 'CollectOutput',true); fclose(fid); C = C{1}; %# handles the case where number of lines is not divisible by 3 n = fix(size(C,1)/3)*3; CC = mat2cell(C(1:n,:), repmat(3,1,n/3), size(C,2)); CC{end+1} = C(n+1:end,:); The result: >> whos CC Name Size Bytes Class Attributes CC 18x1 2328 cell and the last two cells: >> CC{end-1} ans = 2 -4188 3949 2 -4183 3949 2 -4183 3949 >> CC{end} ans = 3 -12851 -12851
{ "language": "en", "url": "https://stackoverflow.com/questions/7525240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to save the window state at wxWidgets? I'm constructing a UI using wxWidgets. In my GUI, I generate a window (wxFrame class) which is accessible through pushing a bitmap button. In that window, I also perform some tasks, again pushing some bitmap buttons and diabling them etc. But I can't close and reopen that window with the state saved. I always have to re-initialize it, and this is very impractical. How can I save the state of my window? I checked the internet, it's suggested to use wxPersistent class but this class is missing in my wxWidgets. Thank you for any help, Best Regards. A: Instead of destroying the window every time, you can just hide it with the wxWindow::Show() member function, passing false as the argument, when you receive a wxCloseEvent. You then veto the wxCloseEvent to prevent WxWidgets from destroying your window: // In your close handler: if(evt.CanVeto()) // Where evt is a wxCloseEvent { Show(false); // Hide window evt.Veto(); // Prevent window destruction } This should remove it from the screen, but all the initialized parts should still be there. If you need to show it again, call the Show() method again with true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Install "hunchentoot" error? I want to install hunchentoot on my freebsd box, but quicklisp reports error: (ql:quickload "hunchentoot") To load "hunchentoot": Load 3 ASDF systems: rfc2388 trivial-backtrace usocket Install 15 Quicklisp releases: alexandria babel bordeaux-threads cffi chunga cl+ssl cl-base64 cl-fad cl-ppcre flexi-streams hunchentoot md5 trivial-features trivial-garbage trivial-gray-streams * - Header missing magic values 1F,8B (got 3C,21 instead)! The following restarts are available: ABORT :R1 Give up on "hunchentoot" ABORT Break 1 [2]> :i : standard object type: QL-GUNZIPPER::GZIP-DECOMPRESSION-ERROR 0 [$FORMAT-CONTROL]: "Header missing magic values ~2,'0X,~2,'0X (got ~2,'0X,~2,'0X instead)!" 1 [$FORMAT-ARGUMENTS]: (31 139 60 33) :R2 Abort main loopnter code here How to fix it ? thanks! A: It looks like the files Quicklisp has downloaded are not valid; they don't start with the expected GZIP file header. Instead, they start with <!... which looks very much like HTML. Do you have a proxy involved on your network? If so, try this: (setf (ql-config:config-value "proxy-url") "http://your.proxy.url:xyz/") A: The "hunchentoot" can be installed on my archlinux box now. But the "uffi" cannot be installed: (ql:quickload "uffi") To load " uffi": Install 1 Quicklisp release: uffi ; Fetching #<URL "http://beta.quicklisp.org/archive/uffi/2010-11-07/uffi-20101107-git.tgz"> ; 175.27KB ================================================== 179,479 bytes in 10.53 seconds (16.64KB/sec) ; Loading "uffi" *** - Component "uffi" not found I donot understand why the quicklisp has so many problems !
{ "language": "en", "url": "https://stackoverflow.com/questions/7525250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++/CLI DLL project stops linking after conversion from VS2008 to VS2010 I converted a perfectly working Managed C++ DLL project that uses Unmanaged C++ LIBs from VS2008 to VS2010. Beforehand I separately rebuilt the LIBs with VS2010 (they are part of another project that I have no authority over). However, after conversion my managed DLL project stopped linking giving me few dosen of LNK2001 error messages (see the sample below). All errors about "std" entities defined within "string" and "iosfwd" headers. Which compiler/linker settings am I missing? Thanks in advance for your help. Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) bool __cdecl std::operator!=<char,struct std::char_traits<char>,class td::allocator<char> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,char const *)" (__imp_??$?9DU?$char_traits@D@std@@V?$allocator@D@1@@std@@YA_NAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@PEBD@Z) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl std::operator<<<char,struct std::char_traits<char>,class std::allocator<char> >(class std::basic_ostream<char,struct std::char_traits<char> > &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (__imp_??$?6DU?$char_traits@D@std@@V?$allocator@D@1@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@@Z) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: static unsigned __int64 const std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::npos" (__imp_?npos@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@2_KB) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __cdecl std::basic_streambuf<char,struct std::char_traits<char> >::_Lock(void)" (__imp_?_Lock@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QEAAXXZ) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: void __cdecl std::basic_streambuf<char,struct std::char_traits<char> >::_Unlock(void)" (__imp_?_Unlock@?$basic_streambuf@DU?$char_traits@D@std@@@std@@QEAAXXZ) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::basic_ostringstream<char,struct std::char_traits<char>,class std::allocator<char> >::str(void)const " (__imp_?str@?$basic_ostringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEBA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@XZ) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: __cdecl std::basic_ostringstream<char,struct std::char_traits<char>,class std::allocator<char> >::basic_ostringstream<char,struct std::char_traits<char>,class std::allocator<char> >(int)" (__imp_??0?$basic_ostringstream@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEAA@H@Z) Auxiliary.lib(Error.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::substr(unsigned __int64,unsigned __int64)const " (__imp_?substr@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QEBA?AV12@_K0@Z) etc... A: Finally found it (thanks Hans Passant for the tip!) I had a few files that were still built by VS2008 and that caused the issue. Thanks to everyone who bothered to add a comment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: backbone.js hover on root dom doesn't work Why the hover event bind on the root dom doesn't work? Though by default, i can put the <div class="activity span"></div> around the template and with a wrapper <div></div> outside, but it sucks. Please help~ thx ActivityView = Backbone.View.extend( className: "activity span" events: { "hover" : "toggleSidebarTrigger" // doesn't work.. "hover img" : "foo" // works "click" : "bar" // works } template: _.template($("#activity-item-template").html()) initialize: -> this.model.bind("change", this.render, this) this.render() render: -> $(this.el).html(this.template(this.model.toJSON())) toggleSidebarTrigger: -> this.$(".sidebar-trigger").toggle() ) <script id="activity-item-template" type="text/template"> <img src="{{ photo.url_m }}" class="activity-media" alt="" /> <a href="#toggle-sidebar" class="sidebar-trigger"><%= image_tag "plus_69x69.png" %></a> </script> A: ActivityView = Backbone.View.extend( className: "activity span" events: { "hover" : "toggleSidebarTrigger" // doesn't work.. "hover img" : "foo" // works "click" : "bar" // works } template: _.template($("#activity-item-template").html()) initialize: -> this.model.bind("change", this.render, this) this.render() render: -> $(this.el).html(this.template(this.model.toJSON())) toggleSidebarTrigger: -> $(".sidebar-trigger", this.el).toggle() ) try this one..
{ "language": "en", "url": "https://stackoverflow.com/questions/7525258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AS3 keyboard input assign to child swf can i assign a keyboard eventlistener in a child swf inside of another swf? cause i know if a swf inside of swf still only have one stage. cause the parent swf just like a loader container, i want the child swf to have the keyboard event listener. Thanks A: How are you loading the child swf? It may be a security issue. Possibly due to loaderContext or something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is it possible phone-calling in ipad? Recent iPads are having provision to insert sim card in that. So with latest iOS SDK, is it possible to call from my application. I know that in-app call is possible from iPhone. But how about iPad? is any api for that? or any app already in market? any tutorials or links . thanks A: The 3G ipad doesn't support native phone calls. The 3G is just for data transfer. However there's nothing stopping you from creating an app similar to the way Skype and other voice over ip apps work, that allow you to make phone calls from the ipad. Line2 is an example of such an app. A: It's not possible. The iPad was not created to make phone calls, and there is no native Phone app (like what the iPhone has). The SIM card slot is to allow internet use via 3G.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Overlaying a place marker image over a static image (ImageView) I've got an ImageView containing a static image (map) and I would like to put a marker on the map where the user clicks. I have an OnTouchListener registered and it's providing co-ordinates of the click but I don't know how to draw at this location. Appreciate any ideas. Thanks, m Here's a simple solution to the problem. It works, places a red dot on the background image where the user presses on the screen. Please let me know if anyone can see a problem with it. Thanks, m import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.util.Log; import android.view.ViewTreeObserver; import android.widget.ImageView; public class MapPin extends ImageView { private static final String TAG = "MapPin"; private Paint mPaint; private int mBackgroundHeight; private int mBackgroundWidth; private float mPinX; private float mPinY; //private Context mContext; private void initMapPinView(){ mPaint = new Paint(); mPaint.setColor(Color.RED); } public MapPin (Context c){ super(c); initMapPinView(); } public MapPin (Context c, AttributeSet attrs){ super(c, attrs); initMapPinView(); } public void setPin (float x, float y){ mPinX = x; mPinY = y; } @Override public void onDraw(Canvas canvas){ super.onDraw(canvas); if (mPinX > 0 & mPinY > 0){ canvas.drawCircle(mPinX, mPinY, 5, mPaint); } } } A: you need to convert lat/lng value into the screen pixel using mapview.getProjection.toPixel() method here is code Point screenPts = new Point(); mapView.getProjection().toPixels(defaultPoint, screenPts); // ---add the marker--- Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.cur_loc); canvas.drawBitmap(bmp, screenPts.x,screenPts.y, null); for more check my post how to display map in android with marker
{ "language": "en", "url": "https://stackoverflow.com/questions/7525274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: BigDecimal Problem in java BigDecimal bd= new BigDecimal("00.0000000000"); //now bd format to 0E-10 if(BigDecimal.ZERO.equals(bd) || bd.equals("0E-10")) { flag=true; } There are two problems in the above code * *why variable bd automatically format to 0E-10 *if condition results false value, ie it does not enter inside if block. Can anyone suggest. thanks A: You can test for zero using bd.signum() == 0 BigDecimal.equals also includes scale (which is 10 in your case) and thus fails. In general you should use compareTo in order to compare BigDecimals. A: You've given the constructor ten digits after the decimal point, so even though all of them are zero, BigDecimal has decided to set its internal scale to 10. This explains the -10 in "0E-10". As to equals, the Javadoc says: Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method). Bottom line: * *Use compareTo() instead of equals(). *Don't directly compare BigDecimal to String as this won't work. A: The BigDecimal uses a scale of 10 because you've given it ten digits after the decimal point, which answers your first point. For the if, for the first part, you are comparing 0 with 00.00000000000 (the scale is different, so they aren't the same). In the second, you're comparing a String with a BigDecimal. Which won't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Do I really have to do write my code differently so just so I can test it? I am coming to c# from ruby on rails where I did TDD using Rspec and Mocha. I was looking to get into get into a mocking framework and an older stackoverflow post pointed me in the direction of MOQ and rhino mocks. I was hesitant to commit to either and am looking for a bit of advice or clarification or maybe just a pep talk... Here were my concerns: * *Rhino mocks seems to be a bit out of date. A lot of the examples didn't even make use of generics because it seems like they weren't available when the framework was created *Moq seems to be less powerful than Rhino mocks and it seems like you need to adapt your classes in order to mock them (either they must implement an interface or all methods must be virtual) Am I way off base here? Am I missing something? Is there some cool new framework I should know about or do I just need to open my mind up and accept that mocking isn't the same for static languages? (I know questions kinda like this have been asked in the past but they seem a little dated to me and I am interesting in what the latest hip new things are) A: I personally vote for moq, but selection of mocking framework is really up to you. I also think that testability is good enough reason to write your code differently. Interfaces in general are quite hard to overuse and in the long run they probably make your code more maintainable. A: Test-driven development doesn't have a side-effect of making you write your code in a different way. It is actually intended to make you write code differently. We think that you write code better when you test it. You are more likely to hide code behind an interface, which is a good thing. It will hopefully make you do lots of stuff in a different way! Onto Rhino / Moq... Rhino Mocks has received a bit overhaul since it was first written, you no longer have to use the record/replay syntax, you can use Arrange-Act-Assert syntax and there are no magic strings to be seen. Rhino Mocks - Arrange Act Assert Syntax In Moq you can mock interfaces and classes. The syntax is simpler and a bit more expressive. The good news is, I think you are looking at the best two and trying to choose between them. I don't think you would regret selecting either of these.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read JSON object I have a JSON object like {"status":"200","id":"23","username":"nipinponmudi@gmail.com","fname":"hh","laname":"hh","timezone":"2","createdate":"2011-09-20 22:05:24","key":"db3f57a8f2b9abd9d51916232f5a77b9"} The object above is a response from a server.I want to display these objects in corresponding textfields on the viewdidload method.I want to read this object and display separately in textfields.I need to extract the username,fname,lname only.No need to read the status A: take a look at https://github.com/stig/json-framework/ . I'm sure they are so many source and example out there to show you. NSString *jsonString = @{"status":"200","id":"23","username":"nipinponmudi@gmail.com","fname":"hh","laname":"hh","timezone":"2","createdate":"2011-09-20 22:05:24","key":"db3f57a8f2b9abd9d51916232f5a77b9"}"; SBJsonParser *parser = [SBJsonParser new]; id object = [parser objectWithString:jsonString]; txtName.text = [object objectForKey:@"username"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7525291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Is Copy Protection Option on android market make application to uses the User Data of device? I have uploaded the Application with the Copy protection to that application. I have also given the Android Licensing to that Application. Now After downloading that application from android market, I got some problems like : 1) User is not able to start the application after restarting device 2) If user have to start again that application then he/she have to clear all the Userdata from user setting. Now i dont know why it ishappening ? Is Copy protection option of the market will make application to use the User data of the Device ?? If anyone know about it then please let me know about it. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7525307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }