text
stringlengths
8
267k
meta
dict
Q: Do we need the "Expect: 100-continue" header in the xfire request header? I found the apache xfire has add one head parameter in its post header: POST /testservice/services/TestService1.1 HTTP/1.1 SOAPAction: "testAPI" Content-Type: text/xml; charset=UTF-8 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; XFire Client +http://xfire.codehaus.org) Host: 192.168.10.111:9082 Expect: 100-continue Will this Expect: 100-continue make the roundtrip call between the xfire client and its endpoint server a little bit waste because it will use one more handshake for the origin server to return the "willing to accept request"? This just my guess. Vance A: I know this is old question but as I was just researching the subject, here is my answer. You don't really need to use "Expect: 100-continue" and it indeed does introduce extra roundtrip. The purpose of this header is to indicate to the server that you want your request to be validated before posting the data. This also means that if it is set, you are committed to waiting (within your own timeout period - not indefinitely!) for server response (either 100 or HTTP failure) before sending your form or data. Although it seems like extra expense, it is meant to improve performance in failure cases, by allowing the server to make you know not to send the data (since the request has failed). If the header is not set by the client, this means you are not awaiting for 100 code from the server and should send your data in the request body. Here is relevant standard: http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html (jump to section 8.2.3). Hint for .NET 4 users: this header can be disabled using static property "Expect100Continue" Hint for libcurl users: there was a bug in old version 7.15 when disabling this header wasn't working; fixed in newer versions (more here: http://curl.haxx.se/mail/lib-2006-08/0061.html)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Any C# .NET Libraries to export images into a PPT File I would like to export a series of images [JPEG/Gif files] into a power point presentation. Are there any .NET libraries that I can use for this purpose ? Looking for a library, which can help me create ppt from C# .NET, and import the images into slides and arrange them in slides [ for instance i could chose to have 6 images per slide / 2 images per slide ]. Appreciate any help in this regard.. Regards Vidya Sagar. A: You should look at Aspose.Slides. Their library allows generating PPT files via code. They have a very intuitive and simple API, and are very active in their development and improvements of their libraries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't my recursive array search work on this array of data? I have a recursive array search function which has previously been working a treat. For some reason though now it appears to be telling me things exist in the array which actually don't. IE, I have an array like this Array ( [0] => Array ( [name] => people [groups] => Array ( [0] => Array ( [name] => tom ) [1] => Array ( [name] => john ) ) ) ) And my recursive search function: function searchArrayRecursive($needle, $haystack){ foreach ($haystack as $key => $arr) { if(is_array($arr)) { $ret=searchArrayRecursive($needle, $arr); if($ret!=-1) return $key.','.$ret; } else { if($arr == $needle) return (string)$key; } } return -1; } If I were to do the following however: $search = searchArrayRecursive('kim',$the_array); if($search != -1) { echo 'result: found<br />'; } else { echo 'result: not found'; } I get result: found Its clearly not in the array. Maybe my function never worked. maybe my heads on backwards. Any ideass? note: I also get result: found when I search for tom or john o.O A: This example works as provided. Possibly your actual data has mixed case? ('john' != 'John') or possibly extra spaces or a stray newline because they weren't trimmed when the array was created? Try a var_dump() instead of a print_r(). It should show you the exact nature of the data you are trying to search. I suspect your data may not be in the format you expect it to be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there an event for an image change for a PictureBox Control? How do I know when the image of the picturebox change? Is there an event for an image change? A: First make sure that the images are loaded asynchronously. To do this set the PictureBox's WaitOnLoad property to false (which is the default value). pictureBox1.WaitOnLoad = false; Then load the image asynchronously: pictureBox1.LoadAsync("neutrinos.gif"); Create an event handler for the PictureBox's LoadCompleted event. This event is triggered when the asynchronous image-load operation is completed, canceled, or caused an exception. pictureBox1.LoadCompleted += PictureBox1_LoadCompleted; private void PictureBox1_LoadCompleted(Object sender, AsyncCompletedEventArgs e) { //... } You can find more information about this event on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.picturebox.loadcompleted.aspx A: There are load events if you use Load() or LoadAsync(), but not for the Image property. This is explicitly set by you (the developer) and is generally speaking in 100% of your control (see notation below). If you really wanted to though (there isn't really a point, though), you can derive your own UserControl from PictureBox and override the Image property, and implement your own event handler. Notation I suppose one event you would want an event to subscribe to is if you are using some third-party component or control that changes the image property, and you want to implement some sort of sub routine when this happens. In this event it would be a reason to need a ImageChanged event since you don't have control over when the image is set. Unfortunately there still isn't a way to circumvent this scenario. A: The Paint event is working: private void pictureBox_Paint(object sender, PaintEventArgs e) { // image has changed } A: using System; using System.Windows.Forms; using System.Drawing; namespace CustomPX { public class CustomPictureBox : PictureBox { public event EventHandler ImageChanged; public Image Image { get { return base.Image; } set { base.Image = value; if (this.ImageChanged != null) this.ImageChanged(this, new EventArgs()); } } } } You can add this Class into ToolBox and/or from code and use ImageChanged event to catch if Image is Changed
{ "language": "en", "url": "https://stackoverflow.com/questions/7551339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Sharepoint Attendees without a Workspace for Calendar Event I am wondering if it is possible to have a custom form in Sharepoint 2010 where I am able to add/edit a calendar event and access the attendees list that is normally visible on the workspace page. I assume that perhaps I need to at least hard code a workspace to be selected as I believe attendees need to be assigned to a workspace. Open to suggestions as I'm new to Sharepoint but seems crazy having to create or link to a workplace for each event. Greatly appreciate any help. A: @WashBurn not sure if this what you are looking for. Goto your calendar - list settings. goto the "Content Types" section. click the content type...should be event. from there click "Add from existing site content types " and attendees should be in there. hope that helps! A: There is a simple (unfortunately not intuitive) way to achieve what you are trying to do. * *click on list settings for your calendar list. You will see about half way down a section called content types. ![enter image description here][1] *Click on the event content type (which should be there by default. *this takes you to another similar screen where you can simply add the attendees column. Once you know that attendees are part of an event it is then intuitive. Hope this helps. A: This is one of many nasty little things that come up when you try to build your meeting management on SharePoint. Other very common problems include integration with any e-mail client, first of all Outlook but not only, sending meeting requests from SharePoint and handling the respoded attendee's status... The SharePoint calendar e-mail extension is a third party solution that might solve your problem. Here is the link: http://www.sapiens.at/en/products/pages/sharepoint-calendar-e-mail-extension-3.0.aspx A: Every SharePoint list (wether it's document library, calendar, lnks or custom list) have both a Create Form, Edit Form and a Delete Form. Each of which you through SharePoint designer can create your own custom versions of, in your case, this is needed to edit a Calendar List item with its associates/attachments. Read one of Microsoft's own guides on how, here A: Although this is a very old post, i just ran into the same issue and figured out a way to solve this issue. Simply go into the Content Type 'Event' and add the Column 'Attendees' :) Then you can also use the attendees as input for a workflow, e.g. to notify them on Event creation/update. i attached two Screenshots to show how you can do that using SharePoint designer! With this phrase you can add the Link to the Event into the Mail Body: [%Workflow Context:Current Item URL%] Hope that helps other people in the future. A: I believe I have the solution we are all looking for. * *Create a standard event calendar (the one that does not have attendees) *Add the 'Schedule and Reservations' content type to the calendar from the list settings page *Modify the 'Calendar' view so the filters read attendees is equal to me OR attendees is equal to The second entry is completely empty but allows SP to match for no attendees You can add more columns with OR statements if you need to be sorting based on additional groups This worked for my needs, hope it works for everyone else
{ "language": "en", "url": "https://stackoverflow.com/questions/7551341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Has anybody had this problem - jquery not working with Magento in Firefox? I'm running Magento 1.5.1.0 and have included a jquery image fader on the home page, running on my testing server. It works perfectly in Ie and chrome but does not work in Firefox. If i enable Template Path Hints it will run the script ok turn it of and it does'nt run. I'm getting no errors in firebug or firefox. I have this code in the head.phtml <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/ 1.3.2/jquery.min.js"></script> <script type="text/javascript"> //<![CDATA[ var $j = jQuery.noConflict(); $j(document).ready(function() { $j('#s3slider').s3Slider({ timeOut: 4000 }); }); //]]> </script> And i have this at the top of my page.xml file: <action method="addJs"><script>jquery-1.4.2.min.js</script></action> <action method="addJs"><script>jquery.js</script></action> <action method="addJs"><script>prototype/prototype.js</script></action> I have also cleared the cache in Magento and firefox. Has anybody got any ideas ?? Many thanks in advance. A: You're loading three versions of jQuery: * *1.3.2: http://ajax.googleapis.com/ajax/libs/jquery/ 1.3.2/jquery.min.js. *1.4.2: jquery-1.4.2.min.js. *and an unknown version: jquery.js. You should only load one and that should probably be a version more recent than 1.4.2. Try just loading the most recent (1.6.4) from Google's CDN: http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7551346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress post into Jquery mobile framework I want to show my wordpress post into jquery mobile application... But so far i didnt got the success. I am using jquery.post() function but my response comes empty.... Request to the desired url goes well , status comes 200 ok but response coming is always blank :( Although the same post function & url is working fine in other php pages.... below is my code function get_Time(cityCode,date){ jQuery.post( "http://test.local/time/", { city: cityCode, date:date}, function (data){jQuery('#print_time').html(data);} ); } function _get_Time(response) { alert("response:"+response); var time = new Array(); time = response.split('|') jQuery("#print_time").html(time[0]); } Please give me some solution for showing my wordpress post (only text + links) content into my jquery mobile applicaton.... A: I am not sure about what you are going to do. It seems to me, like you want to retrieve a certain WordPress post content + additional information via Ajax, I think the easiest way to do it is the following: * *Write a custom server-side PHP-Script (which possibly takes a WordPress Slug or ID) *Create a connection to the database in this script, get the post contents you want to have and return these as text or JSON to your JQuery mobile and use it It might work in a way like this (not tested): include ‘path-to-wp-directory/wp-blog-header.php’; $post_id=0; if(isset($_REQUEST['post_id'])) { $post_id=intval($_REQUEST['post_id']); } global $wpdb; $post_content = $wpdb->get_var("SELECT post_content FROM $wpdb->posts WHERE post_id=".$post_id." AND post_status='publish'"; echo $post_content; This is only possible if you have access to the server, of course. If you want to get Post Content from an external WordPress Blog, then you should consider using the RSS Feed. The following article shows how to load WordPress functions in an external PHP Script, which also might be useful: http://www.bloggingtips.com/2009/01/25/use-wordpress-functions-externally/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problems with "sliding menus" program I was reading a program to make sliding menus. Though the program works fine,there are certain things for which i don't have a clue what do they mean and what are they doing. HTML <html> <head> <title>Shakespeare's Plays</title> <link rel="stylesheet" href="script.css" /> <script type="text/javascript" src="script.js"> </script> </head> <body> <h1>Shakespeare's Plays</h1> <div> <a href="menu1.html" class="menuLink">Comedies</a> <ul class="menu" id="menu1"> <li><a href="pg1.html">All's Well That Ends Well</a></li> <li><a href="pg2.html">As You Like It</a></li> </ul> </div> <div> <a href="menu2.html" class="menuLink">Tragedies</a> <ul class="menu" id="menu2"> <li><a href="pg5.html">Anthony &amp; Cleopatra</a></li> <li><a href="pg6.html">Hamlet</a></li> </ul> </div> <div> <a href="menu3.html" class="menuLink">Histories</a> <ul class="menu" id="menu3"> <li><a href="pg8.html">Henry IV, Part 1</a></li> <li><a href="pg9.html">Henry IV, Part 2</a></li> </ul> </div> </body> </html> CSS body { background-color: white; color: black; } div { padding-bottom: 10px; background-color: #6FF; width: 220px; } ul.menu { display: none; list-style-type: none; margin-top: 5px; } a.menuLink { font-size: 16px; font-weight: bold; } a { text-decoration: none; } Java Script window.onload = initAll; function initAll() { var allLinks = document.getElementsByTagName("a"); for (var i=0; i<allLinks.length; i++) { if (allLinks[i].className.indexOf("menuLink") > -1) { allLinks[i].onclick = toggleMenu; } } } function toggleMenu() { var startMenu = this.href.lastIndexOf("/")+1; var stopMenu = this.href.lastIndexOf("."); var thisMenuName = this.href.substring(startMenu,stopMenu); var thisMenu = document.getElementById(thisMenuName).style; if (thisMenu.display == "block") { thisMenu.display = "none"; } else { thisMenu.display = "block"; } return false; } In the javascript code: * *what do these 2 statements do ? var startMenu = this.href.lastIndexOf("/")+1; var stopMenu = this.href.lastIndexOf("."); *what does this.href mean . I know that this refers to the link but what does href denote ? *what does the statement thisMenu.display == "block" mean ? I mean to say what is display and what is block . The code does not declare it anywhere. *In the same way what is meant by none ? *What does the statement document.getElementById(thisMenuName).style return ? A: 1. what do these 2 statements do ? var startMenu = this.href.lastIndexOf("/")+1; var stopMenu = this.href.lastIndexOf("."); That code is within the toggleMenu function that is assigned to an onclick listener of link elements (they are probably the items in your menu). When the function is called by the onclick handler, the function's this keyword is set to a reference to the element (i.e. the link). So the first line is getting the position of the last '/' in the href property, the second is getting the index of the last "." in the href. 2. what does this.href mean . I know that this refers to the link but what does href denote ? It is a refernce to the link's href property, which is initially set to the value of the href attribute. 3. what does the statement thisMenu.display == "block" mean ? I mean to say what is display and what is block . The code does not declare it anywhere. It is changing the value of the display property of the element's style object to "block", which is one value that it may have according to the CSS 2.1 specification. A better strategy is to set the display property in CSS (or just use the default) and in code set it to "" (empty string) so that it adopts the default or cascaded style (which can be any one of 13 values and might be different in different browsers so setting it specifically can be an issue). That way the layout and display are independent of the code, which just hides it or returns it to whatever it was. 4. In the same way what is meant by none ? That makes the element not part of the document flow, effectively hiding it and meaning it doesn't have any effect on the document layout. 5. What does the statement document.getElementById(thisMenuName).style return ? It returns a reference to the element's style object, it's used to make the code more concise (and likely a tad faster, not that you'd notice here).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HttP url problem to read xml data in jquery ajax if you copy http://tgbs.ir/xml/Category.xml in your browser , you will see content of xml file. but in below code alert doesnt show and i think url doesnt work . please help me to solve this problem because this code has to read from this url. Date.ReadCategoryXml = function() { var counter=0; $.ajax({ type: "GET", url: "http://tgbs.ir/xml/Category.xml", dataType: "xml", success: function(xml) { $(xml).find("category").each(function() { var cTitle = $(this).find("title").text() var cUrl = $(this).find("url").text(); Data.arrCategory[counter++]= new Category(cTitle,cUrl); }); alert("behnaz"); } }); } A: You can try using jsonp to get cross domain calls More info @ http://api.jquery.com/jQuery.ajax/ Example $.ajax({ url: 'http://tgbs.ir/xml/Category.xml', dataType: 'jsonp', success: function( data ) { alert("Success : "+data); } }); A: http://tgbs.ir the Domain where the script runs? If not… You can't load xml data from an other Domain because of the Same origin policy Possible Solution: craigslist rss feed In short... you have to build a wrapper function which gets your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a if statement with NSNull in objective-c I am develop a iPhone application, in which i need to use JSON to receive data from server. In the iPhone side, I convert the data into NSMutableDictionary. However, there is a date type data are null. I use the following sentence to read the date. NSString *arriveTime = [taskDic objectForKey:@"arriveTime"]; NSLog(@"%@", arriveTime); if (arriveTime) { job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; } When the arriveTime is null, how can i make the if statement. I have tried [arriveTime length] != 0, but i doesn't work, because the arriveTime is a NSNull and doesn't have this method. A: the NSNull instance is a singleton. you can use a simple pointer comparison to accomplish this: if (arriveTime == nil) { NSLog(@"it's nil"); } else if (arriveTime == (id)[NSNull null]) { // << the magic bit! NSLog(@"it's NSNull"); } else { NSLog(@"it's %@", arriveTime); } alternatively, you could use isKindOfClass: if you find that clearer: if (arriveTime == nil) { NSLog(@"it's nil"); } else if ([arriveTime isKindOfClass:[NSNull class]]) { ... A: In a single line arriveTime ? job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; : NSLog(@"Arrive time is not yet scheduled");
{ "language": "en", "url": "https://stackoverflow.com/questions/7551369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Set value into a property in Class1 from Form1 then get value of that property in Class1 to Form2 using C# Windows Form I have this problem, i've set a value to a property from shall we say Form1, then get that value in Form2 but it return null. sample code. //Sample.cs public class Sample { private string exchange; public Sample() { } public string Exchange { get { return exchange; } set { exchange = value; } } } //From Form1 set value private void setBtn_Click_1(object sender, EventArgs e) { Sample testing = new Sample(); testing.Exchange = exchange.Text; } //From Form2 get value private void getBtn_Click_1(object sender, EventArgs e) { Sample testing2 = new Sample(); string exchange2 = testing2.Exchange; } Here's the problem, exchange2 have a value of null, i know its because i declared a new instance, please tell me how to get the value using Form2 that have been set in Form1. Thanks in advance guys! A: It is OK return null because you each time create a new object Sample testing2 = new Sample(); declare the public property in Form2 class class Form2 { public Sample MySample {get; set;} } private void setBtn_Click_1(object sender, EventArgs e) { Sample testing = new Sample(); Form2 form2 = new Form2(); form2.MySample = testing; form2.Show(); } A: If you want to use classes and properties in this way make exchange field static so it will be shared among all instances of your class. Static fields are class related and not instances related and in your case from Form1 and Form2 you are creating different instances of class. A: Following are few posibilites: 1) Delcare the property static: public static string Exchange{get;set;} 2) Pass the object created in Form1 in some way to Form2:
{ "language": "en", "url": "https://stackoverflow.com/questions/7551379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set the volume mute in movie player in iphone? I am creating an app regarding movie player. In movie player I played videos. It worked fine but I want to mute the volume through coding. I want to set one button for volume mute. When I click the button it performs actions for mute. How can I proceed for this? A: Hi there is no such mute option available. But you can set volume through codebase. Check this Apple documentation, it might be helpful to you: http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMusicPlayerController_ClassReference/Reference/Reference.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7551385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete subarray from array in php? I have multidimensional array and I need to delete one sub array how can I do it without creating another array and copying values? $myarray [one] a->1 b->2 c->4 [two] a->5 b->8 [three] a->44 b->55 c->66 I need to remove two $myarray['two'] A: Try unsetting it, e.g. unset($myarray['two']); A: unset($myarray['one']) should work
{ "language": "en", "url": "https://stackoverflow.com/questions/7551386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Page Flip For Web View Now I am trying page flip animation for web view in android visit http://github.com/harism/android_page_curl and you can get information on how to page flip, but it is applicable only for images. What would I have to do to apply this for web view? A: i had also facing same problem so I'm implementing below link but its not like page curl but full fill my requirement hope your also. https://github.com/openaphid/android-flip hope use full for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it okay to allow objects to be stored in each other depending on loading order? I have an object that represent's a User's account on my site, and a separate object that acts as an attachment to the main account object and extends the user's ability to operate some major functionality on the site - a full functioning storefront. I have been representing the relationship as so: Class Account { $id $store // this is the store object $email $password $status get_store() // loads the store } Class Store { $id // unique store id $store_name $store_info post_item() } So far, this has been working great, but when I search or aggregate stores this way, it requires me to go through the Account object to get to the store. I would like to cut the process in half by being able to also get to the account object through the store. Does it create a problem to ALSO allow an $account object to be stored in the $store object, just in case I want to load it the other way around? An example of allowing for this bi-directional loading would be as follows: Class Account { $id $store // this is the store object $email $password $status get_store() // loads the store } Class Store { $id $account // this is the account object $store_name $store_info get_account() // loads the account post_item() } A: That's a common refactoring. The only thing you have to be aware of is that you will need to manage the "back pointer" when you associate one object with the other, e.g. when fetching the store for an account, you have to make sure the store will also get the back pointer to that account and vice versa. Further reading: * *Change Unidirectional Association to Bidirectional *Same with examples in PHP
{ "language": "en", "url": "https://stackoverflow.com/questions/7551390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the User's ID when they click "Like" Button on my dynamic url? Please forgive my poor English, My Problem is that i have a article.php?id=xxx , and i set the Like Button(facebook socail plugin) on the article.php , and i also set the like_href=http://bikeid.net/20110908/article.php?id=25 , the query id will do the SQL query like every select * from TABLE_NAME where id=25 , every thing is fine and well , each article.php has their own like button and count number and content and author , but my problem is that 【My Boss wanna know who click the Like Button on particular page】, I just want to get the user's FB_ID who click the page like http://bikeid.net/20110908/article.php?id=25 , if i get the FB_ID , i can use the faceboog graph api to get the user's name , but my problem is that【i dont know how to get the User's fb_id who has already clicked the http://bikeid.net/20110908/article.php?id=25】 Please provide me some example or answer , Thanks a lot! A: The only way you can get the users id is by prompting them to authenticate with your application. The like button alone will not provide you with this info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Free reporting tools for .net? I'm looking free reporting tools like SharpShooter. I use VS2008, if reporting tools can work with asp.net it would be great! A: there should be CrystalReports bundeled with VS2008. Or you should be able to use Microsoft Reporting Here is a sample-walkthrough from MSDN A: don't miss to take a look into List&Label Free Edition. It has an interesting approach of reporting and is - in my experience - more helpful in a lot of cases. They announced a new version in some weeks which will be even better for use with ASP.NET. Plenty of coding examples are included
{ "language": "en", "url": "https://stackoverflow.com/questions/7551403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP: what is the purpose of session_name I'm not quite sure what the purpose of session_names is.. Can someone please explain in what circumstances defining a name would be beneficial? A: The default is - I think - PHPSESSID. If you have more than one application on the same host, they would share those sessions. So, you should set different session names for each application, so that there is no weird stuff happening. A: You have two sites on the same domain. (say, a blog and a forum) They both run different pieces of software. If they ran on the same session and used the same variables in $_SESSION, (say, user_id), they would conflict. session_name lets you give each application a different session.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Data fetching from SugarCRM custom build module I have a custom made module in SugarCRM called AOS_Products. I have stored a product detail in that module. I want to fetch that product detail using PHP. Can anyone suggest how I can do that? A: You can directly access sugarcrm's database, one module will be mapped to one database table. But sugar will suggest you to use their SOAP/REST to access data in sugarcrm. Here is their sugarcrm web service API document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inherting parent folder permissions in new java-created files I hava a java application, that creates files and folders somewhere on the customer machines. i need that the new files and folders will get the same permissions as their parent folder, and their same permitted group. I can tell the user to do some linux manipulations on the parent folder (like using umask), but i cannot tell him to change some files that effect on all his machines.... how can i do that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7551407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIScrollView blocks run loop? I implemented a NSTimer(repeats) and UITableView on the same viewController. Somehow, when I scroll through the tableView, the run loop seems to stop firing the NSTimer. The same goes for UITextView, which is also a subclass of UIScrollView. May I know what is happening here? A: The reason that the timer stops firing is that the run loop switches to UITrackingRunLoopMode during scrolling and the timer is not added by default to that mode. You can do that manually when you start the timer: NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; NSRunLoop *runloop = [NSRunLoop currentRunLoop]; [runloop addTimer:timer forMode:NSRunLoopCommonModes]; [runloop addTimer:timer forMode:UITrackingRunLoopMode];
{ "language": "en", "url": "https://stackoverflow.com/questions/7551411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to restrict sending an email to a pre-defined destination only? I would like to send some info from within the app per email - but restruct the recipient list. I know when sending emails the standard email-dialog opens. However, is there a solution anyway? Possibly somehow intercepting the "Send" Btn and at least check the recipient list. A: No, you cannot do this. iOS requires that the user controls the final setup of an outbound email for security/trust reasons. If you're asking for undocumented workarounds, someone (not me) might know one, but your app won't be App Store-eligible if you find one. As commenter @Rog says, if you send email via your own server, you can do this however you want without Apple's restrictions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not get minOccurs="1" maxOccurs="1" for a string type in a DataContract Below is a DataContract in my WCF service and its respective xsd schema shown in the wsdl file. [Serializable] [XmlRoot(Namespace = "http://www.example.com/l0257/services/mgnt/datatypes/0/1",IsNullable = false)] public partial class InstrumentData { private string _serialNo; private string _model; private int _pointsRecorded; [XmlElement(ElementName = "SerialNo", IsNullable = false)] public string SerialNo { get { return _serialNo; } set { _serialNo = value; } } [XmlElement(ElementName = "Model", IsNullable = false)] public string Model { get { return _model; } set { _model = value; } } [XmlElement(ElementName = "PointsRecorded", IsNullable = false)] public int PointsRecorded { get { return _pointsRecorded; } set { _pointsRecorded = value; } } } WSDl file contains the below info for the respective datacontract: <xs:complexType name="InstrumentData"> <xs:sequence> <xs:element minOccurs="0" maxOccurs="1" name="SerialNo" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="1" name="Model" type="xs:string" /> <xs:element minOccurs="1" maxOccurs="1" name="PointsRecorded" type="xs:int" /> </xs:sequence> </xs:complexType> Can someone please let me know what am I missing in my data-contract to get minOccurs=1 and maxOccurs=1 for the "Model" & "SerialNo" properties of Instrumentdata class. A: See here for a full description of the way minOccurs is determined. It seems that for a reference type you must specify IsNullable=true in order to produce minOccurs=1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: FB.Auth.setAuthResponse only compatible with OAuth2 issue Loading my facebook page in a tab shows following error: FB.Auth.setAuthResponse only compatible with OAuth2. I use oauth parameter like this: FB.init({ appId: fbAppId, status: true, cookie: true, xfbml: false, oauth: true }); Am I doing something wrong ? A: remove the parameters from your JDK including: script src="http://connect.facebook.net/en_US/all.js" A: * *Log in to the Facebook account that is in charge of the App. *Go to https://developers.facebook.com/apps/ and click on the App in question. *In the left menu, under Settings, click Advanced and look at the settings in the Migrations section. I encountered this issue on a test environment of mine, and switched the "Encrypted Access Token" setting to 'Enabled' and it seems to resolve the issue for me. I did all this code work for the migration but had NO IDEA that I had to go into the App and mess with settings. HTH A: Some Facebook social plugins(the ones that require actually inserting JavaScript) have their own authentication scheme. The newly implemented Add To Timeline button is one example of a social plugin that will cause this error to appear in your JS console. Try removing social plugins and see if the error persists. If they disappear, your only real option is to switch to XFBML. A: when using outh 2 add oauth=1 to provided js function for social plugins <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/tr_TR/all.js#**oauth=1**&xfbml=1&appId=164442023647373"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> A: i had this error when using ow.fbAsyncInit = function() { FB.init({ appId : '<s:property value="app_id" />', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML oauth : true }); Old variables i used: response.session.access_token response.session.uid New variables helped: response.authResponse.accessToken response.authResponse.userId
{ "language": "en", "url": "https://stackoverflow.com/questions/7551419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can I access asp.net server control in Ajax.AjaxMethod? How can i access asp.net server control in Ajax.AjaxMethod. My code is below. protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(Default2)); } [Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.ReadWrite)] public void CreateModelPopupForRenameApplication() { Timer1.Enabled = true; } I am getting error.......on Timer1 (object ref not set) A: Ajax methods are not meant to interact with the server controls on your page in this way, because you are not actually running through the page lifecycle like when you normally load the page. That's why it cannot find the Timer1 object. You should think of these methods as stand-alone functions that calculate a value or do something independently of any page controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: convert latitude and longitude into x and y cordinates Possible Duplicate: Longitude, Latitude to XY coordinate conversion In my iphone application i am getting latitude and longitude of my current place.But I want to draw a line graph taking these latitude and longitude as points.How this is possible?? A: Try this: CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(latitudeInFloat, longitudeInFloat); MKMapPoint point = MKMapPointForCoordinate(coord); NSLog(@"x is %i and y is %i",point.x,point.y);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: DOMDocument and php html problems Alright. So I'm using DOMDocument to read html files. One thing I've noticed is that when I do this $doc = new DOMDocument(); $doc->loadHTML($htmlstring); $doc->saveHTML(); it will add on a doctype header, and html and body tags. I've gotten around this by doing this $doc = new DOMDocument(); $doc->loadXML($htmlstring,LIBXML_NOXMLDECL); $doc->saveXML(); The problem with this however is the fact that now all my tags are case sensitive, and it gets mad if I have more than one document root. Is there an alternative so that I can load up partial html files, grab tags and such, replace them, and get the string without having to parse the files manually? Basically I want the functionallity of DOMDocument->loadHTML, without the added tags and header. Any ideas? A: In theory you could tell libxml not to add the implied markup. In practise, PHP's libxml bindings do not provide any means to that. If you are on PHP 5.3.6+ pass the root node of your partial document to saveHTML()which will then give you the outerHTML of that element, e.g. $dom->saveHTML($dom->getElementsByTagName('body')->item(0)); would only return the <body> element with children. See * *How to return outer html of DOMDocument? Also note that your partial document with multiple root elements only works because loadHTML adds the implied elements. If you want a partial with multiple roots (or rather no root at all) back, you can add a fake root yourself: $dom->loadHTML('<div id="partialroot">' . $partialDoc . '</div>'); Then process the document as needed and then fetch the innerHTML of that fake root * *How to get innerHTML of DOMNode? Also see How do you parse and process HTML/XML in PHP? for additional parsers you might want to try A: You can use some divs with specific id, and then from the document object, partially extract the div object using its id.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to know if the request is ajax in asp.net in Application_Error() How to know if the request is ajax in asp.net in Application_Error() I want to handle app error in Application_Error().If the request is ajax and some exception is thrown,then write the error in log file and return a json data that contains error tips for client . Else if the request is synchronism and some exception is thrown ,write the error in log file and then redirect to a error page. but now i cant judge which kind the request is . I want to get "X-Requested-With" from header ,unfortunately keys of headers don't contain "X-Requested-With" key ,why? A: You can also wrap the Context.Request (of the type HttpRequest) in a HttpRequestWrapper which contains a method IsAjaxRequest. bool isAjaxCall = new HttpRequestWrapper(Context.Request).IsAjaxRequest(); A: Testing for the request header should work. For example: public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult AjaxTest() { throw new Exception(); } } and in Application_Error: protected void Application_Error() { bool isAjaxCall = string.Equals("XMLHttpRequest", Context.Request.Headers["x-requested-with"], StringComparison.OrdinalIgnoreCase); Context.ClearError(); if (isAjaxCall) { Context.Response.ContentType = "application/json"; Context.Response.StatusCode = 200; Context.Response.Write( new JavaScriptSerializer().Serialize( new { error = "some nasty error occured" } ) ); } } and then send some Ajax request: <script type="text/javascript"> $.get('@Url.Action("AjaxTest", "Home")', function (result) { if (result.error) { alert(result.error); } }); </script> A: it is possible to add custom headers in the client side ajax call. Refer http://forums.asp.net/t/1229399.aspx/1 Try looking for this header value in the server. A: You could use this. private static bool IsAjaxRequest() { return HttpContext.Current.Request.Headers["X-Requested-With"] == "XMLHttpRequest"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Passing an operator as a parameter to odbc_execute() I am taking my first tentative steps into prepared statements (and falling flat on my face). Previously, I built the following from $_GET and echoed it back - the code was working fine and it returned what I expected from my simple test database. SELECT * FROM edit_box WHERE (tag="9") AND (text="mango") ORDER BY time_stamp DESC and when I try to code it using a prepared statement, even if I don't use $_GET but just hard-code the values from the previous, my code looks like this $odbc_query = OdbcPrepare('SELECT * FROM edit_box WHERE (tag="?")' . ' AND (text ? "?") ORDER BY time_stamp DESC'); $odbcResult = odbc_exec($odbc_query, array('9', '=', 'mango')); var_dump($odbcResult); I get NULL. Obviously a beginner mistake, but I stare at it and still don't say d'oh! What am I doing wrong? A: You cannot do this -- AND (text ? "?") Parameters, like this, can usually only be passed for actual values - and in some cases identifiers... To do what you want you need to interpolate the '=' inline into the SQL statement... Kind of, like this -- $logical_operator = '='; $sql = SELECT * FROM edit_box WHERE (tag=\"?\") AND (text $logical_operator \"?\") ORDER BY time_stamp DESC'); $odbc_query = OdbcPrepare($sql); $odbcResult = odbc_exec($odbc_query, array('9', 'mango'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7551425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ListView with DataPager problem VB.Net / ASP.NET I've been hunting down this problem for days, so far I have tried many popular methods, absolutely nothing, my listview just dissapears after I rebind it. I am binding a List(Of KeyValuePair(Of String, Integer)), for the indexing functionality, to ListView. When I first bind it, it works nicely, it shows all the key, and value pairs in the required limits of DataPager, but when I turn to pager, the listview dissapears. Heres what happens when PagePropertiesChanging on ListView is called. Me.DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, False) userInterface.DataPagerReBind(ListView1) And the actual ListView <asp:ListView ID="ListView1" runat="server" EnableTheming="True" OnPagePropertiesChanging="ListView1_PagePropertiesChanging"> <LayoutTemplate> <table cellpadding="2" width="640px" border="1" ID="tbl1" runat="server"> <tr id="Tr2" runat="server" style="background-color: #98FB98"> <th id="Th1" runat="server">Test point name</th> <th id="Th2" runat="server">Number of failed Test points</th> </tr> <tr runat="server" id="itemPlaceHolder" /> </table> </LayoutTemplate> <ItemTemplate> <tr id="Tr1" runat="server"> <td> <asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("key") %>' /> </td> <td> <asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("value") %>' /> </td> </tr> </ItemTemplate> </asp:ListView> <asp:DataPager ID="DataPager1" runat="server" PageSize="10" PagedControlID="ListView1" > <Fields> <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" /> <asp:NumericPagerField /> <asp:NextPreviousPagerField ButtonType="Button" ShowLastPageButton="True" ShowNextPageButton="False" ShowPreviousPageButton="False" /> </Fields> </asp:DataPager> And userInterface.DataPagerRebind just rebinds the listview to the original list. Can anyone help? I've realy gone lost here, this has troubling me for soo long, the listview just dissapears when I use the pager. Thank you. Definition for userInterface.DataPagerReBind: Sub DataPagerReBind(ByRef listView1 As ListView) listView1.DataSource = TestList listView1.DataBind() End Sub A: protected void DataPager1_PreRender(object sender, EventArgs e) { //Assign the updated datasource to your listview again //Bind the listview. } This is C# code so try to use the pager prerender event in vb.net
{ "language": "en", "url": "https://stackoverflow.com/questions/7551427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send app to background on button tap In my apps there is a button named "Back". When the user clicks on that button, the apps should be sent to the background, like when we click on the home button. A: Even if you manage to do this, it is against Apple's HIG (because it will look as a crash to the user) - if you plan to publish your app on the AppStore you'll be rejected. A: I think turning to background is impossible. Make user press home button by using UIAlertView with no cancel button. A: We can send an application to the background using SpringBoardUI or the SpringBoardServices private frameworks. However, Apple won't accept this on the App Store.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I plot a function and data in Mathematica? Simple question but I can't find the answer. I want to combine a ListLinePlot and a regular Plot (of a function) onto one plot. How do I do this? Thanks. A: An alternative to using Show and combining two separate plots, is to use Epilog to add the data points to the main plot. For example: data = Table[{i, Sin[i] + .1 RandomReal[]}, {i, 0, 10, .5}]; Plot[Sin[x], {x, 0, 10}, Epilog -> Point[data], PlotRange -> All] or Plot[Sin[x], {x, 0, 10}, Epilog -> Line[data], PlotRange -> All] A: Use Show, e.g. Show[Plot[x^2, {x, 0, 3.5}], ListPlot[{1, 4, 9}]] Note, if plot options conflict Show uses the first plot's option, unless the option is specified in Show. I.e. Show[Plot[x^2, {x, 0, 3.5}, ImageSize -> 100], ListPlot[{1, 4, 9}, ImageSize -> 400]] shows a combined plot of size 100. Show[Plot[x^2, {x, 0, 3.5}, ImageSize -> 100], ListPlot[{1, 4, 9}, ImageSize -> 400], ImageSize -> 300] Shows a combined plot of size 300.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to pass string value from one class to another I just want to know that how to pass the string value from one class to another.. Actually i have two classes.In first class i fetch string value from the array and i just want to use this string value into my second class.Now i don't know how to pass value between this two classes.Please give me some idea to do that.Should i use some class method to pass the value.But i don't know how to use this class methods.How i create the class methods to set the values from one class and then get the same value from class methods. Thanks for help A: Class1.h: @interface Class1 : NSObject { NSArray *arr; } - (NSString *)myString; @end Class1.m: @implementation Class1 - (NSString *)myString { return [arr objectAtIndex:0]; } @end Class2.h: @interface Class2 : NSObject { } - (void)methodThatUsesStringFromClass1:(Class1 *)c1; @end Class2.m: @implementation Class2 - (void)methodThatUsesStringFromClass1:(Class1 *)c1 { NSLog(@"The string from class 1 is %@", [c1 myString]); } @end A: The simplest way is to define public @property in class where you want to pass your object, for example, for NSString: // CustomClassA.h @interface CustomClassA : NSObject { } @property (nonatomic, retain) NSString *publicString; @end // CustomClassA.m @implementation CustomClassA @synthesize publicString; @end In your sender: //somewhere defined CustomClassA objectA; [objectA setPublicString:@"newValue"]; But you should understand what means retain, @synthesize and other. Also it is not your current question. A: you can use appDelegate.YourStringVaraible =@"store your string"; and then use this YourStringVaraible in any class by using appDelegate.YourStringVaraible A: pass the string parameter by overriding the init method. Class1.m @implementation Class1 Class2 *class2 = [[Class2 alloc] initWithString:myString]; ... @end Class2.h @interface Class2 : NSObject { NSString *string2; } @end Class2.m -(id) initWithString:(NSString*)str { self = [super init]; if(self) { string2 = str; } return(self); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert my Xml File into customized Xml file using XSLT 2.0? I want to Convert my Input Xml File into more customized xml file by using XSLT 2.0. This is my Input Xml File... <w:document> <w:body> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph1</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph2</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Heading1”/> <w:r> <w:t>First Heading1 Paragraph</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph3</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph4</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Heading2”/> <w:r> <w:t>First Heading2 Paragraph</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph5</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Heading3”/> <w:r> <w:t>First Heading3 Paragraph</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph6</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Heading3”/> <w:r> <w:t>Second Heading3 Paragraph</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph7</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Heading1”/> <w:r> <w:t>Second Heading1 Paragraph</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph8</w:t> </w:r> </w:p> <w:p> <w:pPr pStyle=”Normal”/> <w:r> <w:t>Normal Paragraph9</w:t> </w:r> </w:p> </w:body> </w:document> And I Expected Output XML File is Given Below... <Document> <Paragraph>Normal Paragraph1</Paragraph> <Paragraph>Normal Paragraph2</Paragraph> <Heading1> <Title>First Heading1 Paragraph</Title> <Paragraph>Normal Paragraph3</Paragraph> <Paragraph>Normal Paragraph4</Paragraph> <Heading2> <Title>First Heading2 Paragraph</Title> <Paragraph>Normal Paragraph5</Paragraph> <Heading3> <Title>First Heading3 Paragraph</Title> <Paragraph>Normal Paragraph6</Paragraph> </Heading3> <Heading3> <Title>Second Heading3 Paragraph</Title> <Paragraph>Normal Paragraph7</Paragraph> </Heading3> </Heading2> </Heading1> <Heading1> <Title>Second Heading1 Paragraph</Title> <Paragraph>Normal Paragraph8</Paragraph> <Paragraph>Normal Paragraph9</Paragraph> </Heading1> </Document> A: I think it's possible. A XSLT manual is available under http://www.w3.org/TR/xslt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can we have "Chroma key" technique using plain CSS or jQuery? This one is not trivial. I want to create a chroma key menu. For those not familiar, it is the same in video with the green background (or whatever color) being removed and special background is added. I have images as a background in a menu. What I want is to set in someway the section where the background is transparent and the rest being filled with a color. In the example below, the background of the menu is image. Can we have such a background without one? I am interested in unified solutions, not ones using css3. A: I'm happy to be proven wrong, but I'm fairly sure the answer is no, not even with CSS3. Maybe using IE's very advanced filter()s but those aren't cross-browser. Using a transparent channel for the background is the only way to go. It won't be trivial, but you could use a server-side script to change a specific colour into the transparent colour. ImageMagick should be able to do this. Here's a promising example. However, these examples are for replacing one colour. Whether it's possible to make this look good for anti-aliased edges (where the "transparent" colour blends into the surface colour, creating a mixture that the program would have to detect), I don't know. If at all possible, use proper transparency from the start. A: I imagine this would be possible on the client-side by copying the image into a <canvas> rendering context, processing the image data (like ImageMagick does) then outputting a data uri which you can use as the CSS background-image of your menu. For reference see: http://www.hmp.is.it/creating-chroma-key-effect-html5-canvas/ http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-url/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c# generic constraint where is not class? is there a where clause for a generic that determines that T is of type primitive? void Method<T>(T val) where T : primitive case: have a functional language written in C that feeds on primitive unmanaged blitable types, or things that can be pushed into a primitive easily (eg. a date without hours/mins/seconds could be pushed to an int, etc.) The original plan was to utilise GPU. Not doing that though. C# is holding up well in its co-ordinator role so far. I tend to think of the schema's home as living in C#. This isn't strictly true, but the idea serves the project well. I like OO, but when it comes to functional ideas, I'd like to constrain those thoughts to types that are supported in that domain. Interestingly, I'm still leaning on C# to help me stay structured and disciplined. I don't see that changing. There are other reasons why getting more detailed with constraints would be a good thing for me. btw: resharper suggested explicit interfaces which I tried for a while. I really liked this notation... and the constraints can live with the interface too. Nice. However, I came across Jon Skeet's warning on S/O about this messing up inheritance. So, back to a more labour intensive run-time AssertIsXYZ. To take that a little further, where constraints to me are a step towards proof of correctness (old ideas, but still good ones). The typing system seems to enable some of this to be pushed to the compiler. Using the word "where" made think about a clause or phrase (like in SQL/LINQ). I'm not asking for it to be taken to the nth degree. The more work the compiler can do the better as far as I'm concerned. Getting tactile with constraints helped me clarify some ideas. Got to give credit there... but it's a pity that I had to comment the constraints out afterwards. A: No! There is no constraint for primitive type. Your best bet in enforcing primitive type is as under: void Method<T>(T val) where T:struct { if (!typeof(T).IsPrimitive) throw new ArgumentException("Only primitive types are allowed.", "val"); } OR public void Method(int val) { GenericMethod(val); } public void Method(double val) { GenericMethod(val); } private void GenericMethod<T>(T val) where T:struct { } A: I suspect that what you want based on your comments on Jon's answer is a way to constrain a type parameter to either blittable types or unmanaged types. An "unmanaged type" is a type whose definition precludes any reference to memory tracked by the garbage collector; you can only make pointer types out of unmanaged types. Blittable types are those types which can be marshalled from managed to unmanaged code without any modification to their bits; they are a subset of the unmanaged types. A number of people have told us that it would be quite handy to have a generic constraint that constrains a type parameter to be only an unmanaged type. We have experimented with prototypes of C# and the CLR that have this constraint, but have no plans at this time to actually put the feature into the product. If you can describe the scenario that is motivating the feature request, that would help us prioritize the feature against the hundreds of other features that are also possible. A: You can't do this(at least currently). If you want it to be a value type: void Method<T>(T val) where T : struct or you can check it at run time to make sure it's really primitive(I think you want int/float/etc instead of all value types?) public static class Ext { public static bool IsPrimitive(this Type t) { return t == typeof(int) || t == typeof(float) || t == typeof(double) || ... } } EDIT LOL just found that there is a built-in property in Type named IsPrimitive, that's what I'm going to say... A: I am just appending some new information to this thread, sorry for digging it up... As many people have already answered, the following construct can be used for this reason for quite some time now: void Method<T>(T val) where T : struct With the release of C# 7.3, one will be able to write: void Method<T>(T val) where T : unmanaged which insures that you can take a pointer/address/size of T, meaning that the following is now perfectly valid: unsafe static U BinaryConvert<T, U>(T input) where T : unmanaged where U : unmanaged => *(U*)&input; float value = 42.80f; int bits = BinaryConvert<float, int>(value); This does technically help you in strictly constraining T to language primitives ... but it's a start, I guess. Sources: * *Proposal: https://github.com/dotnet/csharplang/blob/master/proposals/csharp-7.3/blittable.md *Issue: https://github.com/dotnet/csharplang/issues/187 A: There's where T : struct That's not the same as it being a primitive type, mind you. It forces it to be a non-nullable value type. That would include, say, Guid (which isn't a primitive) but exclude Nullable<Guid> (which isn't a primitive either, but also isn't a class). If you can be more precise about your requirements, we may be able to help you more. A: There is not, but you can use struct constraint. where T: struct A: A constraint has to be a non-sealed type, so there isn't a way to constrain a generic to a primitive type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: j is null exception while tinyMCE editor is added to the page as a widget I have a page where we can add any number of widgets containing tinyMCE editor. When I add the first widget the editor works fine. If I try to add a second widget or more the editor of the second widget shows 'j is null' error. The widgets and textareas have unique ids in all the cases. The widgets containing the editor is added using jQuery drag and drop method. The application is created in asp.net mvc 3 I used functions for initializing the tinyMCE as tinyMCE.execCommand('mceAddControl', false, textareas_id); and for destroying the tinyMCE as tinyMCE.execCommand('mceFocus', false, textareas_id); tinyMCE.execCommand('mceRemoveControl', false, textareas_id); I need the editors of all the widgets to work fine A: Make sure all tinymce editors have different ids. You may weant to check this SO-question regarding the "j is null" error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: connect to different type of DBs Is it possible for a playframework app to connect to different types of database systems, for example, MySQL and also MongoDB, and decide on the fly based on the traffic which database:table on which database system to talk to. A: Basically, Play manages only one RDBMS database using the DB configuration in application.conf. Play takes care of providing a Connection object to modules requiring it (the default JPA and also Siena for ex) But nothing prevents from connecting several databases at the same time to Play. Then querying the right database depending on some routing rules is not really meaningful because it's more at the class model level that it is decided right now. If your model is JPA, it will use the RDBMS, if it is Siena, it will use GAE/RDBMS/SDB (siena doesn't manage yet multidb connection), if it is Morphia, it will use MongoDB etc... Thus, if you want to use directly SQL (or anything else) for ex & multidb connections and route to the right DB/table according to some rules, nothing prevents from doing it. Nevertheless, you will have to implement a little Play module to manage it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql to mysqli php I am trying to convert my current code to MySQLi extension... But I have a problem with this code.. $sql = "SELECT COUNT(*) FROM users WHERE username='$username'"; $result = mysql_query($sql); if (mysql_result($result, 0) > 0) { $errors[] = 'The username is already taken.'; } What is the mysqli function of "mysql_result" ? I can't get it work. My current MySqLi code is just the connection and $sql = "SELECT COUNT(*) FROM users WHERE username='$username'"; $result = $mysqli->query($sql); if (mysql_result($result, 0) > 0) { $errors[] = 'The username is already taken.'; } But I need to change the mysql_result, but can't find the opposite function in MySQLi.. A: I usually use the object-y interface to MySQLi: <?php $db = new mysqli($hostname, $username, $password, $database); $result = $db->query('SQL HERE'); // OOP style $row = $result->fetch_assoc(); $row = $result->fetch_array(); while($row = $result->fetch_row()) { // do something with $row } // procedural style, if you prefer $row = mysqli_fetch_assoc($result); $row = mysqli_fetch_array($result); while($row = mysqli_fetch_row($result)) { // do something with $row } ?> Full list of result methods is here: http://www.php.net/manual/en/class.mysqli-result.php A: Based on this thread, there is no such equivalent: MySQLi equivalent of mysql_result()? They give some possible alternatives, however. A: There is no equivalent to mysql_result, but you can fetch a single row and use the first element of this row (because your query returns a table of one row and one column): $sql = "SELECT COUNT(*) FROM users WHERE username='$username'"; $result = $mysqli->query($sql); $arr = $result->fetch_row(); if ($arr[0] > 0) { $errors[] = 'The username is already taken.'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Server type from a given URL What is the PHP function to get the server type and information from a given 'URL'? A: PHP doesn't has a built in function to get that type of information (which is rarely useful unless you have easier ways to get it that don't involve programming, or unless you are planning to attack the server). It is possible to make an educated guess about what the server is by examining HTTP response headers (which somethings declare information about what the server is, sometimes don't and sometimes lie). I believe it is also possible to do low level network testing to look for oddities about how it responds and use that information as a fingerprint. A: The ($_SERVER) array is only available on the Server php is running on as are all php variables. If you have access to the Server you can use ($_SERVER) and phpinfo to get informations. If you don't you should use another tool to examine the server like: nmap. A: $_SERVER works only on localhost but you should give it a try you can get some information if server administrator haven't changed server signature.. like when you go to a 404 error link apache send information in line the end of the page and you can get it using fopen() function... I don't think there's other way to do it.. and if you found another way to do it please post it here
{ "language": "en", "url": "https://stackoverflow.com/questions/7551471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does omitting the declaration of ivars for properties might cause trouble or leaks? I started to learn and develop for iOS4, so I just skipped the old ivar declaration convention and started to use pure properties without even declaring ivars. Everything went fine, I even released my first homemade app on the app store. But then at my dev company, guys told me that they are still using old convention and are declaring ivars with underscored names, use properties and synthesize them (see example at the end). They also said that they are using properties only when outside access to ivars is needed, and for inner access they use direct ivars (for custom classes). I was told that they are doing so because they were experiencing some weird leaks, that sometimes appeared when using custom classes and nil'ying their properties in viewDidUnload (because setting nil to properties sometimes didn't release those ivar objects) Just wondering why should I bother to use ivar declaration when using properties and synthesize does all the needed stuff. I can even access ivars directly using their names without self in dealloc. So, does anybody got problems with that or many of you still are sticking with the old declaration convention? @interface ContactModel : NSObject { NSString *_firstName; } @property (nonatomic, retain) NSString *firstName; @end @implementation ContactModel @synthesize firstName = _firstName; -(void)dealloc{ [_firstName release]; [super dealloc]; } @end Should also note, that Apple still uses that old declaration style when generating main app delegate class file and synthesize window=_window. Hm, currently, I'm a little bit confused about what convention should I take, so any ideas are welcome :) A: In the modern runtime you don't need the ivar declaration, but synthesize a=_a is still useful to make a distinction between self.a (accessors) and _a (direct access). If @property/@synthesize was leaking I think we should know it by now. AFAIK using ivars instead properties is only useful if you want @protected access (access to subclasses only), or support the old runtime. In dealloc you should release the property directly whether you are using ivar declaration and @properties, and optionally you can nil or not. A: i favor the 'old way' because i favor consistency and (more importantly) encapsulation. Consistency personally, i just want a good idea of the object's size and complexity by looking one place. example: when you implement dealloc, do you prefer to refer to multiple places? not me. it's more complicated than is necessary. i don't want to figure out what i need to cleanup by creating a set from all ivars and properties. properties alone are not enough because they also end up in multiple places (interface, private categories) =\ so the lesser evil imo is to declare ivars so everything is in one place and you have a quick reference to the object's complexity (as well as a good input for some code generators). Encapsulation when you see a program where most objects' ivars/properties are visible and read/writable... that's not OOD, it's a mess. when you need to describe it politely, it's the anti-pattern 'Object Orgy'. unfortunately, it's relatively common in objc programs (partly due to language/runtime restrictions). ivars with prefixed underscores: personally, i don't use that convention in objc. if that's how their code is written, then go with it (not a big deal). They also said that they are using properties only when outside access to ivars is needed, and for inner access they use direct ivars (for custom classes). right - here's where attempts at encapsualtion enter the picture. go with it and embrace proper encapsulation. I was told that they are doing so because they were experiencing some weird leaks, that sometimes appeared when using custom classes and nil'ying their properties in viewDidUnload (because setting nil to properties sometimes didn't release those ivar objects) ideally, they would have provided you with a better explanation (and gotten to the root of the specific problem at the time). it's likely that their mystery program(s) did not make a clear enough distinction from its members (data), interface, and its execution. when those overlap, it's not uncommon to lose track of ownership. that case is a general sign of disorganization and/or an implementation extending beyond expectations. if you organize/write classes properly, ivar/property tracking is dead simple (presumably, they are making progress by favoring encapsualtion). as well, protected is the default visibility; i recommemnd private as your default. Just wondering why should I bother to use ivar declaration when using properties and synthesize does all the needed stuff. I can even access ivars directly using their names without self in dealloc. So, does anybody got problems with that or many of you still are sticking with the old declaration convetion? * *a program that is well designed is not composed of data blobs (with publicly or property accessible variables). *in most cases, state (e.g. ivars) should not directly map to interface. *keep your data and impementations well hidden from others. *even 'private' properties can be an easy source of error (their selectors may be performed or overridden). *when private is your default and the ivar is truly inaccessible externally, you can reduce a lot of complexity. so... i see it as they are making this request to make your life simpler by reducing external exposure to state and ultimately to the program's complexity. they have admitted to having had problems in the past, and they are trying to use encapsulation to reduce complexity and chances for errors. good for them. i know, some programmers just prefer everything publicly visible and mutable - writing programs to support that level of complexity is not an effective use of time, and the reality is that the majority of the people who do write that way don't have the foresight or patience to actually write such a propgram correctly and it then causes headaches for others. sure, it may have worked for you in the past, but it is a naive approach and you don't have the luxury of writing all the programs when you work with a team. therefore, you can't assume they have read and understand every program you write in its entirety. make your programs user/error-resistant by hiding what you can, and make them consistent with your team's style. (there are technically a few additional benefits, which i'll not detail here)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pass parameter client to server-side with RIA services I'm using RIA Services with EF and a Silverlight UI and the built-in validation framework. Problem is the following: The validation rules differ slightly based on user-input client-side, consider this simple scenario. protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (validation_mode == Modes.Normal) { // do normal validation } else { // do admin validation } } I'd like a way to pass the 'validation_mode' to RIA services, server-side. Can i somehow pass it to the ValidationContext.Items collection? Perhaps I'm going about this the wrong way? Thanks in advance! A: You can add the validation_mode to the ValidationContext: ValidationContext.Items.Add(new KeyValuePair<object,object>("validation_mode", validation_mode));
{ "language": "en", "url": "https://stackoverflow.com/questions/7551476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Highlighting a cell while touching iphone(giving a glowing effect just like touching a button) This may be a simple question but i cant find a solution.i'm using a table view.i want to give a highlight option when user selects that cell.highlight means giving a glowing effect for the cell(just like highlighting a button while touching.Is this possible.Can anyone help me.Thanks in advance. A: You can do that in several ways: * *Programmatically when customizing your UITableViewCell by setting appropriate value of selectionStyle (UITableViewCellSelectionStyleBlue, UITableViewCellSelectionStyleGray or UITableViewCellSelectionStyleNone) cell.selectionStyle = UITableViewCellSelectionStyleBlue; *In Interface Builder (if you load your cell from .xib file): In the Attribute Inspector set property Selection : blue, gray, none
{ "language": "en", "url": "https://stackoverflow.com/questions/7551484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: blocking in login page In simple web program I want to block users for some time in log in page if they type incorrect password for 3 times! How can I implement it? Is it good idea that store counter in database? A: This may help: http://www.webcheatsheet.com/PHP/blocking_system_access.php A: This is something that you need to implement on the server-side. Yes, you basically store the time of the next allowed login in addition to the number of consecutive failed login attempts. If you get a login request and the time is less than the first allowed login time, then you return an error code. If you get a failed login attempt, you increment the number of failed consecutive logins, set the next allowed login time to the current time plus some delay (computed based on the number of consecutive failures), and again return an error code. On a successful login, you clear the number of consecutive failures.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't download sources (NullPointerException) Whenever the m2eclipse plugin wants to download the source files of a Maven dependency I'm getting the following error: java.lang.NullPointerException at org.eclipse.m2e.jdt.internal.BuildPathManager.attachSourcesAndJavadoc(BuildPathManager.java:845) at org.eclipse.m2e.jdt.internal.DownloadSourcesJob.run(DownloadSourcesJob.java:165) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54) Do you know what the problem could be? According to the source code the problem seems to be in this line: cp[i] = JavaCore.newLibraryEntry(entry.getPath(), srcPath, null, entry.getAccessRules(), // attributes.toArray(new IClasspathAttribute[attributes.size()]), // entry.isExported()); I'm using the new Eclipse Indigo with the current Maven version. A: I believe I ran into a problem with a similar symptom, but totally different cause, where the entry's getPath() was returning null. If you turn on debug output in Preferences... Maven, I suspect you'll be shown the path. If it's just one jar, you might check the dependency's pom and then check to see if the source jar is where it should be. It shouldn't blow up like this, of course, but stranger things have happened.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing Value to Javascript function via Android Menu I have a WebView and the it loads a html page which has javascript function in it. The WebView has some Menu's namely, edit, refresh, next & previous. When i press Edit, i want the javascript to do what it has to?. When i press edit, the JS function has to show checkbox. I am not being able to pass the value to the html page. Any help will be appreciated. A: your question is not clear. You want to check a checkbox in an HTML-page after you press the edit button in an android menu? use addJavascriptInterface to pass values from javascript to java: http://developer.android.com/guide/webapps/webview.html or just use webview.loadUrl("Javascript:...") to let javascript do something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling stored procedure in jdbc I am developing android application. And i am using sql sever 2008 database to store and retrieve the data. Now i am calling the stored procedure in jbdc. Here is the code. Now it gives me Exception which says Invalid Column Index at 3. I am using the same code in other place which works fine. Bt don't know why nt working here. Give proper advice if you have any idea. Thank You. I just found out that when the String dat = rs.getString(3); is executing it shows the above exception. Let me tell you that in stored procedures it was datetime. But it executes well. Any suggestions do help me. Here is the stored Procedure A: From looking at your java code, it would appear that your parameters are either OUT or INOUT params. If that is the case, you probably need to register them as such, so you can get data from them. eg cst.setInt(1,userId); cst.setLong(2,taskId); cst.setString(3, date); cst.registerOutParameter(1, Types.NUMERIC); cst.registerOutParameter(2, Types.NUMERIC); cst.registerOutParameter(3, Types.VARCHAR); rs = cst.executeQuery(); Hopefully, that should fix your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Start/Stop apache using shell script I am trying to start/stop apache 2.2, using shell script. At present I am using: /usr/local/apache/bin/apachectl start /usr/local/apache/bin/apachectl stop If there is a way to start it: ./StartApache.sh start Thanks in advance. A: Why not use the official way - the apachectl script? You can write your own script that invokes the official script, but why bother? And you certainly don't want it in your current directory - you have lots of directories, don't you? You might add your script to a directory on your PATH (such as $HOME/bin, assuming you have that directory and it appears on your PATH); you might simply add a symbolic link to a directory on your PATH that points at the official script. If you must do it, then: cd $HOME/bin && ln -s /usr/local/apache/bin/apachectl ./Apache Now you can do: ./Apache start ./Apache stop ./Apache restart when you're in your $HOME/bin directory, and (more usually) just: Apache start Apache stop Apache restart without any path specified, so the shell finds the script for you. Of course, you could also simply add /usr/local/apache/bin to your PATH and use apachectl directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split articles in subpages every nine articles I want to seperate my content elements to several subpages of 9 content elements each. Example: If I have 5 content elements then I have only 1 page in the navigation. If I have 14 content elements then there is the navigation with the link to page 1 & 2. It should be a navigation which automatically creates temporare subpages each nine content elements. How do I achive this? Edit: I do not use Templavoila.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Form wrapped in jQuery causing some issues I have a form wrapped in jQuery. It slideToggles on click of a div. This form is self submitting. So when I display any errors / confirmation on submit of the form, they'll be encapsulated within the jQuery / div. On the page reload the jQuery hides the form disallowing the user to see the errors / confirmation unless they reopen the contact form. Now, I clearly am unhappy with that. What would be a work around this. I haven't jumped to much into AJAX as of yet. Would this be my only option here? And if so, what would be some basic code or a good starting ground to solve this? Thank you. Here is the jQuery for when a user clicks the contact div, and below merely represents that it is a self submitting form. $(document).ready(function() { $('#box').hide(); $('#contact_link_contact').click(function() { $('#box').slideToggle(1500); }); }); <form action="" method="post"> A: Try this: $( form ).submit( function() { $.ajax() // send data here return false; }); This will prevent the page from reloading when you submit the form, but you will need to send the data using ajax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make Scroll pane static? Observation:: Whenever the user reaches the last cell in the table and press Tab key, the focus is shifted to the first cell i.e the top the table. Brought the table view back to the last cell, by using the function table.scrollRectToVisible(rect), but due this there is movement and looks like there is a false change in the table values. The Scenario :: If I have make the make Scroll pane Static at particular position, so that I can control the movement. How can make this possible.. Thank You in Advance... A: The basic approach is to wrap the table's default navigation action into a custom Action which checks for the current cell: if it's the last, do nothing otherwise execute the wrapped action code example: Object key = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .get(KeyStroke.getKeyStroke("ENTER")); final Action action = table.getActionMap().get(key); Action custom = new AbstractAction("wrap") { @Override public void actionPerformed(ActionEvent e) { // implement your prevention logic // here: don't perform if the current cell focus is the very cell of the table int row = table.getSelectionModel().getLeadSelectionIndex(); if (row == table.getRowCount() - 1) { int column = table.getColumnModel().getSelectionModel().getLeadSelectionIndex(); if (column == table.getColumnCount() -1) { // if so, do nothing and return return; } } // if not, call the original action action.actionPerformed(e); } }; table.getActionMap().put(key, custom);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: webview without scroll bars in android app i am trying to load some web pages in web view of my android app. By default when the page gets loaded i want the web page to be within the device screen size, without any scroll bars making to move either horizontally or vertically.Is this possible. I found a option of adding view port in the webpage as follows, <meta name='viewport' content="width=devicewidth"/> Here what is mean by device width, if it refers to the android device width which i am using, then how it will be applicable from all the android devices. what can i do if the web page is out of my control. Is there any way to add the view port in my apps code. How to do this....... A: Try using combination of yourWebView.getSettings().setLoadWithOverviewMode(true); yourWebView.getSettings().setUseWideViewPort(true); The page will be loaded completely zoomed out and no scrollbars will be getting in the way (I think). You can also add yourWebView.getSettings().setSupportZoom(false); to disable zooming.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding to cart problem (What am I missing) What am missing in code? Any suggestions? Error display like this:- Error Type: Microsoft JET Database Engine (0x80040E14) Syntax error (missing operator) in query expression 'orderID =1AND productID ='. /mcartfree/addToCart.asp, line 49 Code is so far 'Main program Sub CreateNewOrder() Application.lock if Application("orderID") = "" then Application("orderID") = 1 end if intOrderID = Application("orderID") Session("orderID") = intOrderID Conn.Execute("INSERT INTO orders " _ & " (orderID, status) values " _ & " ("&intOrderID&", 'OPEN')") Application("orderID") = Application("orderID") + 1 Application.Unlock End Sub Sub AddToOrder(nOrderID, nProductID, nQuant) sqlText = "INSERT INTO itemsOrdered " _ & " (orderID, productID, quantity) values " _ & " ("&nOrderID&", "&nProductID&", "&nQuant&")" Conn.Execute(sqlText) End Sub 'Main program intProdID = Request.form("intProdID") intQuant = Request.form("intQuant") set Conn = Server.CreateObject("ADODB.Connection") Conn.Open ConString intOrderID = cstr(Session("orderID")) if intOrderID = "" then CreateNewOrder end if sqlText = "SELECT * FROM itemsOrdered WHERE orderID =" & intOrderID & "AND productID =" & intProdID set rsOrder = Conn.Execute(sqlText) if rsOrder.EOF then txtInfo = "This item has been added to your order." AddToOrder intOrderID, intProdID, intQuant else txtInfo = "This item is already in your cart." end if New Error Error Type: Microsoft JET Database Engine (0x80004005) Operation must use an updateable query. /mcartfree/addToCart.asp, line 19 Now again the new error Error Type: Microsoft JET Database Engine (0x80004005) Operation must use an updateable query. /mcartfree/addToCart.asp, line 31 A: Probably you are missing whitespace orderID = 1 AND productID = instead of orderID =1AND productID =. I your case system can't find AND operator becuase it's represented in query like value 1AND for orderId field. Update your query with the following: sqlText = "SELECT * FROM itemsOrdered WHERE orderID = " & intOrderID & " AND productID = " & intProdID set rsOrder = Conn.Execute(sqlText) ^ ^ ^ whitespace whitespace!!! whitespace A: Write out your SQL string and see if its correct: sqlText = "SELECT * FROM itemsOrdered WHERE orderID = " & intOrderID & " AND productID = " & intProdID ' Debug sql... Response.Write(sqlText) Response.End() ' Just debuging the SQL statement.... set rsOrder = Conn.Execute(sqlText)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .bat file interaction with java or C#.net GUI application How to interact .bat file with java or C#.net GUI application? Here is part of my .bat code. :Valid echo Enter student id: set/p "pass=>" if NOT %pass%== UserStudentId goto FAIL When I run the .bat file it will ask Enter student id: in command prompt, then validate the student id and do some process. I want to pass this input from java or C#.net IDE to .bat file and continue the process. In here User will never deal with command prompt. If there is any output from .bat , it will show in java or .net IDE also. I wonder if it is possible since I'm new to this. TX. A: When you start a process from Java or C# you can get console input and output of that process as streams. You then can simply write into the process' input stream. It might be, though, that the batch file won't actually like that since cmd might look for actual interactive input with set /p (e.g., it fails with file redirection, if I remember correctly). A better method, if you control the batch file itself, would be the following: if defined pass goto SkipInput set /p pass=Enter student ID: :SkipInput which will use an environment variable if present and only ask the user if it isn't already set. This is much more automation-friendly, since you can just set the environment variable in the calling process and have it inherited for every process you spawn. And no hassle with emulating input as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set color mTitles Array in that API demo? http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List6.html In the above link , how toset color to mTitles string. A: You should be able to do something like in the getview function TextView title = (TextView)sv.getChildAt(0); title.setBackgroundColor(Coor.RED);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paint app for ipad [opengl-es] line strokes not proper I have a strange problem with openGL. I am working on paint app for both iphone and ipad. I am using opengl-es for my app. In my app I am filling colors in outline images, drawings a line onscreen based on where the user touches. I just use the "touchesMoved" function to draw a line between two points. Since I would like lines to stay on screen, in my renderLineFromPoint function, but for some reason some of the points of the line just drop out, and it appears completely random. However ipad simulator and iphone device/simulator gives desired output. Line stroke appears as shown in figure. I am creating buffer using following code: - (BOOL)createFramebuffer{ // Generate IDs for a framebuffer object and a color renderbuffer glGenFramebuffersOES(1, &viewFramebuffer); glGenRenderbuffersOES(1, &viewRenderbuffer); glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); // This call associates the storage for the current render buffer with the EAGLDrawable (our CAEAGLLayer) // allowing us to draw into a buffer that will later be rendered to screen wherever the layer is (which corresponds with our view). [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDrawable>)self.layer]; glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight); NSLog(@"Backing Width:%i and Height: %i", backingWidth, backingHeight); // For this sample, we also need a depth buffer, so we'll create and attach one via another renderbuffer. glGenRenderbuffersOES(1, &depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer); if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) { NSLog(@"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES)); return NO; } return YES; } I am using following code snippet for renderLineFromPoint - (void) renderLineFromPoint:(CGPoint)start toPoint:(CGPoint)end{ static GLfloat* vertexBuffer = NULL; static NSUInteger vertexMax = 64; NSUInteger vertexCount = 0, count, i; [EAGLContext setCurrentContext:context]; glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); // Convert locations from Points to Pixels //CGFloat scale = self.contentScaleFactor; CGFloat scale; if ([self respondsToSelector: @selector(contentScaleFactor)]) { scale=self.contentScaleFactor; } else{ //scale = 1.000000; if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] == YES && [[UIScreen mainScreen] scale] == 2.00) { // RETINA DISPLAY scale = 2.000000; } else { scale = 1.000000; } } NSLog(@"start point %@", NSStringFromCGPoint(start)); NSLog(@"End Point %@", NSStringFromCGPoint(end)); start.x *= scale; start.y *= scale; end.x *= scale; end.y *= scale; // Allocate vertex array buffer if(vertexBuffer == NULL) // vertexBuffer = malloc(vertexMax * 2 * sizeof(GLfloat)); vertexBuffer = malloc(vertexMax * 2 * sizeof(GLfloat)); // Add points to the buffer so there are drawing points every X pixels count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1); NSLog(@"count %d",count); for(i = 0; i < count; ++i) { if(vertexCount == vertexMax) { vertexMax = 2 * vertexMax; vertexBuffer = realloc(vertexBuffer, vertexMax * 2 * sizeof(GLfloat)); NSLog(@"if loop"); } vertexBuffer[2 * vertexCount + 0] = start.x + (end.x - start.x) * ((GLfloat)i / (GLfloat)count); vertexBuffer[2 * vertexCount + 1] = start.y + (end.y - start.y) * ((GLfloat)i / (GLfloat)count); vertexCount += 1; } NSLog(@"Scale vertex %f",scale); //NSLog(@"%i",vertexCount); // Render the vertex array glVertexPointer(2, GL_FLOAT, 0, vertexBuffer); glDrawArrays(GL_POINTS, 0, vertexCount); // Display the buffer glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; } touchbegan function code: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ CGRect bounds = [self bounds]; UITouch* touch = [[event touchesForView:self] anyObject]; firstTouch = YES; // Convert touch point from UIView referential to OpenGL one (upside-down flip) location = [touch locationInView:self]; location.y = bounds.size.height - location.y; } touchmoved function code: - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ CGRect bounds = [self bounds]; UITouch* touch = [[event touchesForView:self] anyObject]; // Convert touch point from UIView referential to OpenGL one (upside-down flip) if (firstTouch) { firstTouch = NO; previousLocation = [touch previousLocationInView:self]; previousLocation.y = bounds.size.height - previousLocation.y; } else { location = [touch locationInView:self]; location.y = bounds.size.height - location.y; previousLocation = [touch previousLocationInView:self]; previousLocation.y = bounds.size.height - previousLocation.y; } // Render the stroke [self renderLineFromPoint:previousLocation toPoint:location]; } A: I had a similar issue with missing points and it was related to the drawableProprties of my CAEAGLLayer. Within CAEAGLLayer's drawableProperties, do you have the kEAGLDrawablePropertyRetainedBacking set to YES? If not then the Backing of your drawing is not being retained from frame to frame which can cause missing points and flickering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why this for loop goes in infinite loop executation? see i have one code like this int main () { uint32_t i ; for(i=4;i>=0;i--) printf("i is %d \n",i); return 0; } it goes in infinite loop. why i's value goes below 0 & still loop is going to executive? A: You see negatives values in your printf because you print it as %d, but in the condition, the uint32_t is always positive (you are doing an overflow). A: uint32_t means unsigned integer and so its value is always >= 0 - thus your loop executes infinitely. Note that many compilers will issue a warning indicating that i>=0 comparison is always true. A: You are using uint32_t means unsigned and then checking the condition in for loop that i >= 0 so when the loop executes for value i = 0 and then it makes the i = -1 but i is unsigned so it will make the value of i INT_MAX(what ever your system supports). so and still the value is greater than 0 so condition is true. And the answer for how it prints the negative values for i is that, you are using the '%d' that is for signed. If you want to see the result you can use the '%u' option so it will print the original unsigned value of i. If you want the result that you want from the program then try to cast the uint to int at the time of condition checking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get the hit row in MongoDb Let us say we have the next JSON structure: { { name:"FirstComponent", items:[ { Caption:"Item1", Value:"1" }, { Caption:"Item2", Value:"3" }, { Caption:"Item3", Value:"2" } ] } } Let us say we query for the item with value "2". {"items.Value":"2"} and we would get the whole document back. What I want to have is an index of subdocument it hit on, it would be nice from my scenario. Is there a way to get some indication on which is the first document which hit the search? A: No, that wouldn't make sense: where would it store the index in the document it returns to you? You need to just scan the array again in C# to find the index if you really need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does using a regex and .scan produce these results? >> "aaaaaafbfbfsjjseew".scan(/(.)/) => [["a"], ["a"], ["a"], ["a"], ["a"], ["a"], ["f"], ["b"], ["f"], ["b"], ["f"], ["s"], ["j"], ["j"], ["s"], ["e"], ["e"], ["w"]] >> "aaaaaafbfbfsjjseew".scan(/((.))/) => [["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["f", "f"], ["b", "b"], ["f", "f"], ["b", "b"], ["f", "f"], ["s", "s"], ["j", "j"], ["j", "j"], ["s", "s"], ["e", "e"], ["e", "e"], ["w", "w"]] >> "aaaaaafbfbfsjjseew".scan(/((.)\2*)/) => [["aaaaaa", "a"], ["f", "f"], ["b", "b"], ["f", "f"], ["b", "b"], ["f", "f"], ["s", "s"], ["jj", "j"], ["s", "s"], ["ee", "e"], ["w", "w"]] >> "aaaaaafbfbfsjjseew".scan(/((.)\1*)/) => [["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["f", "f"], ["b", "b"], ["f", "f"], ["b", "b"], ["f", "f"], ["s", "s"], ["j", "j"], ["j", "j"], ["s", "s"], ["e", "e"], ["e", "e"], ["w", "w"]] >> "aaaaaafbfbfsjjseew".scan(/((.)\3*)/) => [["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["a", "a"], ["f", "f"], ["b", "b"], ["f", "f"], ["b", "b"], ["f", "f"], ["s", "s"], ["j", "j"], ["j", "j"], ["s", "s"], ["e", "e"], ["e", "e"], ["w", "w"]] A: From the fine manual: str.scan(pattern) → array [...] If the pattern contains groups, each individual result is itself an array containing one entry per group. This one: "aaaaaafbfbfsjjseew".scan(/(.)/) has a group so you get an array of arrays: each individual result is a single element array. The next one: "aaaaaafbfbfsjjseew".scan(/((.))/) has two groups which happen to have the same value so you get two identical elements in your individual result arrays. The third one: "aaaaaafbfbfsjjseew".scan(/((.)\2*)/) again contains two groups but also contains a back-reference to the inner group so the outer group (AKA the first group) gobbles up duplicates and you get ["aaaaaa", "a"], ["jj", "j"], and ["ee", "e"]. The fourth one: "aaaaaafbfbfsjjseew".scan(/((.)\1*)/) just tries to switch the back-reference to the outer group but \1 isn't defined inside group 1 so it is equivalent to /((.))/. The fifth one: "aaaaaafbfbfsjjseew".scan(/((.)\3*)/) tries to refer to a non-existant group (group 3 when there are only two groups) so it behaves the same as /((.))/. A: "aaaaaafbfbfsjjseew".scan(/(.)/) means the string can be splitted into individual array of strings. Here parenthesis tells that it's an array, and the .-symbol in parenthesis represents number of characters in that individual string of array. If we write for suppose "hellovenkat".scan(/(...)/) , this results [["hel"],["lov"],["enk"]]. It doesn't give the last index, because it can not contain three characters. If we give "hello venkat".scan(/(...)/), this results as following. Ans: [["hel"], ["lo "], ["ven"], ["kat"]].
{ "language": "en", "url": "https://stackoverflow.com/questions/7551538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Generate Sql DB Script in C# I have a sql table that contains Table Columns Properties like TableName, ColumnName, Datatype, IsPrimary, IsNullable, DefaultValue, Length etc and also a versionId. So my requirement is comparing two versionIds and then generating scripts in C# like alter table. Please tell me how to do this programatically. Thanks in Advance A: it is not a simple task by any stretch, the simplest way is to generate scripts for both versions and then do a diff like check - but there is SO much in SQL that can occur that it will require a lot of custom logic to be built. Visual Studio does include Schema Compare which is what you want to build, maybe you can integrate that into your stuff. A: If SQL Server, you could shell out using Process.Start() and run the tablediff Utility
{ "language": "en", "url": "https://stackoverflow.com/questions/7551545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Getting friendly device names in python I have an 2-port signal relay connected to my computer via a USB serial interface. Using the pyserial module I can control these relays with ease. However, this is based on the assumption that I know beforehand which COM-port (or /dev-node) the device is assigned to. For the project I'm doing that's not enough since I don't want to assume that the device always gets assigned to for example COM7 in Windows. I need to be able to identify the device programatically across the possible platforms (Win, Linux, OSX (which I imagine would be similar to the Linux approach)), using python. Perhaps by, as the title suggests, enumerate USB-devices on the system and somehow get more friendly names for them. Windows and Linux being the most important platforms to support. Any help would be greatly appreciated! EDIT: Seems like the pyudev-module would be a good fit for Linux-systems. Has anyone had any experience with that? A: Regarding Linux, if all you need is to enumerate devices, you can even skip pyudev dependency for your project, and simply parse the output of /sbin/udevadm info --export-db command (does not require root privileges). It will dump all information about present devices and classes, including USB product IDs for USB devices, which should be more then enough to identify your USB-to-serial adapters. Of course, you can also do this with pyudev. A: I know this is an older post, but I was struggling with it today. Ultimately I used the wmi library for python as I'm on a Windows machine (sorry, I know my answer only applies to Windows, but maybe it'll help someone). Install the package using pip first: pip install wmi then import wmi c = wmi.WMI() wql = "Select * From Win32_USBControllerDevice" for item in c.query(wql): print item.Dependent.Caption Should result with something like: USB Root Hub USB Root Hub Prolific USB-to-Serial Comm Port (COM9) USB Root Hub USB Root Hub USB Composite Device USB Video Device USB Audio Device USB Root Hub ...snip... In this case, you'd have to string parse the Caption to find the COM port. You can also take a look at just the item. Dependent object to see other attributes of the USB device beside Caption that you may find relevant: instance of Win32_PnPEntity { Caption = "USB Root Hub"; ClassGuid = "{36fc9e60-c465-11cf-8056-444553540000}"; ConfigManagerErrorCode = 0; ConfigManagerUserConfig = FALSE; CreationClassName = "Win32_PnPEntity"; Description = "USB Root Hub"; DeviceID = "USB\\ROOT_HUB\\4&32F13EF0&1"; HardwareID = {"USB\\ROOT_HUB&VID8086&PID3A36&REV0000", "USB\\ROOT_HUB&VID8086&PID3A36", "USB\\ROOT_HUB"}; Manufacturer = "(Standard USB Host Controller)"; Name = "USB Root Hub"; PNPDeviceID = "USB\\ROOT_HUB\\4&32F13EF0&1"; Service = "usbhub"; Status = "OK"; SystemCreationClassName = "Win32_ComputerSystem"; SystemName = "001fbc0934d1"; }; A: At least for linux, you can use some dummy hacks to determine your /dev node, by inspecting for example the output of "ls /dev | grep ttyUSB" before and after you attach your device. This somehow must apply as well for the OSX case. A good idea is to inspect those commands using something like the subprocess.Popen() command. As for windows, this might be helpful. A: Windows: you can pull USB information from WMI, but you need to be administrator. The examples are in .NET, but you should be able to use the Python WMI module. This will give you access to USB identification strings, which may contain useful information. For FTDI serial devices there is a short cut using FTDI's DLL, which does not require privileged access. Linux: all the available information is under /sys/bus/usb, and also available through udev. This looks like a good answer. A: As far as Windows goes, you could scan the registry: import _winreg as reg from itertools import count key = reg.OpenKey(reg.HKEY_LOCAL_MACHINE, 'HARDWARE\\DEVICEMAP\\SERIALCOMM') try: for i in count(): device, port = reg.EnumValue(key, i)[:2] print device, port except WindowsError: pass A: It will be great if this is possible, but in my experience with commercial equipments using COM ports this is not the case. Most of the times you need to set manually in the software the COM port. This is a mess, specially in windows (at least XP) that tends to change the number of the com ports in certain cases. In some equipment there is an autodiscovery feature in the software that sends a small message to every COM port and waits for the right answer. This of course only works if the instrument implements some kind of identification command. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: HLOOKUP over several columns returns nothing else then N/A I am very familiar with VLOOKUP in excel, but HLOOKUP seems not as easy to master as its vertical pendant. Here is a very simple case I can' solve by myself: http://dl.dropbox.com/u/3224566/Book1.xlsx I don't understand what is wrong with that kind of formula use, but I would really need to expend that one to a series of rows (thus I can' transpose that set of data to workaround my issue with VLOOKUP!) Thanks in advance for your help and best regards A: You need to be doing a HLOOKUP on the top row (just as VLOOKUP looks to match the leftmost column) - whereas you are attempting to lookup row 3 using an two stage INDEX and MATCH operation, the MATCH to find your value in row 3, the INDEX to return the cell in row 1 two cells above your MATCH is a superior option =IF(ISNA(MATCH(B3,C3:AW3,0)),"no match",INDEX(C1:AW1,MATCH(B3,C3:AW3,0))) Some further reading courtesy of google searches http://exceluser.com/blog/420/excel%E2%80%99s-vlookup-vs-index-match-functions.html http://www.decisionmodels.com/optspeede.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7551549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem in screen resolution I have created an app.During creation i have used Nexus s device for testing of my app.But i want my app to support multiple screen.So for that have created separate layout for small device, medium device and so on as suggested in android support multiple screen documentation.Now my problem arise in maintaining layout for Nexus s device having resolution of 480 x 800 pixels and Samsung galaxy ace having resolution of 320 x 480 pixels (ie HVGA devices) because both these device uses same layout folder not like other small/medium device which take its layout from layout-small/layout-medium directory.So its very difficult for me to manage the layout for nexus s device and Samsung galaxy ace device/HVGA devices,because if i manage layout for nexus s devices than its not fit in HVGA devices, similarly if i maintain layout for HVGA device than its not match for nexus s devices.So how can i create separate layout for these two range of devices,because in the documentation it is given that for devices having resolution of 320x480 mdpi, 480x800 hdpi, etc would used the same layout.So please help me to solve this out. A: If you use dp/dip (density independent pixel) units in your layout instead of px, everything should be fine. A: Did you use fix size for the width and height in your xml? I think if you want to support different screen resolution, you have to use the standard android code for layout width and height. And be sure to use draw9patch in your images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Mousemove and performance question I've just wrote some code (and it works) for displaying some text near the mouse when the mouse is on any of 4 rectangles (different text for different rectangle). I used html tag < map >< /map>, css and jquery. Everything works fine. I don't like 100% CPU Usage when mouse is moving on the picture. This is a jquery part: $('area').each(function(){ var area = $(this), alt = area.attr('alt'); area.mousemove(function(event){ var tPosX = event.pageX +10; var tPosY = event.pageY - 85; $('#rectangletext').css({top: tPosY, left: tPosX}); $('#rectangletext').html(alt); }).mouseleave(function(){ $('#rectangletext').html(''); }); }); I've tested it in IE, FF, Chrome and Opera (at the same time, on the same computer). Area.mousemove eats up to 100% CPU when you move your mouse on that . The question is: how to reduce resources that are needed when you move your mouse on that map? IE is the worst - CPU Usage jumps up to 100%. FF eats about 67%-100%. Opera eats less than 62% (never more than 62%). Chrome is the best: average is about 28%, maximum is 42%. It's OK to reposition text to be near the mouse not every millisecond, but every 300 milliseconds, if it helps to reduce the resources that are required. How to do that? Any better solution for this problem than to use mouseenter instead of mousemove? The cons of mouseenter is it doesn't update the position of the popup text until mouseleave is called. Thank you. A: You can keep track of the time your mouse last moved. var prevDate; // keep this as a global variable // put the following inside the mousemove function var date = new Date().getTime(); if(date - prevDate > 300){ // your code goes here prevDate = date; } A: You could start an interval on mouseenter and update the position in there. Play around with the interval time to find a good frequency. Also storing the jquery objects in a variable could help a bit, but not much since you're accessing them via ID which is pretty fast. A: Setting the html is pretty expensive, and you only really need to do it on mouseenter. Moving your selectors outside of the loop will also give you a nice speedup. var $rectText = $("#rectangletext"); $('area').each(function(){ var area = $(this), alt = area.attr('alt'); area.mousemove(function(event){ var tPosX = event.pageX +10; var tPosY = event.pageY - 85; $rectText.css({top: tPosY, left: tPosX}); }).mouseenter(function(){ $rectText.html(alt); }).mouseleave(function(){ $rectText.html(''); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7551559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: calculate median excel having conditions I'm looking for a excel formula which will help me calculate the medians of different data. 1 45 2 54 3 26 4 12 1 34 2 23 3 9 Now, I need to calculate the median of data from B1:B4 and then B5:B8, and print whether the number is lesser/equal/greater than the median.. I've come up with preliminary formula =IF(MEDIAN($B$1:$B$4)<B1;"g";IF(MEDIAN($B$1:$B$4)=B1;"e";"l")) But, this won't help for calculating the median for different sets. What should i do? Thanks for the help! A: To check if B1 is greater, less than, or equal the median of both the medians of B1:B4 and B5:B8 (in this case would be 29.25), then you could use something like this: =IF(B1>(MEDIAN(MEDIAN(B1:B4),MEDIAN(B5:B7))),"g",IF(B1=(MEDIAN(MEDIAN(B1:B4),MEDIAN(B5:B7))),"e","l")) If you just want to check against B1:B4 (as in your example) you can use: =IF(B1>MEDIAN(B1:B4),"g",IF(B1=MEDIAN(B1:B4),"e","l")) UPDATE: According to your comment below, here is what you can write in C1 and drag down to C4: =IF(B1>MEDIAN($B$1:$B$4),B1&">"&MEDIAN($B$1:$B$4),IF(B1=MEDIAN($B$1:$B$4),B1&"="&MEDIAN($B$1:$B$4),B1&"<"&MEDIAN($B$1:$B$4))) A: You have three problems here: * *your 1st column is a sequence rather than a group identifier *there is no =MEDIANIF() *Pivot tables don't support Medians either not a good starting point .... ad #1, you could change your 1,2,3,4,1,2,3, ... towards 1,1,1,1, 2,2,2, ... to indicate what belongs together ad #2, #3 ... I would suggest to define a function =MEDIANIF() in VBA; example: Function MedianIf(R As Range, Cr As Variant) As Variant Dim Idx As Integer, Jdx As Integer, A() As Variant, CCnt As Integer, Tmp As Variant ' find array size CCnt = 0 For Idx = 1 To R.Rows.Count If R(Idx, 1) = Cr Then CCnt = CCnt + 1 Next Idx 'dim array ReDim A(CCnt - 1) ' load from range into array CCnt = 0 For Idx = 1 To R.Rows.Count If R(Idx, 1) = Cr Then A(CCnt) = R(Idx, 2) CCnt = CCnt + 1 End If Next Idx ' bubble sort For Jdx = CCnt - 1 To 0 Step -1 For Idx = 0 To Jdx - 1 If A(Idx) > A(Idx + 1) Then Tmp = A(Idx) A(Idx) = A(Idx + 1) A(Idx + 1) = Tmp End If Next Idx Next Jdx ' get Median If CCnt Mod 2 = 1 Then MedianIf = A(Int(CCnt / 2)) Else MedianIf = (A(CCnt / 2 - 1) + A(CCnt / 2)) / 2 End If End Function Use this function by selecting a range 2 col's wide and x rows down, like =MedianIF($A$1:$B$7,A1) and there we go ... now you can use the new function in your =IF(.... , "g", ...) so one single formula for all the range .... attention: bubble sort is not very economic for large ranges
{ "language": "en", "url": "https://stackoverflow.com/questions/7551562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide the .jsp url extension in struts2 project I am working in the struts2 web application.I want to do the mapping of my url such that the extensions like ".jsp" should be eliminated from the url. So below is the snippet code of my web.xml.I want to do that my url show /login instead of /login.jsp. <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>URLFilter</filter-name> <filter-class>example.MyFilter</filter-class> <init-param> <param-name>onError</param-name> <param-value>/login.jsp</param-value> </init-param> </filter> <filter-mapping> <filter-name>URLFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> A: Just access all your JSPs through Actions (and put them somewhere below WEB-INF to enforce this policy). It's easy to do with the "default action" of Struts2: <action name="login"> <result>/WEB-INF/pages/login.jsp</result> </action> I don't know how well this integrates with ServletFilter, maybe you'll have to turn the one mentioned in your web.xml into a Struts2 Interceptor. A: You can change url extension using property file as shown in below link : http://www.aoiblog.com/change-url-extension-in-struts2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7551566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: disable cookies in Tomcat5 In /conf/context.xml I add: <Context cookies="false"> Idea being to enable url rewrite, disabling cookies (a security patch for a client's server at work). I personally am not sure how this will make it more secure, feel free to throw in your expertise on the matter, but either way, I gotta do it & make it work. When I do disable cookies and open the web application from its context, the browser gets stuck in a constant refresh loop. The tweak has to be made on the tomcat level (no Apache/mod_rewrite, although fronted/bound to an Apache server) & generally, in a few words, I have to disable session cookies, which would, supposedly, automatically enable URL rewrite instead... I can't find any relevant/useful information out there, or any postings/questions/cries-for-help that describe this or effectively similar problem. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7551569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Report Viewer on asp.net page keeps asking for authentication Report Viewer on asp.net page keeps asking for authentication i have report viewer control on asp.net page, on my machine (IIS 7.5, windows 7) its working fine, but when i deployed it to another machine (IIS 7.5, Windows 7), every time i open the report viewer page, i keep getting a dialog to enter my credentials (username, password), and even if i enter the correct credentials, i get a blank page. i tried impersonate windows credentials, but i did not work. can anyone help me on this please?? A: ok i solved it, it was because the /Reports is reserved, i just changed the URL of that page
{ "language": "en", "url": "https://stackoverflow.com/questions/7551571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monkey Runner import giving error i created an empty file an named it something.py, and then i just copied the lines of code from the android developer website. However, if i try to run it, i get an ImportError: No module named com.android.monkeyrunner Is there something i am missing? There doesn't seem to be anything at the android developer website that addresses this issue. Here are the lines of code from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice device = MonkeyRunner.waitForConnection() device.installPackage('myproject/bin/Stamp_Client.apk') package = 'com.example.main' activity = 'com.example.Stamp_Client' runComponent = package + '/' + activity device.startActivity(component=runComponent) device.press('KEYCODE_BUTTON_SELECT','DOWN_AND_UP') device.press('KEYCODE_U','DOWN_AND_UP') device.press('KEYCODE_S','DOWN_AND_UP') device.press('KEYCODE_E','DOWN_AND_UP') device.press('KEYCODE_R','DOWN_AND_UP') device.press('KEYCODE_ENTER','DOWN_AND_UP') device.press('KEYCODE_P','DOWN_AND_UP') device.press('KEYCODE_A','DOWN_AND_UP') device.press('KEYCODE_S','DOWN_AND_UP') device.press('KEYCODE_S','DOWN_AND_UP') device.press('KEYCODE_ENTER','DOWN_AND_UP') device.press('KEYCODE_ENTER','DOWN_AND_UP') A: Make sure you run: $ monkeyrunner yourfile.py instead of: $ python yourfile.py A: I guess you are missing the shebang: #! /usr/bin/env monkeyrunner that is if you are using Linux or OSX, for Windows you probably have to create a batch file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Map reduce value list order problem As we know Hadoop groups values with per key and sends them to same reduce task. Suppose I have next lines in file on hdfs. line1 line2 line3 .... linen In map task I print filename and line. In reduce I receive in different orders.for examle key=> { line3, line1, line2,....} Now, I have the next problem. I want to get this value list in order that they lie in file, as key =>{ line1, line2,...linen} Is there any way of doing this ? A: If you are using TextInputFormat, you get a <LongWritable, Text> as mapper input. The LongWritable part (or the key) is the position of the line in the file (Not line number, but position from start of file I think). You can use that part to keep track of which line was first. For example, the mapper can output <Filename, TextPair(Position, Line)> as output instead of <Filename, Line> as you are doing now. Then you can sort the keys that the reducer gets based on the first part of the Pair (the Position) and you should get back the lines in the same order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any Listener for Media Recorder? Actually i am creating an application which starts recording when user start speaking and stop recording automatically when user stop speaking. so is there any way to find if user is speaking or not? is there any listener for Media Recorder for this? A: No, AFAIK there are no listeners or intents that would notify your app that sound level has gone above some threshold (e.g. user started talking). You could use AudioRecord class to record the microphone audio and then analyze it to see the volume. However this would require your app to run at that time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: create timer using list value and assign those timer to execute query in C# I have a list and i want to use this list value to create timer.And also want to use those timer to execute 2 MySql query. Here is my code, Timer timer; List<uint> _dataValues = new List<uint>(); private void button1_Click(object sender, EventArgs e) { string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;"; MySqlConnection mycon = new MySqlConnection(myconstring); string sql = "SELECT flag FROM sms_data_bankasia group by flag"; MySqlCommand comd = mycon.CreateCommand(); comd.CommandText = sql; mycon.Open(); MySqlDataReader dtr = comd.ExecuteReader(); count = 0; while (dtr.Read()) { _dataValues.Add(dtr.GetUInt32(0)); } dtr.Close(); } void PrepareTimers(List<uint> dataValues) { foreach (uint dataValue in _dataValues) { timer = new Timer(TimerAction, dataValue, 1000, 0); } } void TimerAction(object flag) { string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;"; MySqlConnection mycon = new MySqlConnection(myconstring); MySqlCommand cmd = new MySqlCommand("SELECT * FROM sms_data_bankasia WHERE flag = @flag", mycon); MySqlParameter param = new MySqlParameter(); param.ParameterName = "@flag"; param.Value = flag; cmd.Parameters.Add(param); } In PrepareTimers section provide error.I also want to add another query in "TimerAction".So what to do ?Any one can help me?I am using VS 2005.net and C# language. A: Since your error syas that No overload for method 'Timer' takes '4' arguments, I'm guessing that you are using System.Timers.Timer class, for which there is no constructor which takes 4 arguments. As per your code, you need to use: System.Threading.Timer Edit(as per the comment): In order to overcome from this naming conflict, either you can create an alias for the nemespace like using ThreadingTimer = System.Threading.Timer; and use ThreadingTimer or use fully qualified name like: System.Threading.Timer = new System.Threading.Timer(TimerAction, dataValue, 1000, 0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7551580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to using DOM importNode without DOMException I want to copy an node to a different Documentg, but it always has DOMException about org.apache.harmony.xml.dom.NodeImpl.setNameNS(NodeImpl.java:227) here is my code private String getString(Node seqNode) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement("Test"); doc.appendChild(root); /* following line will cause DOMException */ doc.importNode(seqNode, true); ... ... } catch (Exception e) { } } where seqNode belongs to other Document does any body has idea about this issue? :-) A: I ran into this problem too. I was getting this exception when calling either importNode() or cloneNode(). And BTW, the XML I was parsing/generating was not using namespaces. It seems that the DOM parser (from Apache Harmony) that is included in Android is buggy. See this link: Issue 2735: Harmony DOM implementation is buggy and noncompliant. Everything works fine if the same code is executed using plain Java 1.6 (which isn't based on Harmony of course). I tried setting setNamespaceAware(true) on the DocumentBuilder, but this did not help. Eventually, I gave up and worked around the issue by using adoptNode() rather than importNode(). This is kind of incestuous, because it is stealing a node from one Document tree and putting it into another. But in my case, the first Document tree was only temporary, so I could do things this way. A: I'm guessing, but it seems that you are trying to import node with namespace defined, where your target document does not have this namespace declared. So, what namespaces are declared in source document? Did you declare any namespaces in target document? A: The input is a smil String shown below: <smil> <head> <layout> <root-layout height="720" width="1280"/> <transition id="fade" type="fade" subtype="crossfade" dur="1s"/> <region id="_33_32_bkgd_image" left="0" top="0" width="1280" height="720" background-color="#c12121" showBackground="whenActive" z-index="0"></region> <region id="_33_32_I001" left="380" top="27" width="405" height="352" z-index="1"></region><region id="_33_32_I002" left="0" top="365" width="354" height="354" z-index="2"></region> </layout> </head> <body> <seq begin="wallclock(2011-09-22T01:52:00)" end="wallclock(2011-09-23T00:00:00)"> <par dur="10s" xml:id="32" repeatCount="1"> <brush color="#c12121" region="_33_32_bkgd_image"></brush> <seq repeatCount="indefinite"> <img xml:id="30" region="_33_32_I001" src="http://127.0.0.1/Service/User/2_user/Media/Image/30_image.jpg?JFBukihsTu" dur="5s" fit="meet" regPoint="center" regAlign="center"> <metadata xml:id="meta-rdf"> <meta name="MD5" content="7c8b59b28ea2247f20bc538dcb7108f3"></meta><meta name="width" content="531"></meta><meta name="height" content="720"></meta></metadata></img> <img xml:id="27" region="_33_32_I001" src="http://127.0.0.1/Service/User/2_user/Media/Image/27_image.jpg?jTqCMuIxsX" dur="5s" fit="meet" regPoint="center" regAlign="center"> <metadata xml:id="meta-rdf"> <meta name="MD5" content="db51409f243f79c566811d1b307a77a1"></meta><meta name="width" content="427"></meta><meta name="height" content="602"></meta></metadata></img> </seq> </par> </seq> </body> </smil> and the original Document is generated by: DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = builder.parse(new ByteArrayInputStream(smil.getBytes())); and the seqNode represents the "seq" node (the child of body tag) I want to copy "seq" and all of it's childs to new Document
{ "language": "en", "url": "https://stackoverflow.com/questions/7551582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Usercontrol action event with TextBox I am new to asp.net, My problem is I have one TextBox and user control Button in default.aspx ,After clicking the Button I need change the text value of TextBox(some default value from user control). Is that possible?If Yes,where i need to write the code? Default.aspx <%@ Register Src="Text.ascx" TagName="Edit" TagPrefix="uc1" %> <asp:TextBox ID="TextBox1" runat="server" Width="262px"></asp:TextBox> <uc1:Edit Id="Edit2" runat="server" /></td> Usercontrol - button <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Text.ascx.cs" Inherits="WebApplication4.WebUserControl1" %> <asp:Button ID="Button1" runat="server" Text="Edit " OnClientClick="return confirm('Are you certain you want to Navigate?');" Width="341px" onclick="Button1_Click" /> how to group or ,fire that(text box value change) from usercontrol ? A: Starting from your user control: <asp:Button ID="Button1" runat="server" Text="Edit " OnClientClick="return confirm('Are you certain you want to Navigate?');" Width="341px" onclick="Button1_Click"/> In the code behind use this to create a custom event which fires on the button'c click using System; using System.Web.UI; namespace TestApplication { public partial class Edit : UserControl { public string DefaultValue { get; set; } protected void Page_Load(object sender, EventArgs e) { } private static object EditClickKey = new object(); public delegate void EditEventHandler(object sender, EditEventArgs e); public event EditEventHandler EditClick { add { Events.AddHandler(EditClickKey, value); } remove { Events.RemoveHandler(EditClickKey, value); } } protected void Button1_Click(object sender, EventArgs e) { OnEditClick(new EditEventArgs(DefaultValue)); } protected virtual void OnEditClick(EditEventArgs e) { var handler = (EditEventHandler)Events[EditClickKey]; if (handler != null) handler(this, e); } public class EditEventArgs : EventArgs { private string data; private EditEventArgs() { } public EditEventArgs(string data) { this.data = data; } public string Data { get { return data; } } } } } The "Default.aspx" page will contain the Event Handler for your new Custom Event. markup: <asp:TextBox ID="TextBox1" runat="server" Width="262px"></asp:TextBox> <uc1:Edit ID="Edit1" runat="server" OnEditClick="EditClick_OnEditClick" DefaultValue="default" /> Code Behind: protected void EditClick_OnEditClick(object sender, TestApplication.Edit.EditEventArgs e) { TextBox1.Text = e.Data; } A: In the Button1_Click event of Button1 you can get the reference to TextBox using Page.FindControl() method, like this: protected void Button1_Click(...) { TextBox txtBox = (TextBox)this.Page.FindControl("TextBox1"); if(txtBox != null) txtBox.Text = "Set some text value"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java : get values from table and apply formula in the bellow code, I try to calcul the formula: y=val1+val2+val4/all values val is a string get from a table. my aim is , for a row 0, get all values from each column "values" then calcul the formule. after that do the same for each row. but my code doesn't print me the expected behaviour for the first step. thanks, > String[] values = { x1,x2,x3,x4}; > > String val = null ; > for (int i = 0; i < values .length; i++) > { > val = table.getValue(0, table.getColumnValue(x[i])); > > } > > //my fomula y = value[x[0]]+value[x[1]]+value[x[3]]/values[0..3] > > int Num = Integer.parseInt(value[x[0]])+Integer.parseInt(value[x[1]])+Integer.parseInt(value[x[3]]); > int Denum = Integer.parseInt(val ); > > y=Num/Denum ; A: are you sure that variable value shouldn't be values in this code? A: "1" + "2" = "12" //string 1 + 2 = 3 //int You cannot add String, have to convert them to number first: int[] valuesInt = new int[values.length]; for (int i = 0; i < values .length; i++) { valuesInt[i] = Integer.parseInt(values[i]); } Then add the numbers: int Num = valuesInt[0]+valuesInt[1]+valuesInt[3]; int Denum = valuesInt[0]+valuesInt[1]+valuesInt[2]+valuesInt[3]; Calcaulate Denum in the loop: int Denum = 0; for (int i = 0; i < values .length; i++) { Denum += Integer.parseInt(values[i]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7551584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a row to a table using sqlite browser in android I was able to delete rows in the table i have created by simply clicking on the button "Delete Record". But when i am trying to add a row by clicking on the button "New Record", it displayed an error like this so, in the preferences i have set the default value to empty string. Still it is not working and is displaying the same error. Is it possible to add like this or not? And when i create a new table, there is no problem in creating a new record. But how to add data into that row? please help me. Thank you A: According to this bug report: http://sourceforge.net/tracker/?func=detail&aid=2936194&group_id=87946&atid=584909 ...this appears to be caused by a bug in the app which still isn't fixed (see comments on issue). The last comment states they were successful in changing their preferences by creating a few registry keys where the app looks for its settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Images from camera buffer iOS. Capture still image using AVFoundation I'm using this well known sample code from Apple to convert camera buffer still images into UIImages. -(UIImage*) getUIImageFromBuffer:(CMSampleBufferRef) imageSampleBuffer{ // Get a CMSampleBuffer's Core Video image buffer for the media data CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageSampleBuffer); if (imageBuffer==NULL) { NSLog(@"No buffer"); } // Lock the base address of the pixel buffer if((CVPixelBufferLockBaseAddress(imageBuffer, 0))==kCVReturnSuccess){ NSLog(@"Buffer locked successfully"); } void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); // Get the number of bytes per row for the pixel buffer size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); NSLog(@"bytes per row %zu",bytesPerRow ); // Get the pixel buffer width and height size_t width = CVPixelBufferGetWidth(imageBuffer); NSLog(@"width %zu",width); size_t height = CVPixelBufferGetHeight(imageBuffer); NSLog(@"height %zu",height); // Create a device-dependent RGB color space CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // Create a bitmap graphics context with the sample buffer data CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); // Create a Quartz image from the pixel data in the bitmap graphics context CGImageRef quartzImage = CGBitmapContextCreateImage(context); // Free up the context and color space CGContextRelease(context); CGColorSpaceRelease(colorSpace); // Create an image object from the Quartz image UIImage *image= [UIImage imageWithCGImage:quartzImage scale:SCALE_IMAGE_RATIO orientation:UIImageOrientationRight]; // Release the Quartz image CGImageRelease(quartzImage); // Unlock the pixel buffer CVPixelBufferUnlockBaseAddress(imageBuffer,0); return (image );} The problem is that usually the image that you obtain is 90° rotated. Using the method +imageWithCGImage:scale:orientation I'm able to rotate it, but before getting into this method I was trying to rotate and scale the image using the CTM function, before passing it to a UIImage. the problem was that CTM transformation didn't affect the image. I'm asking myself why... is that because I'm locking the buffer? or because the context is created with the image inside, so the changes will affect only the further mod? Thank you A: The answer is that it affects only further modifications, and it has nothing to deal with the buffer locking. As you can read from this answer mod to the context are applied by time Vertical flip of CGContext
{ "language": "en", "url": "https://stackoverflow.com/questions/7551587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: checking existance of the list element via c# functions I have a list like: List<int> baslikIndexes = new List<int> { }; and I added the elements manually. I want to know whether for example if element "23" is in it or not. I am trying to use "Exists" method but I haven't figured out how to use it. I tried this and it gives error: baslikIndexes.Exists(Predicate<int>(23)); // I try to check whether 23 is in the list or not Thanks for help.. A: use baslikIndexes.Contains(23); A: List<int> lstint = new List<int>() { 5, 15, 23, 256, 55 }; bool ysno = lstint.Exists(p => p == 23); A: You should be using baslikIndexes.Contains(23) here, but if you'd like to use the Exists() method you can use it like this: baslikIndexes.Exists(x => x == 23); Read more about Lambda Expressions on MSDN.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Client Server Apps+java I have a java requirment contains both client and server side program. Server side Server program frequently check the data base and checks if a new order came, if order came it check the order and send it to the corresponding client machine using IP address and port.The client machines are out side the LAV and has static IP address. Client side Client program listen a its on port , when an order came, read it and process. For implementing these app, which java package is best,java socket communication or any other.Anybody know please suggest one. Help is highly appreciated, Thanks, vks. A: Don't go for low level programming like Sockets etc. Use RMI. Your program will have following two entities * *Server side : * *An RMI Client for calling client machine to send update after checking the database *Client side : * *An RMI server application listening for Server update requests and do processing. If you are new to RMI check out this tutorial . You can search for better tutorials if don't find these good enough :). A: I remember I had to do something similar in the university and I used JMS (Java Messaging Service), documented here: http://www.oracle.com/technetwork/java/jms/index.html The Server will create the messages from the DB by checking it periodically and will send messages to the clients which will process the info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pinch Zoom out in Google Maps in Android? I am developing an application in Android in which I'm using google map using the Javascript V3 library with Phonegap. It works fine for me until I noticed that map is zooming in on touch event but couldn't able to zoom out when I tried for number of times. I'll appreciate if someone suggest me how I can get the pinch zoom in and out without using the default zoom controls of Google Maps? A: Unfortunately there is no built-in function for this (not yet anyway), so in order to make it work you will have to create your own custom control for this action. This means capturing the touch event and zooming according to the gesture. To go into a little more details on this, have a control over the map canvas, and in it capture the touch events. Your second option since you are building for Android native is to use google maps from android (however this is java not javascript). You can find a basic tutorial on this here: http://mobiforge.com/developing/story/using-google-maps-android Hope this helps, Vlad
{ "language": "en", "url": "https://stackoverflow.com/questions/7551597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I send an email through my Exchange ActiveSync mail account? How can I send an email through my Exchange ActiveSync mail account and not gmail? When I use createchooser only gmail appears... Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); String aEmailList[] = { "me@mail.com" }; emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList); emailIntent.setType("plain/text"); startActivity(Intent.createChooser(emailIntent, "Send email...")); A: emailIntent.setType("application/octet-stream"); works for me! :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not load type from assembly Before you say anything, I have read the previously asked questions about this issue. The answers there did not fix my problem. It's pretty simple, I guess, if you know the answer. Here's my problem: I've got a solution with several projects, I'm creating a plugin-based application where I use Reflection to load all assemblies. This part goes fine, I load all my assemblies like so var filePaths = Directory.GetFiles(@"C:\CustomerServiceModule\", "*.dll", SearchOption.AllDirectories).Where(n => n.Contains("bin")); foreach (var f in filePaths) { Assembly.LoadFile(f); } Now I want to create an instance of a type, so I can work with it: var assembly = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.ManifestModule.Name == "Kayako.dll").SingleOrDefault(); var name = assembly.GetTypes(); var type = assembly.GetType("Kayako.KayakoData"); var lol = Activator.CreateInstance(type); This goes badly because inside KayakoData I have this: KayakoService _service = new KayakoService("xxx", "yyy", "zzz"); This service is an assembly that works, I've used it before. Version number is fine, there's nothing in the GAC that overrides it, I can't see any errors using Assembly Binding Log Viewer. I still get this error: [System.LoadTypeException]{"Could not load type 'KayakoRestAPI.KayakoService' from assembly 'KayakoRestAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"KayakoRestAPI.KayakoService"} Anyone have any bright ideas? I've been staring myself blind at this. If I remove the service part from KayakoData the whole thing works, but I really need to run the service. A: Quote from the documentation of the LoadFile method: Use the LoadFile method to load and examine assemblies that have the same identity, but are located in different paths. LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does. LoadFile is useful in this limited scenario because LoadFrom cannot be used to load assemblies that have the same identities but different paths; it will load only the first such assembly. Conclusion: try LoadFrom in order to load dependent assemblies as well. A: You just need to change the version of .dll from assembly info of that project. Then rebuild your solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: image resize with php? ive done my research on the net and here as well and i keep on coming up with no answer that can help me: i have the below code which displays an image from a folder based on a user's location however the image is too big and i need to resize it. all the scripts that i have tried or read relate to files being uploaded. can anyone push me in the right direction? thank you. <?php print" <table <td width=\"138\" height=\"73\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"> <tr> <td align=\"center\" valign=\"middle\"><a href=\"map.php\"><img src=\"" . esc('img/' . $db_name . '_maps/sm' . $user['location'] . '.png') . "\" alt=\"Map of systems around {$user['location']}\" /></a></td> </tr> </table> " ?> My problem arises from the fact that i need to pull the images as: <img src=\"" .esc('img/' . $db_name . '_maps/sm' . $user['location'] . '.png') . "\" alt=\"Map of systems around {$user['location']}\" /></a> A: Wrote a tutorial about this a while ago. Perhaps it can help. It starts with uploading, but most of it is about resizing. Just swap out the usage of the $_FILES array by geting the image type and file name a different way. Here's the code you should need: // Create image from file switch(strtolower($_FILES['image']['type'])) { case 'image/jpeg': $image = imagecreatefromjpeg($_FILES['image']['tmp_name']); break; case 'image/png': $image = imagecreatefrompng($_FILES['image']['tmp_name']); break; case 'image/gif': $image = imagecreatefromgif($_FILES['image']['tmp_name']); break; default: exit('Unsupported type: '.$_FILES['image']['type']); } // Target dimensions $max_width = 240; $max_height = 180; // Get current dimensions $old_width = imagesx($image); $old_height = imagesy($image); // Calculate the scaling we need to do to fit the image inside our frame $scale = min($max_width/$old_width, $max_height/$old_height); // Get the new dimensions $new_width = ceil($scale*$old_width); $new_height = ceil($scale*$old_height); // Create new empty image $new = imagecreatetruecolor($new_width, $new_height); // Resize old image into new imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height); // Catch the imagedata ob_start(); imagejpeg($new, NULL, 90); $data = ob_get_clean(); // Destroy resources imagedestroy($image); imagedestroy($new); // Set new content-type and status code header("Content-type: image/jpeg", true, 200); // Output data echo $data; If you want to store the image as a file rather than dumping it to the browser, remove the head and echo part at the end and then swap out the NULL parameter in the imagejpeg call with an actual filename. Hope that helps :) Here's the code in use: http://samples.geekality.net/image-resize/ A: You make take a look at gd : http://www.php.net/manual/en/function.imagecopyresized.php You can try this: $extension = substr( $img_url, -3 ); $extension = strtolower($extension); switch ($extension) { case "jpg": case "jpeg": $src_im = createimagefromjpeg($img_url); break; case "gif": $src_im = createimagefromgif($img_url); break; case "png": $src_im = createimagefrompng($img_url); break; } // Get size $size = GetImageSize($img_url); $src_w = $size[0]; $src_h = $size[1]; // $width has to be fixed to your wanted width $dst_w = $width; $dst_h = round(($dst_w / $src_w) * $src_h); $dst_im = ImageCreateTrueColor($dst_w, $dst_h); ImageCopyResampled($dst_im, $src_im, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h); ImageJpeg($dst_im); ImageDestroy($dst_im); imageDestroy($src_im); A: There a simple to use, open source library called PHP Image Magician that has some nice features and documentation. It uses 100% GD. Example of basis usage: $magicianObj = new imageLib('racecar.jpg'); $magicianObj -> resizeImage(100, 200, 'crop'); $magicianObj -> saveImage('racecar_small.png'); A: If you need more features convert might be a help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculate distance between two locations using google map in iphone I just want to calculate distance between two location . In which user can enter both the location's addresses, and from that addresses I want to calculate the distance between them. Is it possible to calculate distance from CLLocation using these addresses ? A: First you need to geocode the address to latitude/longitude, then you can use the CLLocation framework to calculate the distance. To geocode the adress, you could use this forward geocoding API. // get CLLocation fot both addresses CLLocation *location = [[CLLocation alloc] initWithLatitude:address.latitude longitude:address.longitude]; // calculate distance between them CLLocationDistance distance = [firstLocation distanceFromLocation:secondLocation];
{ "language": "en", "url": "https://stackoverflow.com/questions/7551610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AppWidgetProvider(Widget) with Service Android Why in almost all the tutorials or examples people do that: @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { ... context.startService(resumeIntent); super.onUpdate(context, appWidgetManager, appWidgetIds); } Doesn't it mean that the new service is started every time the update is executed? Is it the best solution? Or is it better to do it with sending broadcasts? And shouldn't context.startService(resumeIntent); better be done in onEnabled method? A: No, the service is started ONLY IF it isn't already running: if it is already running it is sent a new Intent in onStartCommand and it can process that appropriately. As far as whether to use this or to use onEnabled the advantage this has is that the service is restarted every single time if it is not running: onEnabled will start the service but if the service is killed for any reason you may not get it restarted for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: getting rss news feed using jquery mobile I am making a mobile web app. This app will get news from yahoo. I am currently using jquery plugin to get these news. I am also using jquery mobile for interface. On the index page I have listview and it contains all the titles such as Top News, World News, Sports News etc. Here is index page code <html> <head> <title>Title</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width = device-width, initial-scale = 1, user-scalable = no" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" /> <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script> <script src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script> </head> <body> <div data-role="page"> <header data-role="header"> <h1>Yahoo News</h1> </header> <div data-role="content"> <ul data-role="listview" data-inset="true"> <li><a href="topNews.php" data-transition="slidedown">Top Stories</a></li> <li><a href="worldNews.php" data-transition="slidedown">World News</a></li> <li><a href="techNews.php" data-transition="slidedown">Technology</a></li> <li><a href="scienceNews.php" data-transition="slidedown">Science</a></li> <li><a href="enterNews.php" data-transition="slidedown">Entertainment</a></li> <li><a href="sportsNews.php" data-transition="slidedown">Sports</a></li> </ul> </div> <footer data-role="footer"> <h4>Footer</h4> </footer> </div> </body> So when USer clicks lets say Top Stories then it will take user to appropriate page and display top news on that page. Now it does take user to top news page but when he gets there he does not see any news. That page is empty. But when user refresh this page by clicking refresh button of the browser then it does show all the news. So my problem is that it should display the news as top news page is displayed. here is top news page code <html> <head> <title>Title</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width = device-width, initial-scale = 1, user-scalable = no" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" /> <link href="styles.css" rel="stylesheet" type="text/css" /> <script src="http://code.jquery.com/jquery-latest.js"></script> <script src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script> <script language="javascript" type="text/javascript" src="jquery.jfeed.js"></script> <script language="javascript" type="text/javascript" src="jquery.aRSSFeed.js"></script> <script type="text/javascript"> $(document).ready( function() { $('div.RSSAggrCont').aRSSFeed(); }); </script> </head> <body> <div data-role="page"> <header data-role="header"> <a href="#" data-transition="slidedown" data-rel="back" data-icon="arrow-l">Back</a> <h1>Top News</h1> </header> <div data-role="content"> <div class="RSSAggrCont" rssnum="5" rss_url="http://rss.news.yahoo.com/rss/topstories"> </div> </div> <footer data-role="footer"> <h4>Footer</h4> </footer> </div> </body> Can someone tell me where am I making mistake? Any solution Please A: There is a brilliant article called How to build an RSS reader with Jquery Mobile. It takes you through every step of the process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails assets images in production I found some strange behavior of assets images If I run unicorn in production mode at hosting - /assets/image.png - server give me blank image ie file exist, but size=0 . In same time at localhost I run in unicorn development mode - and all works fine, Then I run webrick at hosting - images are display fine. After that I run unicorn in production mode at localhost and images stops display, then I run unicorn in development images already doesn't work. Rails 3.1.0.rc6, after that I update to rc8 at hosting but nothing happened Maybe production mode build some cache, which remains forever? A: There are different things that may go wrong, so here the ideas you have to check: * *There is a known error in Rails 3.1, that the precompilation of assets does not work properly. See Upgrade to Rails 3.1.0 from rc6, asset precompile fails for a question with a solution. *I had problems with creating precompiled assets for production. The following worked for me (after fixing the error above): * *Ensure that your application is not running in production mode. *Call bundle exec rake assets:clean. This will clean all resources hanging around. *Call bundle exec rake assets:precompile afterwards. As a result, the directory /public/assets should be filled with assets with the hash appended (e.g. icon_add-96985e087048a8c2e09405494509750d.gif instead of icon-add.gif). *Start your server in production mode. *Depending on the browser I used, I had to refresh or even clear all caches. Especially Chrome was very nasty in caching resources that he should not cache. I hope some of the ideas will help you find the source of your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python encoding Using mechanize, I retrieved source page of an web which contains some non-ASCII characters, such as Chinese characters. Code goes below: #using python2.6 from mechanize import Browser br = Browser() br.open("http://www.example.html") src = br.reponse().read() #retrieve the source of the web print src #print the src Question: 1.According to the source of the page, I can see that, its charset=gb2312, but when I print src, all the contents are correct, I mean no gibberish. Why? Does print know the src's encoding? 2.Should I explicitly decode or encode the src? A: src is a unicode, which has no encoding. print (or more correctly, sys.stdout.write()) figures out what encoding to use when outputting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Twitter Bootstrap's javascript Popover looking wrong I'm trying to implement Bootstrap JS's Popover (this), and for some reason it's not showing up like it's supposed to. This is what I'm getting As you can see, the body of the Popover is shifted towards the left, and the border's kinda broken. Here's my code <a class="btn success" id="previewBeforeSubmit" href="#" data-original-title="Test" data-content="Lorem Ipsum">Save Changes</a> <script type="text/javascript"> $("#previewBeforeSubmit").popover({position: 10, placement: 'above'}); </script> Any clue as to what's causing this? A: Most likely a CSS conflict. Your existing css rules might be adding attributes to the ones of the popover. I would start with an inspection in FireBug and see what css rules are inherited from where. A: I guess you are using their container example. If yes, you can fix this problem by comment out line margin: 0 -20px. It appears in the following block: .content { background-color: #fff; padding: 20px; margin: 0 -20px; ... } A: It's a margin thing, add .popover .content { margin: 0; } this should fix your problem. A: The more universal fix is to add data-container='body' to the element to stop it from inheriting css rules from (and through) the element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: strncpy segfault I've been having trouble getting this section of code to work. I'm trying to get a character array to be copied so I can get a count of how many tokens there are to dynamically allocate and save them to be examined for environment variables. However, I keep segfaulting when it tries to strncpy the original string. void echo(char *str1) { char *token, *temp; char *saveptr1; int j, i, k, counter; char *copy; strncpy(copy, str1, 80); const char *delim = " "; i = strlen(copy); for(j = 0; j < i; j++, copy = NULL) { token = strtok_r(copy, delim, &saveptr1); counter++; if(token == NULL) { counter--; break; } } // initialize token array for echo char *tokAr[counter]; for(j = 0; j < counter; j++) tokAr[j] = malloc(80*sizeof(char)); for(j = 0, k = 0; j < i; j++, str1 = NULL) { tokAr[k] = strtok_r(str1, delim, &saveptr1); if( tokAr[k] != NULL) { if(strchr(tokAr[k], 36) != NULL) { temp = enviro(tokAr[k]); printf("%s ", temp); } else printf("%s ", tokAr[k]); } else break; } for(k = 0; k < counter; k++) free(tokAr[k]); } char* enviro(char *ret) { char *copy, *expand, *saveptr; const char *delim = "$"; strcpy(copy, ret); expand = strtok_r(copy, delim, &saveptr); return getenv(expand); } I know it has something to do with how I copy the passed in str1 character array but I can't figure it out from gdb. Any help is greatly appreciated A: You haven't allocated memory for copy. char *copy; strncpy(copy, str1, 80); Try malloc or strdup if you don't need the full 81 characters. copy = malloc(81); strncpy(copy, str1, 80); /* Or strdup. */ copy = strdup(str1); A: copy does not contain a valid allocated address. Please allocate enough memory with malloc before using copy. Also remember to free copy after you have completed using it to stop memory leak in larger programs. A: I think in function echo, you haven't initialized the variable counter and trying to incrementing and decrementing it. Try to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: asp.net mvc3 working with master pages In my website, when the user logs in, I want to show the user name and also show a logout button. In ASP.NET 4.0, we could use the code behind file of the master page to write code for a common thing like this. But I don't know how to achieve this in MVC3. I would not like to pass user name on every page view and add action link of logout on every controller. Can anyone suggest a better way? Thanks Saarthak A: You could use a partial. The default template does exactly that. Create a new ASP.NET MVC 3 application using the built-in wizard and look at the _LogOnPartial.cshtml partial that's been generated for you and which is invoked in the _Layout.cshtml using @Html.Partial("_LogOnPartial"). This partial looks like this: @if(Request.IsAuthenticated) { <text>Welcome <strong>@User.Identity.Name</strong>! [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text> } else { @:[ @Html.ActionLink("Log On", "LogOn", "Account") ] } It checks if the user is authenticated and if it is it Welcomes him and provides a LogOff link and if he isn't it simply provides a LogOn link. Same stuff if you are using the WebForms view engine: LogOnUserControl.ascx which is invoked from Site.Master using <% Html.RenderPartial("LogOnUserControl"); %>.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 - JS - Socket.io-emit in *.js.erb gets not executed and prevents execution of jQuery-Function I want to use node.js with my Rails-Project to serve asynchronous io. I don't want to use juggernaut, faye or something like this, because I need clean connections with web-socket, server-sent events and spdy without an alternative. My first try to use node.js is now to use Socket.io, just to get in use with serving data to a node.js-module with JavaScript. But it doesn't work at all. My application.js looks like this: // This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree . window.socket = io.connect('http://localhost:8080/'); The requirements for io get correctly loaded in my application.html.erb: <%= javascript_include_tag "application", "http://localhost:8080/socket.io/socket.io.js" %> Now I want to use the socket to emit a event sent to all listening clients like this in a create.js.erb: $(function() { window.socket.emit('message', <%= @message =>); }; $("#new_article")[0].reset(); The message gets created in the ArticlesCrontroller this way: def create @article = current_user.articles.build(params[:article]) if @article.save msg = {:data => @article.to_json} @message = msg.to_json end end I listen at this event in an other view called index.js.erb this way: $(function() { window.socket.on('message', function (msg) { $("#articles").prepend(<%= escape_javascript render(Article.new.from_json(msg.data)) %>); }); }); The Socket.io looks like this: var io = require('socket.io').listen(8080); io.sockets.on('connection', function (socket) { socket.on('message', function () { }); socket.on('disconnect', function () { }); }); and seems to work right, because it tells me right how it serves the requested js-File: info - socket.io started debug - served static /socket.io.js But it doesn't work at all, although the create.js.erb gets rendered without an error: Rendered articles/create.js.erb (0.5ms) Completed 200 OK in 268ms (Views: 70.0ms | ActiveRecord: 14.6ms) Even the jQuery-Function for resetting the form gets not executed, what works without the try to emit the socket-event. The article gets saved to the database correctly, so that isn't the problem. Can someone tell me where the problem might be? Update: I figured out by using the JavaScript-debugger of chrome, that the problem starts with the definition of window.socket in the application.js. The error-code is: Uncaught ReferenceError: io is not defined (anonymous function) But io is defined in the socket.io.js-File I load in my application.html.erb. I did a workaround for application.js this way: $.getScript('http://localhost:8080/socket.io/socket.io.js', function(){ window.socket = io.connect('http://localhost:8080/'); }); The question is now: Why do I have to get the script this way, although it is loadet in the application.html.erb? But despite this workaround the create.js.erb still doesn't work yet. I will try to workaround that after having a bit of sleep. A: I generally include dependencies in the relevant manifest (in this case, application.js). Rails has awareness of many different asset paths, all of which are checked prior to compilation. I'd be inclined to put (e.g. socket.io.js) in vendor/assets/javascripts and add an extra line to the manifest as follows: //= require jquery //= require jquery_ujs //= require socket.io //= require_tree .
{ "language": "en", "url": "https://stackoverflow.com/questions/7551630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Eclipse: How to get TODOs from SQL and XML files in tasks In Java files I can write TODO comments and they show up in the Tasks window. // TODO: Do something about this However, when I write TODO comments in for example SQL scripts and XML files, they don't show up. Is there a way I can get them to do that? For example: -- TODO: Fix this SQL query <!-- TODO: Fix this XML --> A: checkbox to activate : Editors/structured text editors/task tags => check "Enable searching for task tags" A: Check your main Preference dialog for Task Tags pages. Type "task" into the search box in the upper left of the dialog to help you find relevant pages. For XML files, I know that that feature is off by default. A: Because a picture worth a thousand words : A: Another option is to use Add Task... by right-clicking on the gutter of the editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Ninject Binding Constraint that searches up to find a type I've got a class hierarchy like this (simplified): class Connection { } interface IService<T> { } class ServiceImplementation : IService<int> { public ServiceImplementation(Connection) { } } interface IConnectionConfiguration { public void Configure(Connection c) } class ConnectionConfiguration : IConnectionConfiguration { public void Configure(Connection c) } Where I have multiple implementations of IConnectionConfiguration and IService. I am wanting to create a provider/bindings which: * *constructs a new instance of Connection. *GetAll and applies that to the Connection. *Bindings specify which IConnectionConfiguration implementations to be used, based on on the type of IService to be constructed Currently I have a provider implementation like this: public Connection CreateInstance(IContext context) { var configurations = context.Kernel.GetAll<IConnectionConfiguration>() var connection = new Connection(); foreach(var config in configurations) { config.Configure(connection); } return connection; } But when I try to make the contextual binding for IConnectionConfiguration it doesn't have a parent request or parent context... Bind<IConnectionConfiguration>().To<ConcreteConfiguration>().When(ctx => { // loop through parent contexts and see if the Service == typeof(IService<int>); // EXCEPT: The ParentRequest and ParentContext properties are null. }); What am I doing wrong here? Can I do this with ninject? A: By calling kernel.GetAll you are creating a new request. It has no information about the service context. There is an extension that allows you to create new requests that preserve the original context (Ninject.Extensions.ContextPreservation) See also https://github.com/ninject/ninject.extensions.contextpreservation/wiki context.GetContextPreservingResolutionRoot().GetAll<IConnectionConfiguration>();
{ "language": "en", "url": "https://stackoverflow.com/questions/7551638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: change portlet title from code in Liferay without Jquery I'm having solution to change title of portlet through JQuery. $('#idOfPortlet').find('.portlet-title').html('new title'); But we dont want to use JQuery in our project. Is there any solution to change title of portlet using YUI or anyother thing through code? Thanks in Advance. Regards, Mayur Patel A: If the version of Liferay you're on is using YUI 3, then this aught to do it: Y.one('#idOfPortlet .portlet-title').setContent('new title'); I'm not sure if Liferay exposes the YUI instance as Y, or if they wrap it in AUI and make it A. A: You can do so, by using this code - document.getElementsByClassName('.portlet-title')[0].content = 'something else as title'
{ "language": "en", "url": "https://stackoverflow.com/questions/7551639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NullReferenceException in C# when dealing with Streams? So, I'm pretty new to all this network programming, and I have a few questions... I'm building a client-server chat application, wherein the server is running, the client(s) connect(s) to the server, and then when a client sends a message to the server, the server relays it to all the clients. The server is a console application, and the client is a Windows Form Application. The error I'm getting is in my client, at the very top of my form, I have a textbox to take in a user's name and a button to "submit" it and connect to the server with that username. Anyways, this is my button connect code: private void btnConnect_Click(object sender, EventArgs e) { readData = "Connecting to chat server..."; msg(); try { sck_client.Connect("127.0.0.1", 8888); sw = new StreamWriter(sck_client.GetStream()); string toSend = txtUsername.Text; sw.Write(toSend); sw.Flush(); chatThread = new Thread(GetMessages); chatThread.Start(); } catch (Exception ex) { readData = ex.ToString(); msg(); } } msg() quite simply takes the value in readData and prints it to the screen (in a richtextbox). sw is a streamwriter that has been declared publicly, outside of the method, so is sck_client (a TcpClient) and chatThread (a Thread). Basically, the issue is, when I run my program and try to connect, it throws Exception ex, as though it cannot connect. It throws a NullReferenceException with the text: System.NullReferenceException: Object reference not set to an instance of an object. at Chat_Client.Main.btnConnect_Click(Object sender, EventArgs e) in filepath\Chat_Client\Main.cs:line36 That occurs even when my server is running and listening to port 8888. So, what should I do to fix it? If you need any more of my code to solve the problem, let me know in a comment and I'll post it. To show where the code is instantiated: public partial class Main : Form // new class for the form itself { // all of these are declared outside any method: TcpClient sck_client = default(TcpClient); Thread chatThread = default(Thread); string readData = null; StreamWriter sw = default(StreamWriter); StreamReader sr = default(StreamReader); ... A: Ok, this line is your problem: TcpClient sck_client = default(TcpClient); specifically: default(TcpClient); default() will return the default value for a given type. If the type is a reference type (eg. class), then it will return null. If the type is a value type (eg. int) then it will attempt to set it to 0. The default keyword does NOT create a new instance of the the class for you, you need to the use the new keyword for that. I would seriously be reading this: http://msdn.microsoft.com/en-us/library/fa0ab757.aspx A: TcpClient sck_client = default(TcpClient); ... sck_client.Connect("127.0.0.1", 8888); at some point, you will need to give it a value other than null (the default for TcpClient is null). Also, you probably don't need a StreamWriter just to send a string - I'd look at using Encoding (to get the bytes; typically UTF8), and a length-prefix of the size (in bytes).
{ "language": "en", "url": "https://stackoverflow.com/questions/7551641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Internet explorer 10 wrong behavior with HTML5 video is it other browsers? With this test, IE10 dev-preview shows very strange behavior. It passes the test but continue the playback while it should remain at the paused state. Other browsers don't show this behavior. Given the following piece of code (extracted from the embedded script in ), should the video start playing after passing the test? var t = async_test("video.paused should be true during pause event", {timeout:30000}); var v = document.getElementById("v"); v.addEventListener("pause", function() { t.step(function() { assert_true(v.paused); }); t.done(); }, false); v.src = getVideoURI("http://media.w3.org/2010/05/video/movie_300") + "?" + new Date() + Math.random(); v.play(); v.pause();
{ "language": "en", "url": "https://stackoverflow.com/questions/7551642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mongo DB: how to select items with nested array count > 0 The database is near 5GB. I have documents like: { _id: .. user: "a" hobbies: [{ _id: .. name: football }, { _id: .. name: beer } ... ] } I want to return users who have more then 0 "hobbies" I've tried db.collection.find({"hobbies" : { &gt : 0}}).limit(10) and it takes all RAM and no result. * *How to do conduct this select? *And how to return only: id, name, count ? *How to do it with c# official driver? TIA P.S. near i've found: "Add new field to hande category size. It's a usual practice in mongo world." is this true? A: You can (sort of) check for a range of array lengths with the $size operator using a logical $not: db.collection.find({array: {$not: {$size: 0}}}) A: That's somewhat true. According to the manual http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size $size The $size operator matches any array with the specified number of elements. The following example would match the object {a:["foo"]}, since that array has just one element: db.things.find( { a : { $size: 1 } } ); You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements So you can check for array size 0, but not for things like 'larger than 0' A: In this specific case, you can use list indexing to solve your problem: db.collection.find({"hobbies.0" : {$exists : true}}).limit(10) This just makes sure a 0th element exists. You can do the same to make sure the list is shorter than n or between x and y in length by checking the existing of elements at the ends of the range. A: Have you tried using hobbies.length. i haven't tested this, but i believe this is the right way to query the range of the array in mongodb db.collection.find({$where: '(this.hobbies.length > 0)'}) A: Earlier questions explain how to handle the array count issue. Although in your case if ZERO really is the only value you want to test for, you could set the array to null when it's empty and set the option to not serialize it, then you can test for the existence of that field. Remember to test for null and to create the array when you want to add a hobby to a user. For #2, provided you added the count field it's easy to select the fields you want back from the database and include the count field. A: * *if you need to find only zero hobbies, and if the hobbies key is not set for someone with zero hobbies , use EXISTS flag. Add an index on "hobbies" for performance enhancement : db.collection.find( { hobbies : { $exists : true } } ); *However, if the person with zero hobbies has empty array, and person with 1 hobby has an array with 1 element, then use this generic solution : Maintain a variable called "hcount" ( hobby count), and always set it equal to size of hobbies array in any update. Index on the field "hcount" Then, you can do a query like : db.collection.find( { hcount : 0 } ) // people with 0 hobbies db.collection.find( { hcount : 5 } ) // people with 5 hobbies 3 - From @JohnPs answer, "$size" is also a good operator for this purpose. http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size
{ "language": "en", "url": "https://stackoverflow.com/questions/7551645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Querying data from a child model I have 3 models that I have setup thus far in a simple application I am working on: So far I have these models: * *UserAccountEntity - Top level Table (Has a One-Many Relationship to UserAccountEntityStrings) *UserAccountEntityStrings - Child Table (Has a Many-One relation ship to UserAccountEntity and EavAttributes *EavAttributes - Lookup Table When I query data from my top level table, I get the schema,association information for the child table. But I do not get any of the persisted data from the child table. What I expected the results to be were, the data from the top level model and the data from the associated child model. Any help with this is greatly appreciated. A note that may be helpful, I am using Zend 1.11.10 and Doctrine 2 This is what my query looks like: $users = $em->createQuery('select u from Fiobox\Entity\UserModule\UserAccountEntity u')->execute(); Zend_Debug::dump($users[0]); This is the association in my top level model: /** * * @param \Doctrine\Common\Collections\Collection $property * @OneToMany(targetEntity="UserAccountEntityStrings",mappedBy="UserAccountEntity", cascade={"persist","remove"}) */ private $strings; These are the associations in my child model: /** * * @var UserAccountEntity * @ManyToOne(targetEntity="UserAccountEntity") * @JoinColumns({ * @JoinColumn(name="entity_id", referencedColumnName="entity_id") * }) */ private $user; /** * @var EavAttribute * @ManyToOne(targetEntity="Fiobox\Entity\EavModule\EavAttributes") * @JoinColumn(name="attribute_id", referencedColumnName="attribute_id") */ private $attributes; A: Have you actually tried anything? Doctrine will lazy load stuff for you. Your var_dump probably shows persistent collections of proxy objects for your child objects. But if you access them, they'll be loaded automatically: <?php $users = $em->createQuery('select u from Fiobox\Entity\UserModule\UserAccountEntity u')->fetchAll(); foreach($users as $u){ foreach($u->strings as $s){ var_dump($s); } } If you know that you're going to need all that child data, you might as well force a fetch-join in your DQL: <?php $users = $em->createQuery('select u, s from Fiobox\Entity\UserModule\UserAccountEntity u JOIN u.strings s')->fetchAll();
{ "language": "en", "url": "https://stackoverflow.com/questions/7551646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define part of a Manipulate control variable definition to reduce code duplication This is a little related to this question Define control as variable in Mathematica But the above question did not answer my problem, as it talks about the full control definition. (I also tried some of the tricks shown there, but they do not work for my problem). I am now asking about definition for only part of the control. (It is also very hard to follow up on an old question using this forum format. Because using the tiny comment area, it hard to ask and show more like when asking a new question where the space is larger, and one can paste code and images). All the tries I have made do not work. I'll start by simple example to explain the problem. Assume one want to write Clear["Global`*"]; Manipulate[Plot[f*g, {x, -1, 1}], Grid[{ {Style["f(x)="], PopupMenu[Dynamic[f], {x, x^2, x^3}, ImageSize -> Tiny]},{Style["g(x)="], PopupMenu[Dynamic[g], {x, x^2, x^3}, ImageSize -> Tiny]} }] ] you can see there is allot of code duplication in each control definition. (things like ImageSize, Spacings-> and many other decoration settings, are repeated over and over for each control. What will be great, if I can write something like Manipulate[Plot[f*g, {x, -1, 1}], Grid[{ {Style["f(x)="], PopupMenu[Dynamic[f], Evaluate@Sequence@v]}, {Style["g(x)="], PopupMenu[Dynamic[g], Evaluate@Sequence@v]} }], Initialization :> ( v = {{x, x^2, x^3}, ImageSize -> Tiny} ) ] But this does not work. I tries many other things along the above line, and nothing works. Like {Style["f(x)="], PopupMenu[Dynamic[f], v]}, and {Style["f(x)="], PopupMenu[Dynamic[f], Evaluate@v]} and Manipulate[Plot[f*g, {x, -1, 1}], {{v, {{x, x^2, x^3}, ImageSize -> Tiny}}, None}, Grid[{ {Style["f(x)="], PopupMenu[Dynamic[f], Evaluate@v]}, {Style["g(x)="], PopupMenu[Dynamic[g], v]} }] ] can't get it to work. But here are the rules of the game: This will be for a demo, hence, code must start with Manipulate. Can't have Module outside Manipulate. Also, can not use Hold and its friends. But can use Unevaluated. I was hoping the experts here might have a trick to do this. The will reduce the code size if it is possible to do, as many of the control I have, contain many 'options' like the above that are the same, and being able to do the above will make the code easier to read and manage. thanks, ps. What I am asking for, is sort of similar to what one does for say Plot options, where one can use SetOptions to set some common default options so they do not have to duplicate them for each Plot command each time. But there is no such thing in this case. update Using the method shown by Leonid below, (the Macro trick), I wanted to use it to help me define number of controls, all using one common setting. This is what I tried: Manipulate[{x, y}, Evaluate@With[ { control1 = Function[{var, initialValue, str, from, to, incr}, { {{var, initialValue, str}, from, to, incr, ImageSize -> Tiny} } , HoldAll ] }, { First@control1[x, 0, "x=", 0, 1, .1], First@control1[y, 0, "y=", 0, 2, .1], First@control1[z, 0, "z=", 0, 10, .1] }, ] ] The problem is just an extra {} around the whole thing, else it will work. Will keep trying to solve this. But getting close. Tried Sequence[], and Flatten[..,1] and such, but can not do it yet. Making more coffee, should help. Update 2 This is below an example using Simon method to use to help define common definition across more than one control. This way, one can use it to reduce code duplication for common options on set of separate controls Notice, had to use Control[] to get it to control. Manipulate[{x, y, z}, Dynamic[Grid[{ {control1[x, 0, "x=", 0, 1, .1]}, {control1[y, 0, "y=", 0, 2, .1]}, {control1[z, 0, "z=", 0, 10, .1]} }]], {{control1, Function[{var, initialValue, str, from, to, incr}, Control[{{var, initialValue, str}, from, to, incr, ImageSize -> Tiny}], HoldFirst]}, None} ] Update 3 And got Leonid method to work also on more than one control. The trick is to use Control[]. Can't use plain old {{x,0,"x"},...} [EDIT, yes, you can, just need the Sequence@@ method as shown below by Leonid update.]. Here it is: Manipulate[{x, y, z}, Evaluate@With[ { control1 = Function[{var, initialValue, str, from, to, incr}, Control[{{var, initialValue, str}, from, to, incr, ImageSize -> Tiny}] , HoldAll ] }, Grid[{ {control1[x, 0, "x=", 0, 1, .1]}, {control1[y, 0, "y=", 0, 2, .1]}, {control1[z, 0, "z=", 0, 10, .1]} }] ] ] I'll try to integrate one of these methods into my main demo (has over 600 lines of code just for the control layout so far and growing by the minute, hopefully these methods will shrink this by quite a bit) Update 9/26/11. 7 pm I thought I post a 'birds eye' view of the code saving by using 'macros' to define controls which contains many common boiler-plate code. Here is a screen shot of before and after. Thanks again for all the answer and help. A: I was going to give a solution almost the same as Leonid's and use With to insert the code, but he beat me to it, so here's an alternative way. Define a dynamic local function using ControlType -> None that does your styling: Manipulate[Plot[{f, g + 1}, {x, -1, 1}], Dynamic[Grid[{{Style["f(x)="], pu[f]}, {Style["g(x)="], pu[g]}}]], {{pu, Function[{f}, PopupMenu[Dynamic[f], {x, x^2, x^3}, ImageSize -> Tiny], HoldFirst]}, None}] By the way, the Style[] in Style["f(x)="] is redundant, as you are not actually setting any styles... A: What about this Manipulate[Plot[f*g, {x, -1, 1}], Evaluate@ With[{styleAndpopup = Function[{st, fun}, { Style[st], PopupMenu[Dynamic[fun], {x, x^2, x^3}, ImageSize -> Tiny] }, HoldAll]}, Grid[{styleAndpopup["f(x)=", f], styleAndpopup["g(x)=", g]}]]] This is actually a tiny example of the code-generation at work, since if you look at the FullForm of the resulting Manipulate, you will see the same expression you originally started with. The styleAndpopup is actually not a function here, but a macro, locally defined using With. EDIT Per request of the OP - generalizing to many controls. The easiest fix is to insert Sequence@@... as Sequence @@ {First@control1[.... However, there is some extraneous stuff that can be removed as well: Manipulate[{x, y}, Evaluate@With[{control1 = Function[{var, initialValue, str, from, to, incr}, Unevaluated@{{var, initialValue, str}, from, to, incr, ImageSize -> Tiny}, HoldAll]}, Sequence @@ { control1[x, 0, "x=", 0, 1, .1], control1[y, 0, "y=", 0, 2, .1], control1[z, 0, "z=", 0, 10, .1]}]] A: One could do this: Manipulate[ Plot[f*g, {x, -1, 1}] , Grid[ { {Style["f(x)="], PopupMenu[Dynamic[f], opts]} , {Style["g(x)="], PopupMenu[Dynamic[g], opts]} } ] ] /. opts -> Sequence[{x, x^2, x^3}, ImageSize -> Tiny] If one is in the habit of assigning down-values to symbols whose names do not begin with $, then it would be prudent to wrap the whole thing in Block[{x, opts}, ...] in case x and opts have globally-defined values. A similar technique is possible for the case of multiple controls: Manipulate[ {x, y, z} , Grid[ { {control1[x, 0, "x=", 0, 1, .1]} , {control1[y, 0, "y=", 0, 2, .1]} , {control1[z, 0, "z=", 0, 10, .1]} } ] ] /. control1[var_, initialValue_, str_, from_, to_, incr_] :> Control[{{var, initialValue, str}, from, to, incr, ImageSize -> Tiny}]
{ "language": "en", "url": "https://stackoverflow.com/questions/7551647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }