text
stringlengths
8
267k
meta
dict
Q: how to display legend on right side of piechart in achartengine android I am using the pie chart view from achartengine's tutorial. Here is what i want. I want the legends i.e. pass/fail to be displayed to the right of the pie chart as shown in the figure. In the demo examples of achartengine, they are bottom aligned. How to get them to the right? Please help! A: This code below worked for me. But I think it's better creating a RecyclerView as a legend, instead of using the one provided by MPAndroidChart class. What I did: * *Create the RecyclerView and celda_recycler_legend.xml: *Create an AdapterLegend.java script, which extents RecyclerView.Adapter class, to be able to use a RecyclerView with the legends. On this script, I added a LegendViewHolder instance, which extents RecyclerView.ViewHolder, with the celda_recycler_legend.xml configured. AdapterLegend class AdapterLegend extends RecyclerView.Adapter { private ArrayList<String> legends; private ArrayList<Integer> colors; public AdapterLegend(ArrayList legends, ArrayList<Integer> colors) { this.legends = legends; this.colors = colors; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); return new LegendViewHolder(layoutInflater.inflate(R.layout.celda_recycler_legend, parent, false)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { LegendViewHolder legendViewHolder = (LegendViewHolder) holder; legendViewHolder.LoadLegend(legends.get(position), colors.get(position)); } @Override public int getItemCount() { return legends.size(); } } LegendViewHolder class LegendViewHolder extends RecyclerView.ViewHolder { private final TextView legendText; private final ImageView legendColorLabel; public LegendViewHolder(@NonNull View itemView) { super(itemView); legendText = itemView.findViewById(R.id.legendTextView); legendColorLabel = itemView.findViewById(R.id.legendLabelColor); } public void LoadLegend(String legend, int legendColor){ legendText.setText(legend); legendColorLabel.setBackgroundColor(legendColor); } } *I set the RecyclerView with an AdapterLegend instance legendRecyclerView = recountDataLayout.findViewById(R.id.chartLegendRecycler); legendRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false)); https://github.com/PhilJay/MPAndroidChart/issues/2478#issuecomment-378566623 Hope this works for you!
{ "language": "en", "url": "https://stackoverflow.com/questions/7553067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Query syntax for MySQL I am stuck on the query synatax for the following scenario. Lets say I have a table structured like: id - name - count Now I would like to get records whose count values sum to a particular number. Example. 1 - A - 3 2 - A - 2 3 - A - 5 4 - B - 1 5 - C - 2 And I would like to get only records (tuples) whose count value added together gives me number 10. The result should give me: 1 - A - 3 2 - A - 2 3 - A - 5 A: select * from tableName t where 10 = ( select sum(count) from tableName where name = t.name ) A: I think you can accomplish this with a nested query, like so: SELECT * FROM ( SELECT *, SUM(`count`) AS `sum` FROM `table` GROUP BY `name` ) WHERE `sum` = '10'
{ "language": "en", "url": "https://stackoverflow.com/questions/7553072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Like Button And W3C Errors Im using this like code on my website and W3C Dont Like It Can someone please give me the right code i should use to pass so i know where im going wrong please see code at http://www.justvibe.co.uk/ as i cant seam to post it up. Thanks Dan *ERRORS*** Validation Output: 7 Errors Line 37, Column 105: required attribute "type" not specified…ect.facebook.net/en_US/all.js#xfbml=1"> The attribute given above is required for an element that you've used, but you have omitted it. For instance, in most HTML and XHTML document types the "type" attribute is required on the "script" element and the "alt" attribute is required for the "img" element. Typical values for type are type="text/css" for and type="text/javascript" for . Line 37, Column 129: there is no attribute "href"…ll.js#xfbml=1"> You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Transitional" document type to get the "target" attribute), or by using vendor proprietary extensions such as "marginheight" (this is usually fixed by using CSS to achieve the desired effect instead). This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information. How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the element to incorporate flash media in a Web page, see the FAQ item on valid flash. Line 37, Column 163: there is no attribute "send"…ref="http://www.justvibe.co.uk/" send="true" width="450" show_faces="true" fon… ✉ You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Transitional" document type to get the "target" attribute), or by using vendor proprietary extensions such as "marginheight" (this is usually fixed by using CSS to achieve the desired effect instead). This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information. How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the element to incorporate flash media in a Web page, see the FAQ item on valid flash. Line 37, Column 176: there is no attribute "width"…ww.justvibe.co.uk/" send="true" width="450" show_faces="true" font="arial"> You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Transitional" document type to get the "target" attribute), or by using vendor proprietary extensions such as "marginheight" (this is usually fixed by using CSS to achieve the desired effect instead). This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information. How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the element to incorporate flash media in a Web page, see the FAQ item on valid flash. Line 37, Column 193: there is no attribute "show_faces"…tvibe.co.uk/" send="true" width="450" show_faces="true" font="arial"> ✉ You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Transitional" document type to get the "target" attribute), or by using vendor proprietary extensions such as "marginheight" (this is usually fixed by using CSS to achieve the desired effect instead). This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information. How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the element to incorporate flash media in a Web page, see the FAQ item on valid flash. Line 37, Column 205: there is no attribute "font"…tvibe.co.uk/" send="true" width="450" show_faces="true" font="arial"> ✉ You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Transitional" document type to get the "target" attribute), or by using vendor proprietary extensions such as "marginheight" (this is usually fixed by using CSS to achieve the desired effect instead). This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information. How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the element to incorporate flash media in a Web page, see the FAQ item on valid flash. Line 37, Column 212: element "fb:like" undefined…tvibe.co.uk/" send="true" width="450" show_faces="true" font="arial"> ✉ You have used the element named above in your document, but the document type you are using does not define an element of that name. This error is often caused by: •incorrect use of the "Strict" document type with a document that uses frames (e.g. you must use the "Frameset" document type to get the "" element), •by using vendor proprietary extensions such as "" or "" (this is usually fixed by using CSS to achieve the desired effect instead). •by using upper-case tags in XHTML (in XHTML attributes and elements must be all lower-case). A: You should add the appropriate namespace attribute for XFBML to the html tag: xmlns:fb="http://www.facebook.com/2008/fbml" This is mandatory for IE to work properly with Facebook social plugins. And if you want to use Open Graph: xmlns:og="http://opengraph.org/schema/" The W3C validator will still show errors as it doesn't take the additional namespaces into account. A: If you want to pass it that way, you need to output the FBML via JavaScript and wrap things in CDATA: <script language="javascript" type="text/javascript"> //<![CDATA[ document.write('<fb:like href="http://www.yourdomain.com" layout="button_count" show_faces="false" width="450" action="like" font="arial" colorscheme="light"></fb:like>'); //]]> </script> A: You are using the HTML5 version of the like button with a non-HTML5 doctype. Use the XFBML version with the XML namespace added to your HTML tag instead, or convert your page to HTML5. You'll also need to add type="text/javascript" to the <script> tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Facebook authorize w/permissions request yield "Page Not Found" Somewhere along the way in the past few weeks, the authorize Facebook call in iOS fails with a "Page Not Found". This happens for any user that has not installed the app or if the app's permissions have changed and the user must approve the additional permissions. This happens whether the Facebook app handles the user authentication or Safari or the popup dialog. All redirect to a "Page Not Found" page. Digging through the debugger, I found the initial URL request to be (app id replaces "[app_id]") for the login screen: https://m.facebook.com/dialog/oauth?type=user_agent&display=touch&redirect_uri=fb[app_id]%3A%2F%2Fauthorize&sdk=2&scope=user_location%2Cuser_relationships%2Cemail%2Cpublish_stream%2Coffline_access&client_id=[app_id] The following URL is being sought by the login attempt (I assume by the URL that the user has insufficient permissions): http://www.facebook.com/dialog/permissions.request?_path=permissions.request&app_id=[appid]&redirect_uri=fb[appid]%3A%3F%3Fauthorize&sdk=2&display=touch&type=user_agent&fbconnect=1&perms=user_location%2Cuser_relationships%2Cemail%2Cpublish_stream%2Coffline_access&sso=iphone-safari&from_login=1 I've checked that the Bundle ID listed in Xcode is the same as that listed for my app's settings in Facebook. Because the permissions page is not showing, new users cannot add the app. Old versions of my app that used to work are failing in the same way as well. What could be the problem? A: Okay, I'm feeling a bit stupid. The problem was that I had Sandboxing turned on in the app settings in the Facebook page. Why the error page was so obtuse is beyond me. * *In Facebook developer settings: https://developers.facebook.com, edit your app settings. *Select the "Advanced" tab, under "Settings" on the left side. *Make sure that "Sandbox Mode" is not enabled. A: I had the same problem, when my App ID was incorrect in Info Plist. <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>fb305639062848xxx</string> </array> </dict> </array> I found out, that not the Apple App ID must be put there, but Facebook App ID. (General in your app settings on Facebook developers web page, under App Name there are App ID and App Secret) There 3 last numbers are hidden by xxx. A: If the link you post is exactly the link in your application, then "redirect_uri" parameter is missing the letter "e". "fbconnect" as well. http://www.facebook.com/dialog/permissions.request?_path=permissions.request&app_id=[appid]&redirct_uri=fb[appid]%3A%3F%3Fauthorize&sdk=2&display=touch&type=user_agent&fbocnnect=1&perms=user_location%2Cuser_relationships%2Cemail%2Cpublish_stream%2Coffline_access&sso=iphone-safari&from_login=1 Besides, you should make sure that your [appid] is correct, and fb[appid]%3A%3F%3Fauthorize is the correct FB handler link of your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Help with filtered views across multiple pages! SHAREPOINT 2010 I'm rather new to this SharePoint stuff so be easy with me :) What I am trying to do is have one complete list with all documents (Shared Documents), each assigned a certain DocumentType (managed metadata), and then show only some of these files depending on each web page within sharepoint you look at. Now i know about key filters, but don't I have to set these each time i want to filter? I basically want a filtered view on metadata for each page all related to Shared Documents Thanks in advance :) A: Navigate the site containing list or library. Press "SiteAction"->"View all site content" and choose your list or library. In the ribbon choose "List"->"Create View"-> "Custom view in SP Designer".Create your personal view. After it, you can go to "List"-> Current view" and choose your view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How could i parse this HTML using Jquery? I want to parse HTML using Jquery I am getting some HTML from server as responseText like this : <html> <title>Title</title> <body> <p>My JSON data</p> </body> </html> Now i want to parse this using jquery parseJSON function, How could i do this plz help me. Thanks A: parseJSON is for parsing json if you are getting a valid html from the server then you can apply jquery's simple DOM traversal methods to it and get the desired object, or you can also use .parseXML to parse the html if it contains some non standard html tags A: If you simply create a jQuery object with the responseText, it will return a representation of the content in the body of your responseText, e.g. var jqobj = $('<html><head></head><body><p>Meep</p></body></html>'); var text = jqobj.html(); // returns "Meep" Then you can parse it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to stop a jQuery accordion change event when recreating it? I have three different accordions in three different dom elements, when I move one accordion section to another accordion section programmatically on a click of move button, I'm recreating all the accordions on the page. I want the selected accordion to be opened/expanded in the moved accordion. But the moved accordion is sometimes collapsed and other times expanded. I think this is happening because after recreating the accordion, it fires the change event and becomes collapsed. Can any one suggest a solution how to stop that accordion change event after recreating the accordion. I'm already using the suggestion in this post A: Store the accordion options in a variable so you can use it over and over again. Then, when you destroy the accordion, set which pane you want open/active (integer): accord_options.active = 3; // This is the number value of the accordion pane you want open. Accordion panes start at 0. $selector.accordion('destroy').accordion(accord_options); If you need further control over when the accordion fires, you can use an empty event in the accordion options: accord_options = { event: '', ... Then create a function to handle accordion clicks: $('#accordion_1 h3').click(function() { if (something_happens) { // we don't want the accordion to activate here return false; } // to activate an accordion pane: $selector.accordion('activate', $('#accordion_1 h3').index(this)); return false; } Add your own code to the above click method to handle whether or not you want an accordion pane to activate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cakephp: notice 8:undefined index: id error i'm getting Undefined index: id [APP\controllers\merry_parents_controller.php, line 31]Code debug($this->data['MerryParent']); echo 'id: '.$this->data['MerryParent']['id']; MerryParentsController::login() - APP\controllers\merry_parents_controller.php, line 31 Dispatcher::_invoke() - CORE\cake\dispatcher.php, line 204 Dispatcher::dispatch() - CORE\cake\dispatcher.php, line 171 [main] - APP\webroot\index.php, line 83 My code: merry_parents_controller.php if ($this->Auth->user()){ //debug($this->Auth->user()); $this->data['MerryParent']=$this->Auth->user(); debug($this->data['MerryParent']); echo 'id: '.$this->data['MerryParent']['id']; for debug($this->data['MerryParent']), the record is displaying fine: Array ( [MerryParent] => Array ( [id] => 2 [initial] => Ms [username] => hong [email] => hong7@yahoo.com [password2] => hong7 [landline] => [mobile] => 293472389472 [address] => dsaflkjasdlfk [state_id] => 5 [city_id] => 62 [postal_code] => 825729 [created] => 2011-08-02 10:29:59 [modified] => 2011-09-26 06:42:27 ) ) but when i try echo 'id: '.$this->data['MerryParent']['id']; i'm getting notice 8: undefined index error. I have no idea on what is the problem. Can someone please help me? A: Your array looks like this: Array ( [MerryParent] => Array ( [MerryParent] => Array ( [id] => 2 ... The id you're looking for is in $this->data['MerryParent']['MerryParent']['id']. You probably want $this->data = $this->Auth->user();
{ "language": "en", "url": "https://stackoverflow.com/questions/7553086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is best practice in IIS? One application pool for each application, or a shared application pool? In IIS 7, what is best practice? Should I create an application pool for each application, or should I share an application pool with as much application as possible? Are there any performance drawbacks or security issues related to one of the options? A: In theory it is better to put each site to its own pool. In practice it takes much more RAM than placing the sites to a single pool. So, on most servers you will see 10-100 pools only, even if there are 1000 sites. A: Each application pool is an instance of W3wp.exe, a worker process for that site or set of sites. By placing each application in a seperate app pool, you ensure that problems that could potentially cause problems within the app pool do not cause problems with other applications. There is obviously an overhead to operating like this in terms of resources. So generally, for simple sites and blogs I usually put these in a shared app pool. For more intensive or important applications, I seperate into individual app pools. This is just a guide to how I operate. I believe IIS7 now creates seperate app pools when you create a web site (not 100% though). A: Sharing Application pool is better than creating an application pool for each application for a fixed number of application You can run as many application pools on your IIS 7 server as you need but this will affect server performance.On the other hand Application pools allow a set of Web applications to share one or more similarly configured worker processes but you should not share an application pool to a lot of application.Because This will affect your server performance too! So in both way you have to be tactful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Joomla Questionnaire Component Customization? i developed a lawyer website and looking the below mentioned: I have 5 categories and each category have 40 questions(in 4 pages with/without mandatory options).all the questions are managed by admin only and the questions have checkbox,dropdown,radio button and so on. i searched for component in joomla 1.5,1.6,1.7 but i failed.no component can be found.any one help me to get rid of this problem. Please Recommend any component. Example: Categories: LLC (Limited Liability Company), DBA/Business Names Non-Profit Partnership Agreements Business Licenses Bylaws & Resolutions Certificate of Good Standing Certified Copies Compliance Calendar Conversion Corporate Minutes Corporate Supplies Entity Name Availability Check Entity Name Reservation These are the categories and each category have 40 questions in 10 pages.Each page have 4 questions.client(User) must answer these questions before make payment.i need to summary the answers typed by client(user). Each category have different 40 questions. please help me.am new to joomla. Thanks in advance. EDIT: Multi-Form Submit with progressbar component for free.please recommend this. A: I'm using ChronoForms 4 for simple questionnaire and it's very powerful, as not so user-friedly in admin configuration. The best feature is that you can customize every action on form showing and on form submitting. However I thik it's a bit hard to create a multipage form with this, but maybe in the forum some may answer, they reply very quicly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this pattern reconstitution or what is the name for this problem? I've following problem and don't know the terminology to describe it and hence search for possible solutions. I have a pivot table (matrix), eg each row and column have a named header. there is a defined set for rows and columns. Now let's assume that 10 rows are "combined" meaning each column is summed up to create a new "pattern". What I would like is a way to determine alternative row combinations that lead to the same or similar "combined" pattern. 1 1 1 5 5 5 "Combined" 6 6 6 alternate row combination: 2 2 2 4 4 4 Suggestions? How is this problem called? A: http://en.wikipedia.org/wiki/System_of_linear_equations#Matrix_equation I just have to transpose above matrix to get Matrix A [code] 1 5 1 5 1 5 [/code] combined matrix is a vector b: [code] 6 6 6 [/code] and x would be just a vector full of 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Modify `input` value HTML: <div class="mydiv"> My Div <ul> <li><input type="submit" value="first"/></li> <li><input type="submit" value="second (blah blah)"/></li> <li><input type="submit" value="third . blah blah"/></li> </ul> </div> How can I retrieve the value of the input and replace any '(' or '.' with a '\n'? The result would appear like: second (blah blah) A: Wrote this assuming you wanted to keep the separator as your exemple implied, you can see it working here. $(document).ready(function(){ $('.mydiv input[type=submit]').each(function() { $this = $(this); $this.val($this.val().replace(/(\.|\()/, '\n$1')); }); }); EDIT: @vzwick: regarding your edit no, it shouldn't be a one-liner, I'm caching $this on purpose. A: That should do the trick: $(document).ready(function(){ $('.mydiv input').each(function(i,e){ $(e).val($(e).val().replace('(', '\n').replace('.', '\n')) }); }); Also, keep in mind, that this might/will cause problems with rendering in some browsers (i.e. WebKit doesn't resize the input). http://jsfiddle.net/YTD9p/
{ "language": "en", "url": "https://stackoverflow.com/questions/7553096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Index on Multiple tables, can it be done? Been searching for a solution for a while now, go to (1) or (2) to skip description, first i will explain the situation. My firm have upgraded our erp. system, my primary work is to create lists used by others in the firm, i take all my data from this systems database during upgrade we got some data converted to match the new version, some of it was left behind, some of it was not tampered with and just directly exported to the new database, its on a separate server, basically its a success, the new ERP. system works as supposed, however a lot of my lists have been broken, the data my lists use is missing/partly_missing/all_there okay so the problem is missing data i need from the old database, okay a union on new and old database should be able to do that, however i do not want duplicate records, "data that was converted to the new database also exist in the old database" therefore two fields could exist "they do, i tried it" so 2. version of my solution i am lacking primary keys "iseries database" so i went concatting a combination of feilds making a uniqe key, "takes too long to explain how i did that" however it ends up in me making a view with a union on two databases, making sure no records exist two times, (1) so this is what i got now, a view of the combination of old and new table data all built with checks on a "uniqe" key.... every time i need data that has been effected of the upgrade i must run a expensive query on each table, "some using these views more than 40 times" (Question1) how can i "cost effective" take data from two different schemas/databases and bind together? (2) the only thing i can think of giving me this performance is to make indexes instead of these views that i built, however until now i haven't been able to find any information on how to, (Question2) Can i create a index over two tables, my database is as/400 - iseries however i am interested in a solution up against any database type, i am very flexible with resources :EDIT: code that is used to create view with slight modification, SELECT CTCONO, CTDIVI, CTSTCO, CTSTKY, CTLNCD, CTTX40, CTTX15, CTPARM, CTTXID, CTRGDT, CTRGTM, CTLMDT, CTCHNO, CTCHID FROM NEWDB.CSYTAB UNION SELECT * FROM OLDDB.CSYTAB WHERE ( CTCONO,CTDIVI,CTSTCO,CTSTKY,CTLNCD ) NOT IN ( SELECT A.CTCONO,A.CTDIVI,A.CTSTCO,A.CTSTKY,A.CTLNCD FROM NEWDB.CSYTAB A, OLDDB.CSYTAB B WHERE A.CTCONO = B.CTCONO AND A.CTDIVI = B.CTDIVI AND A.CTSTCO = B.CTSTCO AND A.CTSTKY = B.CTSTKY AND A.CTLNCD = B.CTLNCD ) A: The answer is no. I can't create a index on multiple tables. My solution would be to make a table instead, and in my case a view also, or I could just optimize the SQL code. EDIT I just learned that in MS (at least the 2012 version) you can create indexed views. So in my case I would turn my views into indexed views, and get a huge performance upgrade. A: Make a new table that stores the value of your expensive query, then if you're going to always ignore the older data in general if there's a record in the new DB for it. Then just add in some triggers to update this new table when the other tables get updated. Perhaps, a better question would be to provide your schema, and current expensive query then ask for people to help make it faster. Edit: now you have posted your table I see one thing you could improve, make the second part of your query this: ... UNION SELECT * FROM OLDDB.CSYTAB B WHERE NOT EXISTS( SELECT TOP 1 1 FROM NEWDB.CSYTAB A WHERE A.CTCONO = B.CTCONO AND A.CTDIVI = B.CTDIVI AND A.CTSTCO = B.CTSTCO AND A.CTSTKY = B.CTSTKY AND A.CTLNCD = B.CTLNCD ) Then provided you have a single index that spans { CTCONO,CTDIVI,CTSTCO,CTSTKY,CTLNCD } in the NEWDB.CSYTAB then it should be much better performance than what you're getting currently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Linking error in MSVC 2008 I have a file structure like this: file1.h extern const char *build_info[][3]; file1.cpp #include "file1.h" const char *build_info[][3] = { { "abc", "de", "feg" }, { ... }, ... }; file2.cpp // Use build_info Now I am getting this erro under MSVC 2008 Express file2.obj : error LNK2001: unresolved external symbol "char const * (* build_info)[3]" Looks like I am not able to link file1.obj. Any idea how I can verify: * *Whether the obj is linked. *It has the symbol defined. A: Okay I found the problem, file1.cpp was actually file.c. Only I enclosed that in extern C { .. } it is working fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to call a Date picker dialog inside the Dialog's button I have created an Activity which has a dialog, this dialog has an EditText field with Button. Now, on button click I have to show a Date Picker. How can I do this? A: public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); builder.setMessage("Are you sure? Continue will exit the app") .setCancelable(false) .setPositiveButton("Continue & exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Add your data picker code here. } }) .setNegativeButton("Return", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7553105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete link disappears in Django admin inline formset if ValidationError raised I have a form with KeywordInline. When I add new object using the form inlined formset has a js-link to add new form into formset. Newly added forms have a js-enabled delete button (x mark on the right). KeywordInline class KeywordInline(admin.TabularInline): fields = ('word',) model = models.Keyword formset = forms.KeywordFromset verbose_name = _('Keyword') verbose_name_plural = _('Keywords') extra = 1 can_delete = True def get_readonly_fields(self, request, obj=None): if obj: if str(obj.status) == 'Finished': self.extra = 0 self.can_delete = False self.max_num = obj.keyword_set.count() return ('word',) self.extra = 1 self.can_delete = True self.max_num = None return [] KeywordFromset class KeywordFromset(BaseInlineFormSet): def clean(self): super(KeywordFromset, self).clean() formset_keywords = set() for form in self.forms: if not getattr(form, 'cleaned_data', {}).get('word', None): keyword = None else: keyword = form.cleaned_data['word'] if keyword in formset_keywords: form._errors['word'] = ErrorList([_(self.get_unique_error_message([_('Keyword')]))]) else: formset_keywords.add(keyword) Now if I hit save button and ValidationError rises those delete buttons disappears from fromset. So if I've added wrong keyword mistakenly I cannot delete it. Is this normal behaviour? And how can I make delete links persist? Any help is much appreciated. A: There's no delete link for the inlines that triggered ValidationError since they aren't yet saved to a database, hence no delete link. I realize it's inconsistent behavior (since you can delete those rows before hitting "save" button, but you can't once they triggered validation errors), but its normal, default way of how Django does it. To fix this, you could override the template for inline and make the delete buttons appear despite validation errors. A: I have this issue with django 2.2 First (NOT WORKING) I try to create delete link * *duplicate admin/edit_inline/tabular.html to edit in project *change to use new template class MyAdminInline(admin.TabularInline): # ... other stuff template = 'admin/edit_inline/tabular.html' *add somescript {% load i18n admin_urls static admin_modify %} <script type="text/javascript"> function removeRowById(id, index) { document.getElementById(id).remove(); } </script> *edit how to display delete link <td class="delete"> {% if inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }}{% endif %} {% if not inline_admin_form.original %} <div><a class="inline-deletelink" onclick="removeRowById('{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}', {{ forloop.counter0 }})">Remove</a></div> {% endif %} </td> *it shows the links button but when saved. django throw another error to me. so this way not update inside the inline_admin_formset Second (WORKING) I try another way * *just change how delete checkbox appear from <td class="delete"> {% if inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }}{% endif %} </td> to <td class="delete"> {% if inline_admin_form.original %}{{ inline_admin_form.deletion_field.field }} {% elif not inline_admin_form.original %} {% if inline_admin_form.form.non_field_errors %} {{ inline_admin_form.deletion_field.field }} {% endif %} {% endif %} </td> to display delete checkbox if field is not original (has pk) and has validation error on it
{ "language": "en", "url": "https://stackoverflow.com/questions/7553108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Information about user how liked my page/group After a user clicked on a "like" button of a facebook group or facebook page is it possible to get any addional information about the user beside name and uid? I know with an app I can request access to a lot of data but I don't want to do that. I also know about facebook statistics. The question targets more at the point if I publish any information about me if I like something. A: The user ID isn't included in the callback on the edge.create event when a user clicks like, so the page doesn't get it then. If you get a user ID via the user authorising your app you can access their public information at https://graph.facebook.com/ but you'll need them to allow additional permissions to see anything which wouldn't be accessible to a logged-out user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Page Curl Animation on Android with OpenGL-ES I want to achieve a nice 3D page curl animation in Android. I read some articles and found that nice effect can be achieved by OpenGL-ES so I started to learn OpenGL-ES (I did some of tutorials of OpenGL-ES and am still continuing) but I found it too complex for me to achieve this functionality. Also I got some examples which are available on StackOverflow and on the net, they work but I am not able to understand it, can someone guide me to achieve this functionality? A: Based on the question comments I have an answer to this question. YES, you can do that with OpenGL, BUT you need a deep understanding of math and graphics. This is a lot to learn, this will cost you at least a couple of weeks and it's definitely a hard path to go if you do it only because of this single animation (all of this applies if you don't take code which you probably won't understand and another human being put his whole effort into). Nevertheless there might a ready to use implementation but unfortunately I can't present you one because I don't know if there's any out there. Update You callenged me, so I was eger to know whether there is something out there (because I saw that before and couldn't believe that there isn't a project out there which already does that for you). And actually I found this question which seems to address the very same issue. And yes, there's someone who published his results here. And I have to admit: I looks awesome. It's also a pure java implementation. But still: Having some background knowledge about OpenGL would enhance your whole attitude as developer. I'm not saying it's a must because not every one will succeed in OpenGL programming because it's quite hard to learn and implies a lot of math. But I think it's worth it because you will gain some deep understanding of current and all future graphical interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to center a button (.NET Compact Framework) I want to centre a button in .NET Compact Framework. I dont see any property like StartPosition in .NET CF Form object. Can someone please suggest me how to centre button in .NET CF 3.5? A: You mean you want to center the button in it's container along these lines? myButton.Left = myButton.Parent.Left + (myButton.Width / 2);
{ "language": "en", "url": "https://stackoverflow.com/questions/7553115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Received memory warning. Level=2 &Level =1 in cocos2d I am getting "Received memory warning. Level=2 &Level =1 " while playing my game third time. I have already cleared all texture that used in the game ? what should i do ? A: Using instruments is probably a good first step to see how much memory you are allocating exactly and at what point in code execution those allocations are happening. You'll probably also want to take a look for leaks in instruments. If your're getting memory warnings after a third time playing seems like some memory is not being freed that probably should be. Are you creating sprites, textures or other large pieces of data every time you play?
{ "language": "en", "url": "https://stackoverflow.com/questions/7553117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why don't my user controls render? I've created a set of user controls in vb.net and in their original project they work fine. I've since created a user control library dll and I wish to use it in a new project. I add the reference to the dll fine, specify the tag library in an asp.net page fine and define controls on the page fine. Everything seems to work except I get no rendered output. Various properies of the controls and the page_load methods are all called. Asp.net trace shows the controls in the page hierarchy etc Just no output where the controls should be - any suggestions? Update 1 I just compared a trace of the working output compared to the non working. The working output contains the user controls (and all elements in them) The non working output only lists the user controls - no content It therefore seems that the content of the controls is missing somehow - as if the markup is not being compiled with the codebehind, only the codebehind seems to be working. Update 2 The controls are inheriting from UserControl not control. A: I assume that you are not confusing between user control (.ascx) and custom controls. For user controls to work, one needs both ascx (mark-up file) along with corresponding code-behind class. User control are typically consists of constituent child controls whose hierarchy is specified within ascx file that provides some UI. In a class library (dll) project, you cannot package ascx files - all you get is the code-behind class. Without ascx, the code-behind class will not have any child controls and hence will render empty. In short, you cannot package user controls (ascx) in a class library - you have to add them into your actual web project. For shared control, one has to use custom controls. Custom controls are code-only and typically provides render override that emits necessary html (or creates the own child control tree dynamically). These controls can be package as a class library and shared across project. Typically, a custom control will also have other helper classes to provide design time assistance (UI Editors etc). A: You are correct in your summarization in Update 1- your markup has not been included! You need to provide a bit of elbow grease if your trying to distribute .ascx controls in a .dll but not too much thankfully. The two main things you need to do: * *Embedded your .ascx controls. The .ascx controls need to be marked as an embedded resource in your .dll (as oppossed to 'content') *Create a VirtualPathProvider. This will allow you to load the ascx files directly from the dll they are embedded in. Unfortunately explaining step 2 is slightly lengthy, however this excellent article helped me out in doing exactly what you want to do. The beauty of distributing .ascx controls like this is that you dont have to tear your hair out writing custom controls (rendering anything over than very simple html is a nightmare to make sense of).
{ "language": "en", "url": "https://stackoverflow.com/questions/7553118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merging the keys of two dictionaries What is the best way to merge only the keys of two dictionaries? For example we have: private readonly IDictionary<string, string> _dictionary1= new Dictionary<string, string>{{"1","one"},{"2","two"}}; private readonly IDictionary<string, string> _dictionary2 = new Dictionary<string, string>(){{"3","three"}}; What I want to receive is the list containing {"1","2","3"}. A: Just combine to Key arrays: var a = _dictionary1.Keys.Union(_dictionary2.Keys); A: UNIQUE keys using Enumerable.Union() method: var mergedKeys = _dictionary1.Keys.Union(_dictionary2.Keys); ALL keys using Enumerable.Concat() method: var mergedKeys = _dictionary1.Keys.Concat(_dictionary2.Keys); A: Look at Concat and Union methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GWT fails to create XML elment I'm creating a XML structure basically like this one: Create XML document on GWT client side (first anser). It works fine in 99% of the cases but sometimes, after running for a while, it randomly fails with the follwoing messages: com.google.gwt.dev.shell.HostedModeException: Something other than a short was returned from JSNI method '@com.google.gwt.xml.client.impl.XMLParserImpl::getNodeType(Lcom/google/gwt/core/client/JavaScriptObject;)': JS value of type JavaScript object(2608), expected short at com.google.gwt.dev.shell.JsValueGlue.getIntRange(JsValueGlue.java:266) at com.google.gwt.dev.shell.JsValueGlue.get(JsValueGlue.java:154) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeShort(ModuleSpace.java:279) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeShort(JavaScriptHost.java:99) at com.google.gwt.xml.client.impl.XMLParserImpl.getNodeType(XMLParserImpl.java) at com.google.gwt.xml.client.impl.NodeImpl.build(NodeImpl.java:41) at com.google.gwt.xml.client.impl.NodeImpl.appendChild(NodeImpl.java:82) It's not at the same element but could be at any elment, even after it create 3 of the same kind successfully before. Is that a known problem and does it only happen in debugg mode? A: Seen this error many times, i have feeling it has something to do with how classes are reloaded in GWT dev mode. Never seen it to happen on production mode. There are some other cases when this error can appear(like using window.alert in JSNI), but most of the time it only means that you have to restart dev mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encoding is not giving the right result in objective c I have a c# code which encodes a string. I am trying to write a corresponding routine in objective c. The code is as follows: // c# code public static string Encode(Guid guid) { string encode = convert.ToBase64String(guid.ToByteArray()); encode = encoded.Replace("/","_").Replace("+","-"); return encoded.substring(0,22); } I have written this code in objective c. - (NSString *)encode:(NSString *)inId { NSString *uniqueId = inId; // convert user id in to data NSData *userIdData = [uniqueId dataUsingEncoding:NSUTF16StringEncoding]; // convert encoded userId's data into base64EncodedString NSString *base64String = [Base64 encode:userIdData]; //NSString *base64String = [userIdData encodeBase64ForData]; NSString *encodedId = [[NSString alloc] initWithString:base64String]; // replace "/" character in base64String into "_" character encodedId = [encodedId stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; // replace "+" character in base64String into "-" character encodedId = [encodedId stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; // get substring of range 22 encodedId = [encodedId substringToIndex:22]; NSLog(@"Base 64 encoded = %@",encodedId); return encodedId; } I am calling this function from viewDidLoad NSString *encodedStr = [self encode:@"a8f9f344-d14e-4541-a8e7-0f5936e42254"];// string to encode NSLog(@"Encoded String %@",encodedStr); this code is not giving me the correct result i want for eg:for the string a8f9f344-d14e-4541-a8e7-0f5936e42254 it should give result as RPP5qE7RQUWo5w9ZNuQiVA. Thanks. A: Your problem is that guid.ToByteArray() and [uniqueId dataUsingEncoding:NSUTF16StringEncoding]; do not do the same thing. As far as I can tell from the documentation, the former removes the hyphens and treats the rest as the hex ASCII representation of 16 bytes. The latter just turns each character into UTF16 (actually, it is UTF-16 already) and puts it into an NSData. You need to write some code in Objective-C to take an ASCII Hex string and convert it into bytes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does it matter what color format an image has when saving it as PNG? I am creating tiles for a larger image and I'm saving them to disk. Question: Is there any way I can optimize the image so that reading and decompressing the PNG from disk is faster? Possibly by changing the order or color bytes in the color space on a custom bitmap context from which the image is saved? UIImage *fullSizeImage = [self cachedImageWithURL:imageURL]; CGRect tileRect = (CGRect){{column*tileSize.width, row*tileSize.height}, {tileSize.width, tileSize.height}}; CGRect totalRect = (CGRect){CGPointZero, fullSizeImage.size}; tileRect = CGRectIntersection(tileRect, totalRect); CGImageRef tileImage = CGImageCreateWithImageInRect([fullSizeImage CGImage], tileRect); UIImage *retImage = [UIImage imageWithCGImage:tileImage]; [self.cache setObject:retImage forKey:cacheURL cost:0]; [retImage savePNGAsyncToURL:cacheURL]; A: I've benchmarked this, and it looks that speed is closely correlated to file size (smaller file is faster): http://imageoptim.com/tweetbot.html If you're OK with lossy compression, then use pngquant to create those files. At 8bpp they'll have 1/4th of data to begin with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: improper act in web page I have a web page that contain login control, I face a problem : The code behind not matched to the design.For example , it gives me an error Login1 cannot be found in the current context And when I try to add event to the login it is written as the following: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void LoginButton_Click(object sender, EventArgs e) { } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { height: 28px; } </style> </head> <body > <form id="form1" runat="server"> Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" /> <div> </div> <asp:Login ID="Login1" runat="server" onauthenticate="Login1_Authenticate"> <LayoutTemplate> <table border="0" cellpadding="1" cellspacing="0" style="border-collapse:collapse;"> <tr> <td> <table border="0" cellpadding="0"> <tr> <td align="center" colspan="2"> Log In</td> </tr> <tr> <td align="right"> <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label> </td> <td> <asp:TextBox ID="UserName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label> </td> <td> <asp:TextBox ID="Password" runat="server" TextMode="Password" ></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td colspan="2"> <asp:CheckBox ID="RememberMe" runat="server" Text="Remember me next time." /> </td> </tr> <tr> <td align="center" colspan="2" style="color:Red;"> <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal> </td> </tr> <tr> <td align="right" colspan="2" class="style1"> <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="Login1" onclick="LoginButton_Click" /> </td> </tr> </table> </td> </tr> </table> </LayoutTemplate> </asp:Login> </form> </body> </html> Any idea to solve this problem , the big problem is that the code doesn't see the design and vise verse A: Firstly : Make sure that your name space is : WebApplication4 and the class name is: _Default in your code behind file.like this: namespace WebApplication4 { public partial class _Default : System.Web.UI.Page { } } secondly: Make sure the consistency of the .aspx.designer.cs file. I mean make sure that there is a reference of your control in this file .like this: protected global::System.Web.UI.WebControls.Login Login1; and tell us which Visual studio version does u use. A: It sounds like the designer.cs file is out of sync. If you go into the designer.cs file, you can declare the control, like this: /// <summary> /// Login1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Login Login1; You might also try cutting and pasting the markup, so the designer registers all of the controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding out the call site from hex representation I'm trying to analyse a crash dump of MS BizTalk service, which is constantly consuming 100% CPU (and I assume that's because of our code :) ). I have a couple of dumps and the stack trace of the busiest threads looks similar - the only problem is, that the top of the stack seems to be missing symbols. It looks like this: 0x642`810b2fd0 So, the question is - how can I find out the module/function from this address? (or at least the module, so that I know what symbol file is missing). A: lm in WinDbg dumps list of modules. In your case WinDbg does not find any modules that occupy this address -- otherwise it would have printed +. Some of the libraries generate code dynamically, in this case the body of the function will be placed in the heap and won't have any symbols or even module associated with it. I know MCF at some point did this. I suggest you try to analyze the frames at the top of the stack that have symbols and try to find out what they might be doing. A: Wish I could help more, but the only thing I can suggest is reading this cheat sheet of WinDbg commands. There is one command wt which has a list of params which could help with getting module information about that call site. Let me know if this is any use for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Redirect all file reading and writing I'm using a virtual file system (PhysFS) in my application. Is there any way to redirect all file reading and writing through this virtual file system? I would like everything to be redirected, such that even third-party libraries go through this file system. Is there something similar to rdbuf, but for all file IO, both though C++ streams and the old C FILE objects? Edit: OS dependent The platform I'm currently interested in is Windows, so I'd like to know how this can be don with the WinAPI. Also, is file redirection a common feature of OSes? A: Only through an operating-system specific API, you might be able to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding the Server Redirects as a result of a jQuery Post I would like to post a serialized form like the one in the following url http://api.jquery.com/jQuery.post/ And i need to figure out whether there is a redirect, if the application to which i post the data has been timed out [auto logoff] from jquery, so i would like to have like this $.post("getData", serializedForm, function(data){ process(data);}, statusCode:{ 302 : { function() { alert("your request has been timed out, re-login to continue further"); } } }); This kind of code is not working.. any workarounds in this case. Also suggest me a suitable way to find redirects when i request data using $.getJSON from jQuery. A: You've got your synthax messed up. Try this: $.post("getData", serializedForm, function(data, textStatus){ if (textStatus === 302) { alert("your request has been timed out, re-login to continue further"); return; } process(data); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7553135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create simple xml in Java I am trying to build server that sends a xml file to client. I am getting info from db and wants to build from that xml file. But I have a problem with: DocumentBuilder documentBuilder = null; Document doc =documentBuilder.newDocument(); I am getting NullPointerException. Here is me full code: public void createXmlTree() throws Exception { //This method creates an element node DocumentBuilder documentBuilder = null; Document doc =documentBuilder.newDocument(); Element root = doc.createElement("items"); //adding a node after the last child node of the specified node. doc.appendChild(root); for(int i=0;i<db.stories.size();i++){ Element child = doc.createElement("item"); root.appendChild(child); Element child1 = doc.createElement("title"); child.appendChild(child1); Text text = doc.createTextNode(db.stories.get(i).title); child1.appendChild(text); //Comment comment = doc.createComment("Employee in roseindia"); //child.appendChild(comment); Element child2 = doc.createElement("date"); child.appendChild(child2); Text text2 = doc.createTextNode(db.stories.get(i).date); child2.appendChild(text2); Element child3 = doc.createElement("text"); child.appendChild(child3); Text text3 = doc.createTextNode(db.stories.get(i).text); child3.appendChild(text3); root.appendChild(child3); A: Well yes, you would get a NullPointerException. You're calling a method on a null reference - very clearly, given that you've assigned the documentBuilder a null value on the line before. You need to get an instance of DocumentBuilder to start with. For example: DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); A: of course you are getting a NullPointerException, your DocumentBuilder is null. Try instantiating it first. // Step 1: create a DocumentBuilderFactory DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // Step 2: create a DocumentBuilder DocumentBuilder db = dbf.newDocumentBuilder(); A: Guys are right about DocumentBuilder. But may I offer you other solution? Your servlet mostly deals with generating of XML itself, i.e. produces kind of markup. This is the purpose of JSP. You can implement simple JSP page that will actually contain template of your XML and some code that inserts dynamic data. This is much simpler and easier to maintain. Yes, JSP typically generate HTML but no-one said that they cannot generate XML or any other text format. Just do not forget to set content type to text/xml. A: Do you really need to write you XML manually? Do you have the XSD of the XML you want to write? Because, it would be easier to generate some classes using XJC/JAXB and use the marshaller to write your XML file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add/modify the 'Description' property value for LinkTable in VBA? I have a LinkTable which points to an existing table of SQL server in my Access database. I need to change the 'Description' property value for that table link. I had tried many ways but failed to do that. Can any any one help me in this regard ? A: Some notes. Dim db As DAO.Database Dim tdf As TableDef Set db = CurrentDb Set tdf = db.TableDefs("Table1") On Error Resume Next tdf.Properties("Description") = "Link" If Err.Number = 3270 Then 'property not found Set prp = tdf.CreateProperty("Description", dbText, "Link") tdf.Properties.Append prp End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7553139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Java limit at json format I want to transfer some database data through a TCP socket. The data is formatted to JSON. Since the database size might grow, I'm afraid that the String object maximum size will not be enough to store the entire data with JSON formatting. I already had an problem transferring the data using the DataOutput function writeUTF(). What should I do? Maybe convert the database rows to CSV and transfer it through the Internet line by line? Or do I not need to worry about String limits and solve the writeUTF() problem by getting the bytes of the String, transferring them through the socket and rebuilding the String from the bytes at the destination? A: Java strings can be extremely long - you're unlikely to run into problems with the String type itself. If you convert the string to binary first, then use writeInt to write the number of bytes, then the bytes themselves, that should be fine. The problem with writeUTF is that it uses writeShort, so it only handles up to 64K of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java AWT: Remove frame title bar and add customised title Bar I am new to AWT and was wondering how to remove the title bar that comes up when we open a frame and add customised title bar. Though I was able to remove Tiltle Bar using setUndecorated(true) but not getting a idea how to add a Custom Title bar with just a ICON and Close Operartion. Also I need to color the Title Bar with a specific color. P.S : Cannot use Swing Thanks in Advance !!! A: You have 2 possibilities. * *Use java.awt.Window instead of Frame. *Use JFrame and call frame.setUndecorated(true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7553146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aptana - Different PHP projects same deploy directory I have a PHP project in Aptana which files I want to share with others projects. I can do this by properties project -> resources -> linked resources. But I want to deploy on the server this project in all the projects that share this. For example: Project 1) CMS library (/cms), Project 1 Web Site (w/eb1), Project 2 another web site (/web2). On the server I need: web/cms and web2/cms without need to copy manually cms folder into web1 and web2. It's that possible? A: Yes. If you using linux then just make links to your needed folders. If you using windows try making shortcuts to that folder. I think that should work. EDIT: This will help you: Windows XP vs Vista: NTFS Junction points
{ "language": "en", "url": "https://stackoverflow.com/questions/7553147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting next submit after actual textarea and disable it I have various instances of a form in a page. I want to desactivate the submit button of that ones with the default text in the textarea. My actual code is: // This works $(".proposal-write-comment-submit").each(function(){ var element = $(this).closest(".proposal-write-comment-textarea"); var default_text = element.attr("data-default"); var value_text = element.val(); if(default_text == value_text) { $(this).attr("disabled","disabled"); } }); // This no $(".proposal-write-comment-textarea").keypress(function(e){ var default_text = $(this).attr("data-default"); var value_text = $(this).val(); if(default_text == value_text) { $(this).closest(".proposal-write-comment-submit").attr("disabled","disabled"); } else { $(this).closest(".proposal-write-comment-submit").removeAttr("disabled"); } }); My HTML code: <form class="proposal-write-comment" method="post" action=""> <textarea class="proposal-write-comment-textarea" data-default="Write a comment...">Write a comment...</textarea> <input class="proposal-write-comment-submit" type="submit" value="Save" /> </form> The second part of the javascript doesn't works. How I can select right the submit buttons "next to" the textarea? Thank you in advance! A: You could try the 'siblings' selector - if(default_text == value_text) { $(this).siblings(".proposal-write-comment-submit").attr("disabled","disabled"); } else { $(this).siblings(".proposal-write-comment-submit").removeAttr("disabled"); } A: closest looks up the DOM tree, at parents and ancestors, rather than at siblings. As the input element is a sibling of the textarea element, you need to look at siblings. To do that, you could use next, (assuming the input always directly follows the textarea... if not, you could use nextAll or siblings with the appropriate selector) $(this).next().removeAttr("disabled");
{ "language": "en", "url": "https://stackoverflow.com/questions/7553148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: defining alphabets as numbers not working inside loop Please check my code below,it returns 0 while I am expecting a result 14.But when I add A+D manually it returns 5.Am i doing something wrong inside the loop ? <?php define('A',1); define('B',2); define('C',3); define('D',4); define('E',5); //echo A+D; returns 5 $name = 'EACE'; $len = strlen($name); for($i = 0; $i<=$len; $i++) { $val += $name[$i]; } echo $val; //returns 0 ?> A: You need to use constant(..) to get the value of a constant by name. Try this: for ($i = 0; $i < strlen($name); $i++) { $val += constant($name[$i]); } A: define('A',1); define('B',2); define('C',3); define('D',4); define('E',5); //echo A+D; returns 5 $name = 'EACE'; $len = strlen($name); $val = null; for($i = 0; $i<=$len-1; $i++) { $val += constant($name[$i]); } echo $val;
{ "language": "en", "url": "https://stackoverflow.com/questions/7553149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java proxy settings I have global proxy settings made from Java control applet. It takes proxy settings from browser. I need to run a Java application that does not use global proxy settings, it has to use direct connection. How can I do it with command line arguments? A: Did you have a look here: http://download.oracle.com/javase/6/docs/technotes/guides/net/proxies.html ? You can set the system properties from the command line: java ... -Dhttp.proxyHost=your-proxy.example.com ... A: open java control panel using javaws -viewer General-> Network Settings -> direct Connetcion now direct connection is set
{ "language": "en", "url": "https://stackoverflow.com/questions/7553150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mysql file upload error? Here is my code to upload a file. Everything is working perfect. This code uploads the file to destination folder and MySQL query work perfect and insert all data into their relative fields in database. But it is not going to the page which is mentioned in header() function. It gives me an error at the end like this Error: please try again, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1 I think it occurs when last if($exe) is executed <?php include('./includes/connection.php'); if(!$_POST['song_name']){ header('location: pro_add.php'); exit; } $path = "../upload_data/"; $uniqid = uniqid(strtotime('now')); $uniq_name = $uniqid .'_'. $_FILES['file']['name']; $complete_path = $path . $uniq_name; $move = move_uploaded_file($_FILES['file']['tmp_name'],$complete_path); if(!$move){ echo 'Error: please try again'."<br/>"; } $query = mysql_query("INSERT INTO products SET sub_cat_id='".$_POST['sub_cat_id']."', song_name='".$_POST['song_name']."', artist='".$_POST['artist']."', path='".$complete_path."' "); $exe = mysql_query($query); if($exe){ header('location: products.php'); exit; }else{ echo 'Error: please try again, <br />' . mysql_error(); } ?> A: You are querying the result of your query: $query = mysql_query('...'); $exe = mysql_query($query); Just replace $query = mysql_query('...'); with $exe = mysql_query('...') and it should work. EDIT As commenters on your question also pointed out, your script is extremely vulnerable to SQL Injection. You should read up on that before putting this online. http://en.wikipedia.org/wiki/SQL_injection http://php.net/manual/en/security.database.sql-injection.php A: code is fine but it has only one problem. may be it has gone out of your mind... $query = mysql_query("INSERT INTO products SET sub_cat_id='".$_POST['sub_cat_id']."', song_name='".$_POST['song_name']."', artist='".$_POST['artist']."', path='".$complete_path."' "); instead of this you should write $query = "INSERT INTO products SET sub_cat_id='".$_POST['sub_cat_id']."', song_name='".$_POST['song_name']."', artist='".$_POST['artist']."', path='".$complete_path."'"; it will work fine if you replace this much of code..
{ "language": "en", "url": "https://stackoverflow.com/questions/7553158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get new profile cover with sdk Is it possible to get and to change the new porfile cover (mine or my friends' profil cover) with the sdk php or JS ? A: It is possible to get the Facebook's user cover image using the Graph API. You have to add 'fields=cover' to the user request. The response is an array of fields id, source, and offset_y. You need an access token for this. You cannot update the cover photo using the API, only retrieve it. http://graph.facebook.com/[USER_ID]?fields=cover A: It's still not possible with the current APIs exposed by Facebook.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to enable Spring Security Annotations not using app-Context.xml file? I've implemented my Application using SecurityContextImpl as SecurityContext. anything works well (Authentication and Authorization). Now I want to use Spring Security Annotations (@Secured , ...) , I my searched result in a single comment :"USE in your context.xml file" is there any other way to embed security annotations using non-file-based ContextImpls? A: Here's the config snippet you need. Not sure why you don't want to enable via XML. <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns:security="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <security:global-method-security secured-annotations="enabled" /> </beans:beans>
{ "language": "en", "url": "https://stackoverflow.com/questions/7553163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you set up github version control for a team of two? We're trying to set up github version control for a Jsp-project in NetBeans 7.0.1. The problem is we don't have a clue what to do. I Have set up a public account on github and done all the steps in the install guide on github, ssh keys and everything. So if I wanted to work on my own in this project I wouldn't have a problem. The problem is how to get my collaborator started. He has an account on github. he set it up with ssh keys and such. In the admin view on github I added him as a collaborator, but we don't know the next step. So the question is how to connect the collaborator to the project? something like this I suppose? git remote add origin git@github.com:username/Hello-World.git git pull (another question: Do I git only the source files or the whole project folder?) A: For the first access, what your collaborator should be able to do is a git clone of your repository. That will set for him the remote address. If he is declared as a collaborator, he then should be able to push/pull to that remote repo. Note that your collaborator should have received a push notification access. A: Regarding your second question... That's a tough one. A few months ago I was working with a colleague on a JavaEE project and we initially decided to share the whole Eclipse project. Since I was working on Windows and he was working on Linux, we had much trouble maintaining everything. Also we had to make sure that we don't accidentally push up our .project dir, because that would overwrite the settings on the other persons machine, messing up the whole project. So we ended up removing all the project files from the repository and just keeping the source folders (src and WebContent). Both of us set up an empty project, made our settings and than imported the source code from the repository. Was some trouble setting it up until everybody had the same project settings, but afterwards it worked like a charm. For just two developers that is fine, I guess for a bigger team, there might be better solutions. So, I guess Netbeans handles the project settings in a similar way. So in my opinion you should just share the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SilkTest : Navigate to Browser Instance1 I login as User1 from Browser- instance1, then login as User2 from same browser Instance2, how can I go back to Browser- instance1? Browser: IE6-7 A: Assuming you are using the Open Agent, you should be able to access the windows with Desktop.Find("//BrowserApplication[1]") and Desktop.Find("//BrowserApplication[2]"). Alternatively, if the browsers have distinct captions, you can use Desktop.Find("//BrowserApplication[@caption='Distinct Caption']")
{ "language": "en", "url": "https://stackoverflow.com/questions/7553172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to filter all the posts that don't have one of the IDs in the favoiritePosts array? I want to filter all the posts that don't have one of the IDs in the favoritePosts array. I tried this but it doesn't work: [NSPredicate predicateWithFormat:@"postID IN %@",favoritesPosts_]; I get this error: 'Invalid predicate: nil RHS' Any ideas on how to write the predicate correctly? The array is made of a NSNumber objects and i want to filter my tableview's fetchResultController with this predicate. the Post object has a PostID attribute which is of the NSNumber type. Maybe thats not the way to do that.. The objective is to show in the tableview which is controlled by the fetchResultsController only the posts that their ids are in the favoritesPosts_ array. So if someone has a different idea on how to do that i will appreciate it. A: If favoritesPosts_ is a string array containing the post IDs, then you can very well use the predicate you have created, predicateWithFormat:@"postID IN %@", favoritesPosts_]; But if favoritesPosts_ contains objects which have a property, say, postID, then your predicate should be, predicateWithFormat:@"postID IN %@", [favoritesPosts_ valueForKey:@"postID"]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7553177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to populate a property that is not directly stored in Database with CodeFirst I have 2 Entities, each of which is managed by EF Code First, and each happily sitting in its own table. Entity_A has a property, called "SumTotal", which should be the sum of a specific column in Entity_B that matches a certain criteria. SumTotal should not be persisted in the DB, but rather calculated each time an instance of Entity_A is retrieved. I have looked at ComputedColumns, but it appears that the computedcolumn can only be defined relative to columns in the same table. I also have a feeling that I need to set SumTotal to NotMapped (or something similar with AutoGenerated), but dont know how to get the actual value into SumTotal. Hope this question makes sense, thanks in advance A: You can project the results to an anonymous object and transform that it to your entity var projection = db.EntityAs.Where(/* */) .Select(a => new {A = a, Sum = a.Bs.Sum(b => b.Total)}) foreach(p in projection) { p.A.SumTotal = p.Sum; } var As = projection.Select(p => p.A);
{ "language": "en", "url": "https://stackoverflow.com/questions/7553180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure the "Assign To" list in mantis When a reporter creates a bug , in the "Assign To" drop down list , at present there is all the users i've created for my project.How to confgure the list so that only a single usere is listed in "Assign To" list. A: The config option $g_handle_bug_threshold determines which users can be assigned to issues. All users with access level >= this option will be listed in the "assign to" selection list. Most likely if you see all users, you have either lowered this setting from its default of DEVELOPER to REPORTER (or even VIEWER), or all of your users are DEVELOPER or above. A: In the categories section , we can add diff entries regarding the application , i added sub modules , Each modules can be given an default assigne (a developers email) .So when ever the reporter , reports an issue , he/she needs to select an entry from the category list .This will make the bug assigned to the developer associated with that category.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to do versioning of shared library? Windows provides the resource file for version information for an application and DLL. The resource file includes information like version, copyright and manufacturer. We have a shared library and would like to add version information. How can we do it on Linux with a shared library? A: The best way to handle this is using libtool, which does the versioning for you. Essentially, version information is not (or not primarily, don't know from my head) encoded in the library itself, but rather in its filename. Version numbers are normally given in three-dot format, with the major number increasing for each break in downward ABI compatibility, the middle for breaks in upward ABI compatibility, and the minor for patches that did not change the ABI. Like qdot noted, symlinks in the lib directory provide the essential versioning. There is a symlink without a version number (libfoo.so) for the currently installed development headers, a symlink with a major number for each installed major version (libfoo.so.1) and a real file with the full version number. Normally, programs are linked to use libfoo.so.1 at runtime so that multiple major versions may coexist. A: Linux uses the following strategy - you (the system maintainer) provide symlinks from a 'specific' shared library file, like this: lrwxrwxrwx 1 root root 16 2011-09-22 14:36 libieee1284.so -> libieee1284.so.3 lrwxrwxrwx 1 root root 20 2011-09-22 14:36 libieee1284.so.3 -> libieee1284.so.3.2.2 -rw-r--r-- 1 root root 46576 2011-07-27 13:08 libieee1284.so.3.2.2 This way, developers can link either against -lieee1284 (any version ABI), or libieee1284.so.3 or even to the specific release and patch version (3.2.2) A: The short version is that you do this via the soname of the library. Read chapter 3 at http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html as well as chapter 3.3 ABI Versioning at http://www.akkadia.org/drepper/dsohowto.pdf
{ "language": "en", "url": "https://stackoverflow.com/questions/7553184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Reusing data entry methods across views I have written code for scrolling my table view even when keyboard hides it from entering data, using the notification center and the keyboardDidShow and keyboardDidHide methods. The problem is that I have almost 8 views in my app where I need to enter some data. Should I write the whole code in every single .m file, or is there any other easy way I could do it? A: Either you define that method in your application delegate file or create a separate class file which contains the method and you can call it whenever it required. myMethod.h file @interface myMethod : NSObject { } - (void) callMyMethod; myMethod.m file - (void) callMyMethod { // your code } In your view, call this method.... myMethod *objMyMethod = [[myMethod alloc] init]; [objMyMethod callMyMethod]; A: You could write some kind of BaseTableViewController which handles all the keyboard notifications. Then let all the other TableViewControllers inherit from this base controller. A: The DRY (Don't Repeat Yourself) principal would lead to creating one set of code to handle the input, not many copies that do the same thing. The principal of decoupling would lead to a separate class for the code. A separate class would also allow easier Unit Test to be written. A: This sounds like a perfect use-case for a category.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to integrate facebook graph api in Spring Roo I am very new to Spring Roo. I have decided to create my first project in Spring Roo that should implement facebook graph api. I have found few api (fbRest, facebook-api-java) after searching over the internet but some blogs say these are old. I don't know, where i get appropriate api that is supported by spring roo and how to start? Any help be appreciated. A: You can simply integrate Spring Social add-on to add Social features to your Spring Roo project, just like you would do for any Java project. :) Please see the following answer for a similar question. How to Access third Party API (Like as: Facebook, Linkedin, Twitter) using Spring ROO
{ "language": "en", "url": "https://stackoverflow.com/questions/7553189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Transform-to-center animation in horizontal list I have an horizontal listbox of many images. Now I need whenever I choose an image not at center. It will slide to center of listbox (not jump). Can anyone give me the solution ? Thanks a lot ! A: Have you tried ScrollToHorizontalOffset? If you have specific requirements about how the animation should look you'll need to do this yourself though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two branch pointers, but merging one Could someone explain, why in a situation like this: A--B--C--D (master) \ \E--F (feature/xxx, feature/xxx-blah) if I do a merge feature/xxx-blah into master, the branch pointer doesn't actually move? The commit is there, master pointer is advanced, but both features point at the same commit F. I expected to end up with this instead: A--B--C--D--G (master, feature/xxx-blah) \ / \E--F/ (feature/xxx) A: This is working as designed - when you merge, you only advance your current branch. This is actually a useful property, since if instead it worked as you expected, you then wouldn't easily be able to tell what was just on your feature branch after you had merged it - master and feature/xxx-blah would contain exactly the same commits. In most cases ("porcelain" commands in particular), actions in git that create new commits will advance your current branch, but won't advance any other branches as side-effects. One other point that might be worth making is that you can merge from any commit (or more than one) - they don't have to be branches. A: The fact that you comment doing no-ff merges explains why you expected: A--B--C--D--G (master, feature/xxx-blah) \ / \E--F/ (feature/xxx) But as mentioned in "Why does git use fast-forward merging by default?", no-ff is not the default. You see a similar scenario in "Moving master head to a branch".
{ "language": "en", "url": "https://stackoverflow.com/questions/7553191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Catching Click() in fancybox Js code $(".iframe").fancybox({'zoomSpeedIn': 0, 'zoomSpeedOut': 0, 'showCloseButton' : 'false','overlayShow': false, "width" : 500, "height" : 265 , 'titleShow': false, 'onClosed': function() { parent.location.reload(true); }}); $("#abtn_add_new").click(function () { alert("TEST!!!"); }); And html <a id="abtn_add_new" onclick=""><input id="btn_add_new" type="image" src="/img/btn_add.png"/></a> It doesn't work. Who knows what is problem? A: Try $("#abtn_add_new").live('click', function () { alert("TEST!!!"); }); A: If you want to capture the click before fancybox loads the content you could use: $("#abtn_add_new").fancybox({ onStart: function() { alert('foobar') } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7553192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing windows path in MySQL without escaping backslashes I would like to store windows path in MySQL without escaping the backslashes. How can I do this in Python? I am using MySQLdb to insert records into the database. When I use MySQLdb.escape_string(), I notice that the backslashes are removed. A: Have a look at os.path.normpath(thePath) I can't remember if it's that one, but there IS a standard os.path formating function that gives double backslashes, that can be stored in a db "as is" and reused later "as is". I have no more windows machine and cannot test it anymore. A: Just use a dictionary to add slashes wherever required to make the query valid : http://codepad.org/7mjbwKBf def addslashes(s): dict = {"\0":"\\\0", "\\":"\\\\"} #add more here return ''.join(dict.get(x,x) for x in s) query = "INSERT INTO MY_TABLE id,path values(23,'c:\windows\system\')"; print(addslashes(query));
{ "language": "en", "url": "https://stackoverflow.com/questions/7553200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Doubt on Multiple inheritance Java does not support multiple inheritance but Object class is by default super class of all classes. e.g class Object { } class B { } class A extends B { } Class A can access all method of B and Object.Is not it a example of multiple inheritance? So is it correct that Java does not support multiple inheritance. my question is not to find difference between multilevel and multiple inheritance. Java Docs,it self says :Class Object is the root of the class hierarchy. Every class has Object as a super class. All objects, including arrays, implement the methods of this class. So it means Class Object is super class of Class A{Previous example}. But Class B is also Super Class of Class A. SO what is meaning of it ? A: It is know as transitive nature of Inheritance. A: Look at the difference between transitive inheritance (C inherits directly from B and transitively from A): and multiple inheritance (C inheriting from both A and B): A: No it isn't. Multiple inheritance is when a class has more than one direct base class, as in: class A {} class B {} // not valid Java class C extends A, B {} A class may have many indirect base classes, each with only one direct base class, as in: class D extends A {} class E extends D {} class F extends E {} Here the inheritance hierarchy is F -> E -> D -> A -> Object, but this is still single inheritance. A: Since no Java class can extend directly two or more classes you can safely say that Java does not support multiple inheritance. You would have multiple inheritance if you were able to say class A extends B, C, but you can never do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can the below c++ thread code cause a process crash on an embedded system? similar c++ code as below is written for an embedded device. the process running on the device crashes upon start. on some other version of the device, crash is not observed. can it be related to the thread argument & thread detach being called. on normal linux desktop environment it does not crash. can anyone pls give their comments. Thanks in advance. #include <pthread.h> #include <iostream> using namespace std; #define NUM_THREADS 2 void *PrintHello(void *msg) { cout<<(char*)msg<<endl; while(1) { printf("Hello World! It's me, thread !\n"); sleep(2); } } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; const char* ch = "hello how r u.i'm passing argument"; for(t=0; t<NUM_THREADS; t++) { printf("In main: creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)ch); pthread_detach(threads[t]); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } return 0; } A: Yes. The C++ standard library, by default, is not thread-safe... stream objects like cout in particular. It may or may not have anything to do with the system being embedded. It's possible that the standard library implementation for the desktop system is more thread-safe, or it just happens to be implemented slightly differently, or perhaps you just got [un]lucky that you did not observe any undesired behaviour when testing on the desktop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display SQLite DataBase table? in my app i am using the database for displaying some user information, i created data base by using the SQLite DataBase Browser, and placed that database in the assets folder, this is the coding for that, i want to display this table. public class DataBaseHelper extends SQLiteOpenHelper{ private Context mycontext; private String DB_PATH = "/data/data/com.slate.game/databases/"; private static String DB_NAME = "slider.db";//the extension may be .sqlite or .db public SQLiteDatabase myDataBase; public DataBaseHelper(Context context) throws IOException { super(context,DB_NAME,null,1); this.mycontext=context; boolean dbexist = checkdatabase(); if(dbexist) { System.out.println("Database exists"); opendatabase(); } else { System.out.println("Database doesn't exist"); createdatabase(); } } public void createdatabase() throws IOException{ boolean dbexist = checkdatabase(); if(dbexist) { System.out.println(" Database exists."); } else{ this.getReadableDatabase(); try{ copydatabase(); } catch(IOException e) { throw new Error("Error copying database"); } } } private boolean checkdatabase() { boolean checkdb = false; try { String myPath = DB_PATH + DB_NAME; File dbfile = new File(myPath); checkdb = dbfile.exists(); } catch(SQLiteException e) { System.out.println("Database doesn't exist"); } return checkdb; } private void copydatabase() throws IOException { //Open your local db as the input stream InputStream myinput = mycontext.getAssets().open(DB_NAME); // Path to the just created empty db String outfilename = DB_PATH + DB_NAME; System.out.println("outfilename"+outfilename); //Open the empty db as the output stream OutputStream myoutput = new FileOutputStream("/data/data/com.slate.game/databases/slider.db"); // transfer byte to inputfile to outputfile byte[] buffer = new byte[1024]; int length; while ((length = myinput.read(buffer))>0) { myoutput.write(buffer,0,length); } //Close the streams myoutput.flush(); myoutput.close(); myinput.close(); } public void opendatabase() throws SQLException { //Open the database String mypath = DB_PATH + DB_NAME; myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE); } public synchronized void close() { if(myDataBase != null){ myDataBase.close(); } super.close(); } @Override public void onCreate(SQLiteDatabase arg0) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } please help me how to display this table(database).. A: finally i got answer from this BOOK Beginning.Android.Application.Development. using the SQLite i prepared database from that i will get row's and display using the TableLayout with TextView.. this is the database adapter class public class DBAdapter3x3 { public static final String KEY_ROWID = "_id"; public static final String KEY_NAME = "name"; public static final String KEY_MOVES = "moves"; public static final String KEY_TIME = "time"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "SliderDB3x3.db"; private static final String DATABASE_TABLE = "topscore3x3"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table topscore3x3 " + "(_id integer primary key autoincrement, " + "name text not null, moves integer not null," + "time text not null);"; private final Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter3x3(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL(DATABASE_CREATE); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS contacts"); onCreate(db); } } //---opens the database--- public DBAdapter3x3 open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a contact into the database--- public long insertContact(String name, int moves,String time) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_NAME, name); initialValues.put(KEY_MOVES, moves); initialValues.put(KEY_TIME, time); return db.insert(DATABASE_TABLE, null, initialValues); } //---deletes a particular contact--- public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the contacts--- public Cursor getAllContacts() { return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_MOVES, KEY_TIME}, null, null, null, null, null); } //---retrieves a particular contact--- public Cursor getContact(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_MOVES, KEY_TIME}, KEY_ROWID + "=" + rowId, null,null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a contact--- public boolean updateContact(long rowId, String name, int moves, String time) { ContentValues args = new ContentValues(); args.put(KEY_NAME, name); args.put(KEY_MOVES, moves); args.put(KEY_TIME, time); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } //public Cursor fetchAllNotes() { public Cursor SortAllRows() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_MOVES,KEY_TIME}, null, null, null, null, KEY_MOVES + " ASC"); } } i used database in this activity public class TopScore3x3 extends Activity { private DBAdapter3x3 db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.db3x3); db = new DBAdapter3x3(this); getall(); delete(); private void delete() { db.open(); Cursor c = db.SortAllRows(); int i=1; if (c.moveToFirst()) { do { if(i>10) { db.deleteContact(i); } i++; } while (c.moveToNext()); } c.close(); db.close(); } private void getall() { //---get all contacts--- db.open(); //db.fetchAllNotes(); Cursor c = db.SortAllRows(); int i=1; if (c.moveToFirst()) { do { DisplayContact(c,i++); } while (c.moveToNext()); } c.close(); db.close(); } public void DisplayContact(Cursor c,int row ) { String name11 = c.getString(1) + c.getString(2) + c.getString(3); tv1.setText(name11 ); } } A: use following function to retrieve data from database /** * This function used to select the records from DB. * @param tableName * @param tableColumns * @param whereClase * @param whereArgs * @param groupBy * @param having * @param orderBy * @return A Cursor object, which is positioned before the first entry. */ public Cursor selectRecordsFromDB(String tableName, String[] tableColumns,String whereClase, String whereArgs[], String groupBy,String having, String orderBy) { return myDataBase.query(tableName, tableColumns, whereClase, whereArgs,groupBy, having, orderBy); } /** * select records from db and return in list * @param tableName * @param tableColumns * @param whereClase * @param whereArgs * @param groupBy * @param having * @param orderBy * @return ArrayList<ArrayList<String>> */ public ArrayList<ArrayList<String>> selectRecordsFromDBList(String tableName, String[] tableColumns,String whereClase, String whereArgs[], String groupBy,String having, String orderBy) { ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>(); ArrayList<String> list = new ArrayList<String>(); Cursor cursor = myDataBase.query(tableName, tableColumns, whereClase, whereArgs, groupBy, having, orderBy); if (cursor.moveToFirst()) { do { list = new ArrayList<String>(); for(int i=0; i<cursor.getColumnCount(); i++) { list.add( cursor.getString(i) ); } retList.add(list); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } return retList; } A: Check this: http://www.higherpass.com/Android/Tutorials/Accessing-Data-With-Android-Cursors/2/ Use Cursor c = db.rawQuery(sql, null) to get results, iterating is explained there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Editing and Extracting data from a text file (ASP .NET) I need to extract data from a text file in ASP .NET. Example Data: ; comment data = astringvalue ; comment ; string values person = bob animal = rabbit ; boolean values (yes / no) isValid = yes isAnimal = no I will be creating a GUI control for each line that is not a comment. What is the best way to extract each line and determine if it is a string or a Boolean value. Performance is a must as the file can be quite large. Edit: At some point i will have need to update the values with the updated ones from the web page. private void ShowConfig() { string configLine = String.Empty; using (TextReader tr = File.OpenText(@"textfile")) { do { configLine = tr.ReadLine(); if (!String.IsNullOrEmpty(configLine) && !configLine.Contains(Convert.ToChar(";"))) { CreateControl(configLine); } } while (configLine != null); } private void CreateControl(string configline) { string lineHeader = string.Empty; string lineValue = String.Empty; for (int i = 0; i < configline.Length; i++) { if (configline[i] == Convert.ToChar("=")) { lineHeader = configline.Remove(i).TrimEnd(); lineValue = configline.Remove(0, ++i).TrimStart(); if (GetValueType(lineValue) is CheckBox) { this.Panel1.Controls.Add(CreateCheckBox(lineValue, lineHeader)); } else { this.Panel1.Controls.Add(CreateLabel(lineHeader)); this.Panel1.Controls.Add(CreateTextBox(lineValue, lineHeader)); } this.Panel1.Controls.Add(CreateNewLine()); break; } } } private Control GetValueType(string Value) { switch (Value) { case "yes": case "no": return new CheckBox(); default: return new TextBox(); } } In the future i will need to check for more value types than string and boolean. A: How about something like this? However, I think that working any kind of serious type-recognition into this schema is likely to be error prone. Why not use a better serialization in the first place? Something that captures type info in the serialized data? var data=@" ; comment data = value ; comment ; string values person = Bob animal = Rabbit ; boolean values (yes / no) isValid = yes isAnimal = no"; var parsed = data .Split(new[]{"\r\n","\r","\n"}, StringSplitOptions.RemoveEmptyEntries) .Select(line => line.Trim()) .Where(line => !line.StartsWith(";")) .Select(line => line.Split('=').Select(item => item.Trim())) .Where(kv => kv.Count() == 2) .Select(kv => new{key = kv.First(), value = kv.Last()}) .Select(kv => new{kv.key, kv.value, isBool = Regex.IsMatch(kv.value,"yes|no")}); Taking @Rubens' comments on-board, if the data source is too large to load in at once, you could stream the data with the addition of a helper method: static IEnumerable<string> Lines(string filename) { using (var sr = new StreamReader(filename)) { while (!sr.EndOfStream) { yield return sr.ReadLine(); } } } then: Lines(@"c:\path\to\data") .Select(line => line.Trim()) .Where(line => !line.StartsWith(";")) .Select(line => line.Split('=').Select(item => item.Trim())) .Where(kv => kv.Count() == 2) .Select(kv => new{key = kv.First(), value = kv.Last()}) .Select(kv => new{kv.key, kv.value, isBool = Regex.IsMatch(kv.value,"yes|no")}); A: StreamReader sr = null; while(!sr.EndOfStream) { string line = sr.ReadLine(); if (string.IsNullOrEmpty(line) || line.StartsWith(";")) continue; string[] tokens = line.Split("= ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if(tokens.Length == 2) { if("Yes".Equals(tokens[1], StringComparison.CurrentCultureIgnoreCase) || "No" .Equals(tokens[1], StringComparison.CurrentCultureIgnoreCase)) { // boolean } else { // non boolean } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: Am I missing a restricting pattern? I need to restrict implementation with only selected methods Say I have some class that is too fat of methods for one concrete case, but fits to about a half of them, so it is no way but to extend it. Simultaneously, I want to hide the fact that I've extended this fat class from end-users. Then I want to restrict that class with some new interface and let unneeded methods throw an UnsupportedOperationException: public class TooFatClass { public void usefulMethodOne() { ... }; public void usefulMethodTwo() { ... }; public void usefulMethodThree() { ... }; ... public void notUsefulMethodOne() { ... }; public void notUsefulMethodTwo() { ... }; public void notUsefulMethodThree() { ... }; ... } public interface OnlyUsefulMethods { public void usefulMethodOne(); public void usefulMethodTwo(); public void usefulMethodThree(); ... public static OnlyUsefulMethods create() { return new OnlyUsefulMethodsImpl(); } } // notice it is package-private class OnlyUsefulMethodsImpl extends TooFatClass implements OnlyUsefulMethods { public void usefulMethodOne() { ... }; public void usefulMethodTwo() { ... }; public void usefulMethodThree() { ... }; ... public void notUsefulMethodOne() { throw new UnsupportedOperationException(); }; public void notUsefulMethodTwo() { throw new UnsupportedOperationException(); }; public void notUsefulMethodThree() { throw new UnsupportedOperationException(); }; ... } So, OnlyUsefulMethodsImpl instance can be cast to TooFatClass if user really wants, but it hides this fact and do not forces user to do so. However, java do not allows static methods implementations in interfaces (it is dumb to make it OnlyUsefulMethods abstract, I think), so I finish with this smelly piece of code: public interface OnlyUsefulMethods { public void usefulMethodOne(); public void usefulMethodTwo(); public void usefulMethodThree(); ... public static final class Factory { public static OnlyUsefulMethods create() { return new OnlyUsefulMethodsImpl(); } public static OnlyUsefulMethods create(Options options) { return new OnlyUsefulMethodsImpl(options); } } } Even if I'll move a Factory outside of interface it looks too complex to use just for one class case, I want a factory method without showing OnlyUsefulMethodsImpl outside. Am I doing something wrong / too complex and missing some restricting pattern? May be relates to this questions (anyway, there are some answers that may be fit, I'm not sure): * *Why can't I define a static method in a Java interface? *Why can't I declare static methods in an interface? A: Sounds like a good time to delegation. The "leaner" class wraps the "fat" class and only exposes the interface of the "leaner" class. Some ides can help you implement delegation. A: class OnlyUsefulMethods extends TooFatClass{ public void usefulMethodOne() { ... }; public void usefulMethodTwo() { ... }; public void usefulMethodThree() { ... }; ... public void notUsefulMethodOne() { throw new UnsupportedOperationException(); }; public void notUsefulMethodTwo() { throw new UnsupportedOperationException(); }; public void notUsefulMethodThree() { throw new UnsupportedOperationException(); }; ... } Sometimes I wonder why patterns can make things so complicated... No need for factories, you can directly instantiate it with new. You can also use a composition pattern to wrap the TooFatClass instance inside a class that only exposes the needed methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UpdateSourceTrigger=Explicit Updating multiple field I have multiple textbox with the biding set as explicit Text="{Binding UpdateSourceTrigger=Explicit, XPath=Columns/Column[1]/@Header}" when i try to update them with with a button: txtName.GetBindingExpression( TextBox.TextProperty ).UpdateSource(); txtColumn1.GetBindingExpression( TextBox.TextProperty ).UpdateSource(); txtColumn2.GetBindingExpression( TextBox.TextProperty ).UpdateSource(); The first line of code will update his one and reset the biding of all the texboxes meaning that only the first textbox will update the underlining property. Any idea of how to do this? A: If all other text boxes are updated because the first text box raised the change notification, you can have some "Update source in progress" flag, and don't raise the Property Change Notification in this case, than the Binding Targets won't get updated, and you'd be able to continue updating the binding sources.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android monkeyrunner test calls onClick handler twice I am experiencing funny behavior of monkey. When app shows AlertDialog with two buttons, my onClick handler sometimes called twice. This does not happen when I press the button manually, only when using monkey. Here is my activity code: @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume"); AlertDialog.Builder builder = new AlertDialog.Builder(this) .setPositiveButton("yes", this) .setNegativeButton("no", this); AlertDialog alert = builder.create(); alert.show(); } @Override public void onClick(DialogInterface pDialog, int pWhich) { Log.d(TAG, "onClick " + pWhich); pDialog.dismiss(); } This is how I call monkey: adb shell monkey -p com.mycompany.helloapp -v 500 And here is logcat output (irrelevant lines are skipped): 09-26 12:27:04.867 D/ClickTest(27989): onResume 09-26 12:27:07.557 D/ClickTest(27989): onClick -1 09-26 12:27:07.557 D/ClickTest(27989): onClick -1 Am I doing anything wrong or this is some sort of bug in android UI event handler thet reproduces under high event load? -Lev
{ "language": "en", "url": "https://stackoverflow.com/questions/7553219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using php sessions with ajax (mobile device) I will explain my problem. I need to know if the steps below are correct: The user enters their login details and these get submitted to the php server. If these are correct, I want to use the php code to start a session. However, because this is a mobile device I will be using html5 session storage. Now, my mobile website is all ajax based with no page reloads. So if the user submits the correct login credentials, I make an ajax response back to the user with what information? The SID/session_id of the session_start? Then, on the mobile device I place this session_id into the html5 session storage? So, if these steps are correct, when the user then navigates around the website they are now logged in. And if they want to do something e.g. access a private page this creates an ajax request to the php server... this is where I am stuck. I assume that in this ajax request I send the session_id from the html5 session storage object, how does the php server use this id to prove the user is authentic? Presumably I need some kind of if statement and if it's not satisfied, send an ajax response back which my javascript will interpret as redirecting the user back to the login screen. Many thanks if anyone can help me, it will be much appreciated as I am very stuck. Note that cookies are not an option... A: You could theoretically use HTML5 local storage to store the session ID, or transmit the session ID as a GET parameter in every request and pass it manually to PHP using session_id(), but I can't see the benefit. You might as well rely on cookies for this - they will be transmitted in Ajax requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: google suggested city name autocomplete I'm trying to build a web page in which I want to use google suggested city/state name combinations when user starts typing their address, it auto completes the city and state just like in google maps. For reference visit this URL: Google Maps When someone start typing in top left green A box. it gives you auto suggested list. Can any one help me do the same thing for my web site? Or is there such google api exist that I can use? Thanks A: Job for the Places AutoComplete API :-) http://code.google.com/apis/maps/documentation/javascript/places.html http://code.google.com/apis/maps/documentation/places/autocomplete.html A: Is there a reason it has to be google suggested names? Here's an api that provides autocomplete for city names plus a lot of extra data you can squeeze out about the city (population, life quality data, even photo) http://developers.teleport.org/api/ more specifically the widget http://developers.teleport.org/api/autocomplete_widget/ A: google does not provide such a service for autosugest, google does have a service for getting the geocodes and more, when you have the full address. take a look in this post, where i had the same issue, i'm looking for a service that gives me the city names and addresses there was a suggestion from someone to use geonames.com as a service, but i'm not sure they have streetnames as well...
{ "language": "en", "url": "https://stackoverflow.com/questions/7553225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Tool for JSON API Documentation Is there a tool or an easy way to generate/maintain documentation of a rich RESTful JSON API? I also would want to publish and maintain (as executable documentation) it, something like what relishapp provides. An example. The application is Restful Ruby on Rails 3 application, tested using cucumber and R-Spec controller tests. A: You say you have Cucumber tests already - they are your documentation. They may just need some work to be readable. For output, you can use Cucumber's built-in HTML formatter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: href geo: fallback for non-mobile browsers? I want to use to open clients possible mobile navigation software, but how can i fallback to a normal URL if geo isn't assoicated with any program on the device? E.g. in firefox on PC i get this message; Firefox doesn't know how to open this address, because the protocol (geo) isn't associated with any program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem in ContactsContract API android i have an HTC legend.In its phone contacts it shows 4-5 contacts.But when i query it in my application it shows nearly 45 contacts.I think its gmail contacts. String[] Projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID, ContactsContract.Contacts.HAS_PHONE_NUMBER, ContactsContract.Contacts.STARRED}; Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, Projection, null, null, null); I am getting all the details with photo as well in a listview. Now i need to get particular contact details like all his phone numbers,emails,photo etc.For this i am writing this query final String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.IS_PRIMARY, }; final Cursor phone = managedQuery( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{contactId}, null); > if(phone.moveToFirst()) { > final int contactNumberColumnIndex = > phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); > final int contactTypeColumnIndex = > phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); i am getting all the details of the phone contact but not all other contacts. i have read that all these details are stored in shared table(ContactsContract.Data.CONTENT_URI), but i am not getting exactly what to do go get this done. Can someone help me figure out how to do this. Thanks A: You can do something like: getContentResolver().query( RawContactsEntity.CONTENT_URI, // projection new String[] { BaseColumns._ID, RawContactsEntity.MIMETYPE, // DATA columns are interpreted according to MIMETYPE // Project only union of data columns needed RawContactsEntity.DATA1, RawContactsEntity.DATA2, RawContactsEntity.DATA3, RawContactsEntity.DATA4, RawContactsEntity.DATA7, RawContactsEntity.DATA9, RawContactsEntity.DATA10, }, // selection RawContactsEntity.DELETED + "<>1 AND " + RawContactsEntity.MIMETYPE + " IN ('" + StructuredName.CONTENT_ITEM_TYPE + "','" + Email.CONTENT_ITEM_TYPE + "','" + Phone.CONTENT_ITEM_TYPE + "','" + StructuredPostal.CONTENT_ITEM_TYPE + "','" + Organization.CONTENT_ITEM_TYPE + "')", // selection params null, // sorting null); Next iterate through cursor, and first read MIME type: final String mimeType = cursor.getString(cursor.getColumnIndex( RawContactsEntity.MIMETYPE)); And depends on MIME type read corresponding data kind: if (StructuredName.CONTENT_ITEM_TYPE.equals(mimeType)) { readNameData(cursor); } else if (Email.CONTENT_ITEM_TYPE.equals(mimeType)) { addEmailData(cursor); } and so on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add text to config file and use it in code behind in asp.net I am using AES encryption and generating a random salt, I am storing this random salt in the database.. Before I store the value to the database I want to append a string to it. I want this string to be placed in config file. How can I store a string in config file and How can I call in to append it with my salt. A: Something like <appSettings> <add key="specialstring" value="value to append" /> </appSettings> and access this by ConfigurationSettingsConfigurationManager.AppSettings["specialstring"] and append Also you can use WebConfigurationManager in the same way instead of ConfigurationSettingsConfigurationManager A: Set value in web-config file by below code snippet <appSettings><add key="KeyForValue" value="ValueString" /></appSettings> Get value in coding file by below code snippet string strValuetoGet = ConfigurationManager.AppSettings["KeyForValue"] A: put the string in the appSettings section of your web.config file, something like this: <appSettings> ... <add key="mySaltPrefix" value="your value..." /> ... </appSettings> then read it from your C# code in this way: var mySaltPrefix = System.Configuration.ConfigurationManager.AppSettings["mySaltPrefix"]; to run this code you should add a reference to System.Configuration to your C# project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Image Resizing I've got a script that uploads files to the server as well as adds the filename to a database, but what I'd like to do it restrict the maximum dimensions of the image before uploading. So if I upload an image that is 1000 x 500 it will be restricted but still keep it's dimensions and will be changed to 200 x 100, but an image that is 300 x 300 will be restricted to 200 x 200 <?php //This is the directory where images will be saved $target = "uploads/"; $target = $target . basename( $_FILES['photo']['name']); //This gets all the other information from the form $name=$_POST['name']; $pic=($_FILES['photo']['name']); // Connects to your Database mysql_connect("hostname", "username", "password") or die(mysql_error()) ; mysql_select_db("database") or die(mysql_error()) ; //Writes the information to the database mysql_query("INSERT INTO `table` (name, photo) VALUES ('$name','$pic')") ; //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> Thanks for your help A: To my knowledge, you can’t resize the image before uploading it. (I could be wrong!) However, when you upload the image it goes into a temporary file. You can resize the temporary image and copy the resized image to its final destination. Since (it seems) you want to keep the width constant, you don’t really need to do a lot of ratio tests. Update: You should be able to simply use this in place of your original code. Most of it is unchanged. <?php // resizes an image to fit a given width in pixels. // works with BMP, PNG, JPEG, and GIF // $file is overwritten function fit_image_file_to_width($file, $w, $mime = 'image/jpeg') { list($width, $height) = getimagesize($file); $newwidth = $w; $newheight = $w * $height / $width; switch ($mime) { case 'image/jpeg': $src = imagecreatefromjpeg($file); break; case 'image/png'; $src = imagecreatefrompng($file); break; case 'image/bmp'; $src = imagecreatefromwbmp($file); break; case 'image/gif'; $src = imagecreatefromgif($file); break; } $dst = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); switch ($mime) { case 'image/jpeg': imagejpeg($dst, $file); break; case 'image/png'; imagealphablending($dst, false); imagesavealpha($dst, true); imagepng($dst, $file); break; case 'image/bmp'; imagewbmp($dst, $file); break; case 'image/gif'; imagegif($dst, $file); break; } imagedestroy($dst); } // init file vars $pic = $_FILES['photo']['name']; $target = 'uploads/' . basename( $_FILES['photo']['name']); $temp_name = $_FILES['photo']['tmp_name']; $type = $_FILES["photo"]["type"]; // Connects to your Database mysql_connect("hostname", "username", "password") or die(mysql_error()) ; mysql_select_db("database") or die(mysql_error()) ; // get form data $name = mysql_real_escape_string(isset($_POST['name']) ? $_POST['name'] : 'No name'); //Writes the information to the database mysql_query("INSERT INTO `table` (name, photo) VALUES ('$name','$pic')") ; // resize the image in the tmp directorys fit_image_file_to_width($temp_name, 200, $type); //Writes the photo to the server if(move_uploaded_file($temp_name, $target)) { //Tells you if its all ok echo "The file ". basename( $_FILES['photo']['name'] ). " has been uploaded"; } else { //Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?> A: I used in the past this function to generate thumbnails that fit in given dimensions keeping aspect ratio, maybe you can use it somehow: function resize_img_nofill($src_name,$dst_name,$width,$height,$dontExpand=false) { $MAGIC_QUOTES = set_magic_quotes_runtime(); set_magic_quotes_runtime(0); $type = strtolower(substr(strrchr($src_name,"."),1)); if($type == "jpg") { $src = imagecreatefromjpeg($src_name); } else if($type == "png") { $src = imagecreatefrompng($src_name); } else if($type == "gif") { $src = imagecreatefromgif($src_name); } else { if($src_name != $dst_name) copy($src_name,$dst_name); set_magic_quotes_runtime($MAGIC_QUOTES); return; } $d_width = $s_width = imagesx($src); $d_height = $s_height = imagesy($src); if($s_width*$height > $width*$s_height && (!$dontExpand || $width < $s_width)) { $d_width = $width; $d_height = (int)round($s_height*$d_width/$s_width); } else if(!$dontExpand || $height < $s_height) { $d_height = $height; $d_width = (int)round($s_width*$d_height/$s_height); } if($s_width != $d_width || $s_height != $d_height) { if($type == "jpg") { $dst = imagecreatetruecolor($d_width,$d_height); } else if($type == "png") { $dst = imagecreate($d_width,$d_height); } else if($type == "gif") { $dst = imagecreate($d_width,$d_height); } $white = imagecolorallocate($dst,255,255,255); imagefilledrectangle($dst,0,0,$d_width,$d_height,$white); imagecopyresampled($dst,$src,0,0,0,0,$d_width,$d_height,$s_width,$s_height); if($type == "jpg") imagejpeg($dst,$dst_name, 80); else if($type == "png") imagepng($dst,$dst_name); else if($type == "gif") imagegif($dst,$dst_name); imagedestroy($dst); imagedestroy($src); } else { copy($src_name,$dst_name); } set_magic_quotes_runtime($MAGIC_QUOTES); return array($d_width,$d_height); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: xslt condition to check if each row of a table has same or different data Is there any condition in xslt that will help me to find if a table field, say Name, has different value? I have a set of different names with me in a xml file. I need to display each name in a different color on the html table. If there are 2 rows that has same Name field, then they should both be of uniform color. Is there any if condition that will help me to achieve this requirement in xslt? A: Yes. You can count() the number of nodes with the given name. <xsl:variable name="value" select="Name/text()"/> <xsl:variable name="count" select="count(//row[Name/text() = $value])"/> <xsl:if test="$count &gt; 0"> <!-- do something --> </xsl:if> Or you can check if there is a preceding or following node with a Name: <xsl:variable name="value" select="Name/text()"/> <xsl:variable name="node" select="preceding::.//row[Name/text() = $value]|following::.//row[Name/text() = $value]"/> <xsl:if test="count($node) &gt; 0"> <!-- do something --> </xsl:if>
{ "language": "en", "url": "https://stackoverflow.com/questions/7553253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert Seq to ArrayBuffer Is there any concise way to convert a Seq into ArrayBuffer in Scala? A: scala> val seq = 1::2::3::Nil seq: List[Int] = List(1, 2, 3) scala> seq.toBuffer res2: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3) EDIT After Scala 2.1x, there is a method .to[Coll] defined in TraversableLike, which can be used as follow: scala> import collection.mutable import collection.mutable scala> seq.to[mutable.ArrayBuffer] res1: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3) scala> seq.to[mutable.Set] res2: scala.collection.mutable.Set[Int] = Set(1, 2, 3) A: This will work: ArrayBuffer(mySeq : _*) Some explanations: this uses the apply method in the ArrayBuffer companion object. The signature of that method is def apply [A] (elems: A*): ArrayBuffer[A] meaning that it takes a variable number of arguments. For instance: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8) is also a valid call. The ascription : _* indicates to the compiler that a Seq should be used in place of that variable number of arguments (see Section 4.6.2 in the Scala Reference).
{ "language": "en", "url": "https://stackoverflow.com/questions/7553255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How can I determine is stream is empty? I have a WCF service which is returning PDF files as a stream over a NetTcp endpoint. This is all working fine. However, if the file is not found, or if I can't find the related row in the database to retrieve the filepath then I return Stream.Null from the service. However I can't seem to find a way to compare the returning stream to check and see if it is empty or not. I have tried the following: If myStream IsNot Stream.Null 'Code to execute if stream isn't empty End If and If Not streamPDF.Equals(Stream.Null) 'Code to execute if stream isn't empty End If But neither of these work as the code just carries on into the If block. Any thoughts? A: The Stream.Null is only your service scoped construct. For client you will get most probably empty stream => it will be same stream type as if you really send data. It is strange design choice. If file doesn't exists it is "expected" exception and it should be handled with FaultContract and typed FaultException. A: The Stream.Null field which redirect the stream that will not consume any operating system resources. You can use Stream.Length property to check whether a stream is empty or not. A: If your code runs on a different machine, it's normal. The null stream ("A Stream with no backing store" from the documentation) is not marshaled differently over the wire. On the client side, it's just a stream which always returns EOF. If you need to carry some extra information, you need to find another way (other parameters /value information, exceptions), but not use the Stream itself, or use a data convention understood by both parties. For example "if the file is only 1 byte long and contains the character 255, then, it's the 'null stream'".
{ "language": "en", "url": "https://stackoverflow.com/questions/7553262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can add map object to list object non static in java I have problem with this code,when I add map object to list,all previous added object will be changed.how can I declare map as non static? for(Statment){ map.put(Key,value), } result.add(map); A: When you add something to a container, you are adding the reference (not a copy of the object it references) If you want to add a copy (so that if you can change the original, and the copy added to the list does not change) you have to explicitly copy it. e.g. Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); for(int i=0;i<10;i++) map.put(i, i); list.add(new LinkedHashMap<Integer, Integer>(map)); // add a copy. // you can change map without the list changing as well. A: Try this. for (condition) { if (!map.containskey(key)) { map.put(key,value); } } result.add(map); A: You have to declare each object outside the for otherwise you are adding just one reference, and any modification modifies all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Is there a FIFO stream in Scala? I'm looking for a FIFO stream in Scala, i.e., something that provides the functionality of * *immutable.Stream (a stream that can be finite and memorizes the elements that have already been read) *mutable.Queue (which allows for added elements to the FIFO) The stream should be closable and should block access to the next element until the element has been added or the stream has been closed. Actually I'm a bit surprised that the collection library does not (seem to) include such a data structure, since it is IMO a quite classical one. My questions: * *1) Did I overlook something? Is there already a class providing this functionality? *2) OK, if it's not included in the collection library then it might by just a trivial combination of existing collection classes. However, I tried to find this trivial code but my implementation looks still quite complex for such a simple problem. Is there a simpler solution for such a FifoStream? class FifoStream[T] extends Closeable { val queue = new Queue[Option[T]] lazy val stream = nextStreamElem private def nextStreamElem: Stream[T] = next() match { case Some(elem) => Stream.cons(elem, nextStreamElem) case None => Stream.empty } /** Returns next element in the queue (may wait for it to be inserted). */ private def next() = { queue.synchronized { if (queue.isEmpty) queue.wait() queue.dequeue() } } /** Adds new elements to this stream. */ def enqueue(elems: T*) { queue.synchronized { queue.enqueue(elems.map{Some(_)}: _*) queue.notify() } } /** Closes this stream. */ def close() { queue.synchronized { queue.enqueue(None) queue.notify() } } } Paradigmatic's solution (sightly modified) Thanks for your suggestions. I slightly modified paradigmatic's solution so that toStream returns an immutable stream (allows for repeatable reads) so that it fits my needs. Just for completeness, here is the code: import collection.JavaConversions._ import java.util.concurrent.{LinkedBlockingQueue, BlockingQueue} class FIFOStream[A]( private val queue: BlockingQueue[Option[A]] = new LinkedBlockingQueue[Option[A]]() ) { lazy val toStream: Stream[A] = queue2stream private def queue2stream: Stream[A] = queue take match { case Some(a) => Stream cons ( a, queue2stream ) case None => Stream empty } def close() = queue add None def enqueue( as: A* ) = queue addAll as.map( Some(_) ) } A: I'm assuming you're looking for something like java.util.concurrent.BlockingQueue? Akka has a BoundedBlockingQueue implementation of this interface. There are of course the implementations available in java.util.concurrent. You might also consider using Akka's actors for whatever it is you are doing. Use Actors to be notified or pushed a new event or message instead of pulling. A: In Scala, streams are "functional iterators". People expect them to be pure (no side effects) and immutable. In you case, everytime you iterate on the stream you modify the queue (so it's no pure). This can create a lot of misunderstandings, because iterating twice the same stream, will have two different results. That being said, you should rather use Java BlockingQueues, rather than rolling your own implementation. They are considered well implemented in term of safety and performances. Here is the cleanest code I can think of (using your approach): import java.util.concurrent.BlockingQueue import scala.collection.JavaConversions._ class FIFOStream[A]( private val queue: BlockingQueue[Option[A]] ) { def toStream: Stream[A] = queue take match { case Some(a) => Stream cons ( a, toStream ) case None => Stream empty } def close() = queue add None def enqueue( as: A* ) = queue addAll as.map( Some(_) ) } object FIFOStream { def apply[A]() = new LinkedBlockingQueue } A: 1) It seems you're looking for a dataflow stream seen in languages like Oz, which supports the producer-consumer pattern. Such a collection is not available in the collections API, but you could always create one yourself. 2) The data flow stream relies on the concept of single-assignment variables (such that they don't have to be initialized upon declaration point and reading them prior to initialization causes blocking): val x: Int startThread { println(x) } println("The other thread waits for the x to be assigned") x = 1 It would be straightforward to implement such a stream if single-assignment (or dataflow) variables were supported in the language (see the link). Since they are not a part of Scala, you have to use the wait-synchronized-notify pattern just like you did. Concurrent queues from Java can be used to achieve that as well, as the other user suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: WinRT Reflection (C++/CX) how can I introspect an object in C++/CX? I known how to get its class name (using IInspectable) but I wasn't able to figure out how to get a list of its properties or how to invoke methods if I have just a name of the method (string). I searched for an answer here and at Google but what I found is related to the .NET layer of WinRT (the System.Reflection namespace doesn't seem to be available in C++/CX). A: As hinted by svick, you take the class name (retrieved from IInspectable::GetRuntimeClassName), hand it to RoGetMetaDataFile. This returns an IMetaDataImport2. Now call IMetaDataImport2::FindTypeDefByName. This returns a typedef token. Now call IMetaDataImport2::GetTypeDefProps which will give you properties about the type. From the typedef properties, you can retrieve other information - enumerate the methods/fields if it's an interface/struct (or enum), find the type of the runtime class (if it's an interface or a class), etc. A: Even most of the normal .Net reflection isn't included in the subset of .Net available to WinRT applications. And I didn't find any reflection-related types in the WinRT documentation. This means that (unless I overlooked something) reflection is simply not exposed by the available APIs. Although I don't see why it shouldn't be available. The metadata is there, which should be enough. When looking at the C++-specific functions, there is the function RoGetMetaDataFile(). It seems it should be possible to use it to get the metadata. But it's a native C++ function, not C++/CX. This means it's not easy to use (manual memory management, …) and I doubt it will be allowed in apps that are in the Store. A: C++ doesn't provide any specific APIs to reflect on WinRT types, these types are fully defined in CX compliant metadata files and you can use the CLR native metadata APIs to read their definition. There is a snippet at http://social.msdn.microsoft.com/Forums/windowsapps/en-US/211ef583-db11-4e55-926b-6d9ab53dbdb4/ccx-reflection James McNellis released a full C++ library for CX reflection last year http://seaplusplus.com/2012/04/26/cxxreflect-native-reflection-for-the-windows-runtime/
{ "language": "en", "url": "https://stackoverflow.com/questions/7553273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: HTTP Binding Failure while binding with BPEL process. I have created a very sample SOA application with HTTP binding. The end point URL of my HTTP Binding is a sample netbeans application ( Calculator as a service ) . The service runs through glassfish server and is working fine. I have created a simple BPEL synchrounous processs , which inputs 2 numbers ( defined using complex type schema ) and outputs response ( i.e sum of the 2 numbers ) . Whenver i have compiled the application i get the same fault Warning(24,74): Failed to Find Binding "SesisonLocator":"{http://xmlns.oracle.com/pcbpel/adapter/http/Application3/http_session_locator2/SesisonLocator}GetSessionLocatorMethod_pt" in WSDL Manager I dont know what WSDL changes have to be performed in order to get the application up and running. PS: The calculator service is running is developer machine and BPEL application is to be deployed in other system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C – Smart programming with dependencies I have an iOS application that parses xml data from the web. I've setup it to parse some xml tags for me and then display some information in the application. I do not own the xml data so it's not unlikely that the xml tags could change without my knowledge and then rendering my iOS application useless because I'm not able to parse the data with the wrong xml tags. So instead of having the application crashing when (if) they change xml tags I was thinking of having the application send an e-mail in the background alerting that the xml tags have changed. Or something like that. Is that possible to do or is it even a smart solution to my problem? A: Why don't you parse the XML file in your server side using any technology that you prefer, and provide your controlled XML file to your iOS application. That way you will have the full control over the XML tags that your application expects! If the other party changes the tags, you just re-write your server side program to handle the changes gracefully!
{ "language": "en", "url": "https://stackoverflow.com/questions/7553278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AS3: Best way to include non-specific functions in to class Say I have the following set up of classes... Road - extends MovieClip Car - extends Road Controller - extends Car And I want to incorporate some common Mathematical functions in them all to make them faster e.g.(replacing Math classes with some speedy bitwise versions). What is the best way to incorporate these functions into all of them without writing the functions in the classes or extending from class of the functions. Is importing the class into each the fastest way or is their a better way? A: I agree with the comments that your design may needs some work. You can't use a Class in another Class without an import statement that refers to it in some way--even if you're just importing an Interface that the Class implements. The most flexible way to handle this is to have the functional object be passed in to the object that needs it, rather than having that object create the instance itself. This will allow you to swap out a different implementation when you need to (for instance, you might want to use a mock instance for unit testing, or you might need slightly different functionality optimized for a mobile device). You can pass in the instance either in the Constructor or use a property (which would allow you the freedom to change out the implementation at runtime). A: You can create a public function that you can import into any class. Some examples in the base language are navigateToURL() and getTimer(). These are just public functions in a package, not classes. So create a public function like so package nameOfYourPackage{ public function doSomething(a:arguments):returnType { // Stuf the function does goes here; } } then you can import it into any class like so: import nameOfYourPackage.doSomething; and then youc an call it anywhere in a class that imports it as: doSomething(args);
{ "language": "en", "url": "https://stackoverflow.com/questions/7553281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RedirectToAction is not working while authentication of mvc3 form with jquery i have been facing an issue in my loginscreen of my application which is developed with mvc3 and jquery, as i am writing the code for checking login credentials in controller and and that controller event is firing by clciking the buttoon click which is developed using jquery. i would like to navigate someo other page('/Customer/CollaborationPortal') when the login credentials are correct, else i want display message box stating that "credentials are wrong" and this is my code. JQuery Code $("#btnGo").click(function (e) { var RegData = getRegData(); if (RegData === null) { console.log("Specify Data!"); return; } $.ajax( { url: '/Registration/IsLoginExsit', type: 'POST', dataType: 'json', data: JSON.stringify(RegData), contentType: 'application/json; charset=utf-8', success: function (response) { //window.location.href('/Customer/CollaborationPortal'); Console.Log("success"); error: function () { //aler('Login error'); Console.Log("error"); } } }); }); function getRegData() { var UserName = $("#txtUserName").val(); var Password = $("#txtPassword").val(); return { "UserName": UserName, "Password": Password }; } }); Controller Code public ActionResult IsLoginExsit(BAMasterCustomerDO loginData) { if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty (loginData.Password)) { bool result = Businesss.Factory.BusinessFactory.GetRegistration().IsLoginExist(loginData.UserName, loginData.Password); if (result) { System.Web.HttpContext.Current.Session["UserName"]=loginData.UserName; return RedirectToAction("/Customer/CollaborationPortal"); } else { ViewData["message"] = "Registration failed"; return View(); } } return View(); } and also it is not entering into "success" and "error" code. Thanks in advance. A: you have specified the error callback inside success callback, move it outside like: $.ajax( { url: '/Registration/IsLoginExsit', type: 'POST', dataType: 'json', data: JSON.stringify(RegData), contentType: 'application/json; charset=utf-8', success: function (response) { //window.location.href('/Customer/CollaborationPortal'); console.log("success"); }, error: function () { //alert('Login error'); console.log("error"); } }); A: You have error function inside of success function.... This it's what you must have: $.ajax( { url: '/Registration/IsLoginExsit', type: 'POST', dataType: 'json', data: JSON.stringify(RegData), contentType: 'application/json; charset=utf-8', success: function (response) { //window.location.href('/Customer/CollaborationPortal'); Console.Log("success"); }, error: function () { //aler('Login error'); Console.Log("error"); } }); A: If I were you, I'd return a JSON object to the client like this: Success: { 'error' : false, 'redirect' : '/Customer/CollaborationPortal', 'message' : '' } Error: { 'error' : true, 'redirect' : false, 'message' : 'Please do this or that' } My jQuery would be: $.ajax( { url: '/Registration/IsLoginExsit', type: 'POST', dataType: 'json', data: JSON.stringify(RegData), contentType: 'application/json; charset=utf-8', success: function (response) { if (response.error) { alert(response.message); return; } window.location.pathname = response.redirect; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7553282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing XML literal as a parameter in Scala I can pass a variable as a multivalued parameter: scala> <b/> res26: scala.xml.Elem = <b></b> scala> Elem(null,"a",Null,TopScope,res26) res27: scala.xml.Elem = <a><b></b></a> But I can't pass an XML literal as a multivalued parameter: scala> Elem(null,"a",Null,TopScope,<b/>) <console>:12: error: not found: value < Elem(null,"a",Null,TopScope,<b/>) But I can pass an XML literal as a simple parameter scala> def bar(s:String,n:Elem) = s+n.toString bar: (s: String, n: scala.xml.Elem)java.lang.String scala> bar("super ", <a/>) res30: java.lang.String = super <a></a> ? Thanks A: Adding a space before the XML element makes it work: scala> Elem(null, "a", Null, TopScope, <b/>) resN: scala.xml.Elem = <a><b></b></a> From the Scala Language Specification, Section 1.5: In order to allow literal inclusion of XML fragments, lexical analysis switches from Scala mode to XML mode when encountering an opening angle bracket ’<’ in the following circumstance: The ’<’ must be preceded either by whitespace, an opening parenthesis or an opening brace and immediately followed by a character starting an XML name
{ "language": "en", "url": "https://stackoverflow.com/questions/7553283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: build Custom Share panel of buttons , android I am trying to build a sliding panel from top to down and vice versa. I found the solution to build in for iphone here: Build a custom share panel of buttons. How can I build this panel for Android? All I need is the steps. On Youtube, you can see the panel I built for iPhone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sort some XML elements according to their dependencies, by using XSLT? I would like to sort the following XML file: <root> <element name="a" depends="b,c" /> <element name="b" depends="c" /> <element name="c" /> </root> With this result: <root> <element name="c" /> <element name="b" depends="c" /> <element name="a" depends="b,c" /> </root> My dependencies can be modeled by using a tree (no cycle). depends="b,c" means depends on both b and c. I'm asking the good way to do this by using XSLT. Perhaps, do you have some ideas? Thanks! A: This XSLT 2.0 transformation: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/*"> <root> <xsl:call-template name="directDependents"/> </root> </xsl:template> <xsl:template name="directDependents"> <xsl:param name="pCore" as="element()*"/> <xsl:variable name="vNewDependents" select= "/*/element [not(. intersect $pCore) and not(tokenize(@depends, ',')[not(. = $pCore/@name)]) ] "/> <xsl:if test="$vNewDependents"> <xsl:sequence select="$vNewDependents"/> <xsl:call-template name="directDependents"> <xsl:with-param name="pCore" select="$pCore | $vNewDependents"/> </xsl:call-template> </xsl:if> </xsl:template> </xsl:stylesheet> when applied on the (second) provided XML document: <root> <element name="a" depends="b" /> <element name="b" depends="c" /> <element name="c" /> </root> produces the wanted, correct result: <root> <element name="c"/> <element name="b" depends="c"/> <element name="a" depends="b"/> </root> Update: Here is a more "XSLT 2.0 looking solution" (untested -- will correct any errors when I'm back home): <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my" exclude-result-prefixes="my"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/*"> <root> <xsl:sequence select="my:directDependents(/..)"/> </root> </xsl:template> <xsl:function name="my:directDependents"> <xsl:param name="pCore" as="element()*"/> <xsl:sequence select= "for $vNewDependents in /*/element [not(. intersect $pCore) and not(tokenize(@depends, ',')[not(. = $pCore/@name)]) ] return if($vNewDependents) then ( $vNewDependents, my:directDependents($pCore | $vNewDependents) ) else () "/> </xsl:function> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7553288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Check LDAP store for changes in attributes Is it possible to check if a users atrributes have changed when you query an LDAP. What I want to do is, everytime i run my program i want it to search the ldap and if two attribiutes change, IE from 3 to 0, and Active to Withdrawn, then write those users to a file. Is this possible? A: You can check the operational attribute modifyTimestamp. That tells you when anything changed in the entry. So you could formulate a search filter something like (&(modifyTimestamp > xxxx)(|(IE=0)(yyy=Withdrawn)))), and remember the last time you ran the search for the next value of xxxx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala on Android using Netbeans (preferably 6.8) I have tried Scala on Android using various suggestions found on the Internet. However, I have never been able to get a "one-click" solution for Netbeans. Eventually I settled for Java + Eclipse. However, the urge to create Scala programs on Android persists. Has anyone successfully used Netbeans IDE for Scala development for the Android platform? And that too using the IDE's build tools? Ideally the following features are needed: * *Scala code completion, syntax highlighting, error checking (as in NB-6.8 + Scala 2.8) *Automatic deployment on Android using one-click *No messing around with Proguard config *No messing around with signing of the jars/apks Please post a step-by-step guide if this is possible, or please link to an external page giving details. A: Have you tried the new eclipse plugin? Those are a major improvement from a few month ago. There should be versions for 2.9.1 and (if you need scala 2.8 ) Scala 2.8.2 see www.scala-ide.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7553294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Question about .NET remoting and serializing I have a interface (let name it OuterInt) and a class (OuterClass) that implemented It. Interface OuterInt consists of the other intefaces (InnerInt1, InnerInt2 and etc.) And there are some classes (InnerClass1, InnerClass2 and etc.) that implement these inner interfaces. OuterClass is exposed by server-side of application by .NET remoting (RemotingServices.Marshal(_OuterClass, "myOuterInt");) My question is will inner classes be serialized in the process of remoting or not and should client-side of application knows about those classes (for example to have reference of assembly with these classes)? I hope that I described my question explicitly, if not - ask me in comments. A: Remoting (which is, as Oded notes, pretty much deprecated) creates a remote hook to the object; not the API (the interface). As such, it will indeed be necessary to have the same dll (containing the concrete type being remoted) at both ends. Whether it is serialized vs proxied depends on whether it inherits from MarshalByRefObject. But typically: if it is in the object graph at one end, then it needs to be creatable at the other. If possible, prefer virtually any other implementation to remoting, IMO.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does Entity Framework support Encryption i am using SQLite as the database and Entity Framework to design my database structure. Needed an info. Does Entity Framework support "Encryption" of a particular column in the database. Eg: If i have a table T1 with 2 columns C1 and C2. Now if i need to encrypt the data that i stored in C2, then does Entity Framework allows me to do so? Thanks in advance. A: EF does not directly handle encryption. You'll either enable encryption at the DB level, where I think that SQLite is somewhat lacking in that respect, or you'll have pre-encrypt the data before you persist it to the database using EF. I would say enabling encryption at the DB level is the best option (also for performance reasons) and I know that SQL CE has support for it but not sure about SQLite. If not, you could easily encrypt before putting data into the database and store it as binary data. Then you can easily get the byte[] with EF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customizing ebay store HTML and CSS code (How to?) I have an ebay store and it has some themes but I would like to be able to change the CSS and HTML code myself. Does anyone know how this is done? Thanks A: I've done it several times earlier. Main thing is to add link to stylesheet (which is on your server). If i remember correct, you can add it where HTML for header is added, and then style elements generated by eBay. (Don't use id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7553305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: south & mysql problem can somebody help me out on this: I have installed recently south to use it updating changes in my django-based project on the production server (Appache 2.0, MySql 5.0, python 2.5, Mysqldb for python, django 1.3, and south 0.7.3). After converting my app named signature to south, which was done successfully, the commandmanage migrate signature it prints the following output: C:\python projects\suivireal>manage.py migrate signature Running migrations for signature: - Migrating forwards to 0002_auto__del_field_agent_titre_en__add_field_agent_ni veau__add_field_agen. > signature:0002_auto__del_field_agent_titre_en__add_field_agent_niveau__add_fi eld_agen Traceback (most recent call last): File "C:\python projects\suivireal\manage.py", line 14, in <module> execute_manager(settings) File "C:\Python26\Lib\site-packages\django\core\management\__init__.py", line 438, in execute_manager utility.execute() File "C:\Python26\Lib\site-packages\django\core\management\__init__.py", line 379, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python26\Lib\site-packages\django\core\management\base.py", line 191, in run_from_argv self.execute(*args, **options.__dict__) File "C:\Python26\Lib\site-packages\django\core\management\base.py", line 220, in execute output = self.handle(*args, **options) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\management\comma nds\migrate.py", line 102, in handle delete_ghosts = delete_ghosts, File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\__init __.py", line 202, in migrate_app success = migrator.migrate_many(target, workplan, database) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 215, in migrate_many result = migrator.__class__.migrate_many(migrator, target, migrations, datab ase) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 284, in migrate_many result = self.migrate(migration, database) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 121, in migrate result = self.run(migration) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 94, in run dry_run.run_migration(migration) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 172, in run_migration self._run_migration(migration) File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 162, in _run_migration raise exceptions.FailedDryRun(migration, sys.exc_info()) south.exceptions.FailedDryRun: ! Error found during dry run of '0002_auto__del_ field_agent_titre_en__add_field_agent_niveau__add_field_agen'! Aborting. Traceback (most recent call last): File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 159, in _run_migration migration_function() File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\migration\migrat ors.py", line 56, in <lambda> return (lambda: direction(orm)) File "C:\python projects\suivireal\..\suivireal\signature\migrations\0002_auto __del_field_agent_titre_en__add_field_agent_niveau__add_field_agen.py", line 12, in forwards db.delete_column('signature_agent', 'titre_en') File "c:\python26\lib\site-packages\South-0.7-py2.6.egg\south\db\mysql.py", li ne 90, in delete_column result = cursor.execute(get_fkeyname_query % (db_name, table_name, name)) File "C:\Python26\Lib\site-packages\django\db\backends\util.py", line 34, in e xecute return self.cursor.execute(sql, params) File "C:\Python26\Lib\site-packages\django\db\backends\mysql\base.py", line 86 , in execute return self.cursor.execute(query, args) File "C:\Python26\Lib\site-packages\MySQLdb\cursors.py", line 176, in execute if not self._defer_warnings: self._warning_check() File "C:\Python26\Lib\site-packages\MySQLdb\cursors.py", line 92, in _warning_ check warn(w[-1], self.Warning, 3) Warning: Table 'chold.signupsetup' doesn't exist I googled to see the problem whether it is related to mysql but I couldn't a find a way out. A: The error is saying that there is a missing table in your database called "chold.signupsetup". You should check that that this table exists, and if not create it. The usual way of creating tables for django apps is to run syncdb: $ python manage.py syncdb Then try running the migration again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Galleriffic plugin hiding images in IE7 Has anyone resolved the Galleriffic IE7 issue? I noticed a few questions posted in the past on this topic. I have tried absolutely everything and have had no luck... The main images are hidden for some reason, only in IE7, anyone have a clue why? A: Issue was with a CSS property. When resizing the image display window it would push the image down below it in IE7, so the issue was with the default CSS in div.slideshow img. Had to add position: absolute; and left: 0; to fix the issue. Reference: Galleriffic plugin issues with IE7
{ "language": "en", "url": "https://stackoverflow.com/questions/7553308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHPUnit reports a PHPUnit_Framework_Exception I added a simple test to a bundle. As suggested in the manual I tried to have PHPUnit load the configuration with: phpunit -c /app phpunit.xml looks like this: <?xml version="1.0" encoding="UTF-8"?> <!-- http://www.phpunit.de/manual/current/en/appendixes.configuration.html --> <phpunit backupGlobals = "false" backupStaticAttributes = "false" colors = "true" convertErrorsToExceptions = "true" convertNoticesToExceptions = "true" convertWarningsToExceptions = "true" processIsolation = "false" stopOnFailure = "false" syntaxCheck = "false" bootstrap = "bootstrap.php.cache" > <testsuites> <testsuite name="Project Test Suite"> <directory>../src/*Bundle/Tests</directory> </testsuite> </testsuites> </phpunit> The error message I get is: root@h0x03:/var/www/fi/FrontendIntegrator# phpunit -c app/ PHP Fatal error: Uncaught exception 'PHPUnit_Framework_Exception' with message 'Neither "Project Test Suite.php" nor "Project Test Suite.php" could be opened.' in /usr/share/php/PHPUnit/Util/Skeleton/Test.php:102 Stack trace: #0 /usr/share/php/PHPUnit/TextUI/Command.php(157): PHPUnit_Util_Skeleton_Test->__construct('Project Test Su...', '') #1 /usr/share/php/PHPUnit/TextUI/Command.php(129): PHPUnit_TextUI_Command->run(Array, true) #2 /usr/bin/phpunit(49): PHPUnit_TextUI_Command::main() #3 {main} thrown in /usr/share/php/PHPUnit/Util/Skeleton/Test.php on line 102 PHPUnit apparently loads the file and tries to find a PHP-file named after the test suites name. I cannot find any information on why it does so or how such a file should look like. A: It seems like PHPUnit tries to find a file named after the name-attribute of the testsuite-tag * *if it either cannot find any tests (wrong naming or wrong directory) or *if there is a fatal error occuring in a test-script; which occures so early that PHPUnit cannot identify the content of that file as a test - as no class could be loaded up until that point. A: I had the same problem today testing my controllers. Turns out just following the Book's command for it doesn't work, since PHPUnit can't find the test classes. I managed to find a workaround, just specify the test file you'd like tested, and it'll work. phpunit -c app src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php A: It happened to me that I had one extra directory level in my bundles. Instead of MyVendorName\MyBundleNameBundle I had MyVendorName\MyProject\MyBundleNameBundle The default directories within phpunit.xml.dist, in the section testsuites are those: <testsuites> <testsuite name="Project Test Suite"> <directory>../src/*/*Bundle/Tests</directory> <directory>../src/*/Bundle/*Bundle/Tests</directory> </testsuite> </testsuites> but none did match my bundle namespace: Xmontero\Emperors\AdminBundle whose tests, in turn, were in the directory src/Xmontero/Emperors/AdminBundle/Tests. In addition ALL my bundles had that syntax and I removed any bundle with the other syntax (like Acme\DemoBundle). As a result, phpunit did not find any test. I solved like this: just below this line in phpunit.xml.dist <directory>../src/*/*Bundle/Tests</directory> I added this line <directory>../src/*/*/*Bundle/Tests</directory> so it reads: <testsuites> <testsuite name="Project Test Suite"> <directory>../src/*/*Bundle/Tests</directory> <directory>../src/*/*/*Bundle/Tests</directory> <directory>../src/*/Bundle/*Bundle/Tests</directory> </testsuite> </testsuites> ...and everything worked fine ;) -- EDIT 1 day later -- It gives me now report on coverage about the test itself, when running phpunit -c app --coverage-html myNiceDir - when I expect it to give me only the coverage of the system under test. This is because there is a whitelist that follows the same pattern, and there is something to be added in the exclude list: Where it read this: <exclude> <directory>../src/*/*Bundle/Resources</directory> <directory>../src/*/*Bundle/Tests</directory> <directory>../src/*/Bundle/*Bundle/Resources</directory> <directory>../src/*/Bundle/*Bundle/Tests</directory> </exclude> I changed into this: <exclude> <directory>../src/*/*Bundle/Resources</directory> <directory>../src/*/*/*Bundle/Resources</directory> <directory>../src/*/*Bundle/Tests</directory> <directory>../src/*/*/*Bundle/Tests</directory> <directory>../src/*/Bundle/*Bundle/Resources</directory> <directory>../src/*/Bundle/*Bundle/Tests</directory> </exclude> I hope now it's correct ;) A: I had the same exact error, and I solved by just upgrading my phpunit version, I had 3.6.10 and now I have 4.0.17 and it works perfectly and as expected. The Synfony book is not completely wrong, it just states the wrong phpunit version as the needed one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: add markers to my OSM .PHP and .JS heey everyone, I've got a task from my work where I need to put our customer database on a OSM using .PHP and .JS is this possible? And is it possible to get the info rom our database without having the lat and longtitude of the addresses? I'm also not very good at programming. thx for everyone that tries to help. A: There's a great number of things you need to learn to be able to build the kind of site you're talking about. You need to know several (not just one) programming language, how relational databases work, how HTML and JavaScript work together, and the many different ways geographic information is processed. To put it another way, it's like saying "I've been asked to build a house, where can I learn the bricklaying I need?". You're being asked too large a task, especially for an intern. There is a simple example of overlaying markers on an OSM map,simple example of overlaying markers on an OSM map but that needs you to know some JavaScript yourself, which you'll need to learn separately. got this from someone else on other forum maybe helps other people also still searching for more though if people know some
{ "language": "en", "url": "https://stackoverflow.com/questions/7553318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do not have permission to open the created .mdf file using my application in Windows 7 log in as normal user then i am able to create .mdf file using my application, but not able to open the same file. It says i don't have permissions to open contact administrator. Let me know the reason. A: you should put the file in a folder with permission . usually its data folder inside the sql installation dir ( or one of its childs) ... put the file there and them youll be able to open the file
{ "language": "en", "url": "https://stackoverflow.com/questions/7553322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Leave message to Drupal 7 with iPhone app How to leave message to an article in Drupal 7 with iPhone app (iOS 4.3)? Any connector from D7 I can use in iOS SDK ? A: The Drupal Services module provides endpoints via XMLRPC/JSON-RPC/etc. to perform many core functions remotely (including adding comments to nodes). As far as I know that's currently the only option available without having to write a connector yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Background image color changes firefox/chrome I have a very strange from when testing a website on Chrome. The CSS is exactly the same but appears different. Plus tested on the same monitor. Firefox Chrome You can see from the Chrome print screen the background image I am using for the knives/forks, its the background color of this image which changes. A: Chances are, your image has a color profile applied, and thus is being rendered differently in Chrome and Firefox, which only the former of these two will actually respect it. Reading off of Chris Coiyer's article on web color profiles, you can fix the problem by doing as follows: If you "Save As..." from the file menu, you will have the opportunity to save your color profile along with the image. If you "Save for Web & Devices..." the "sRGB" (best for the web) color profile will be automatically applied (in CS3 anyway). A: The background image at http://www.cater-shawrecruitment.co.uk/webapp/templates/default/images/bgpage.jpg has an embedded colour profile, which different browsers will interpret differently. You'll need to re-render the image without the embedded colour profile. This is probably caused by using photoshop to simply 'Save' the JPG, rather than 'Save for web'ing. A: this is something to do with colorprofiles. this might help - Image color differences in different browsers. (Firefox, Chrome, IE) and this http://code.google.com/p/chromium/issues/detail?id=143 check your colorprofiles in photoshop (cmd+shift+k) and try to recreate the image. should work. A: If you change the image to be png it will be the same color. The reason is in the link of @Nightfirecat and in @graphicdivine 's answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: InflateException I've been encountering and InflateException error and am not really sure what it means. I hope someone can explain it to me. Thanks. Below is the stack trace. 09-26 17:35:29.747: ERROR/AndroidRuntime(10214): Uncaught handler: thread main exiting due to uncaught exception 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.comp.something/com.project.something.something.android.SomethingActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class com.project.something.something.android 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.os.Handler.dispatchMessage(Handler.java:99) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.os.Looper.loop(Looper.java:123) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.ActivityThread.main(ActivityThread.java:4363) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at java.lang.reflect.Method.invokeNative(Native Method) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at java.lang.reflect.Method.invoke(Method.java:521) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at dalvik.system.NativeStart.main(Native Method) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): Caused by: android.view.InflateException: Binary XML file line #15: Error inflating class com.project.something.something.android 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.rInflate(LayoutInflater.java:618) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.inflate(LayoutInflater.java:407) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.Activity.setContentView(Activity.java:1631) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at com.project.something.something.android.SomethingActivity.onCreate(SomethingActivity.java:48) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): ... 11 more 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): Caused by: java.lang.ClassNotFoundException:com.project.something.something.android in loader dalvik.system.PathClassLoader@4803c918 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at java.lang.ClassLoader.loadClass(ClassLoader.java:573) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at java.lang.ClassLoader.loadClass(ClassLoader.java:532) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.createView(LayoutInflater.java:466) 09-26 17:35:30.072: ERROR/AndroidRuntime(10214): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565) A: It seems you want to set a layout in your onCreate() method using setContentView(). The layout refers to a class in line #5 that is named com.project.something.something.android. I guess the class doesn't exist and so the layout couldn't be inflated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementing thread-safe arrays I want to implement a array-liked data structure allowing multiple threads to modify/insert items simultaneously. How can I obtain it in regard to performance? I implemented a wrapper class around std::vector and I used critical sections for synchronizing threads. Please have a look at my code below. Each time a thread want to work on the internal data, it may have to wait for other threads. Hence, I think its performance is NOT good. :( Is there any idea? class parallelArray{ private: std::vector<int> data; zLock dataLock; // my predefined class for synchronizing public: void insert(int val){ dataLock.lock(); data.push_back(val); dataLock.unlock(); } void modify(unsigned int index, int newVal){ dataLock.lock(); data[index]=newVal; // assuming that the index is valid dataLock.unlock(); } }; A: Take a look at shared_mutex in the Boost library. This allows you to have multiple readers, but only one writer http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex A: The best way is to use some fast reader-writer lock. You perform shared locking for read-only access and exclusive locking for writable access - this way read-only access is performed simultaneously. In user-mode Win32 API there are Slim Reader/Writer (SRW) Locks available in Vista and later. Before Vista you have to implement reader-writer lock functionality yourself that is pretty simple task. You can do it with one critical section, one event and one enum/int value. Though good implementation would require more effort - I would use hand-crafted linked list of local (stack allocated) structures to implement fair waiting queue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trouble sending files through IE8 I got some problem with sending files through IE8. var form = formAppend('', OBJ.uploadFileContainer); form.enctype = 'multipart/form-data'; form.action = 'iCal/iCalUpload.php'; form.target = 'help'; form.method = 'post'; var input = inputAppend('[type=file][name=calendarFile]', form); var id = inputAppend('[type=hidden][name=id]', form); $(form).submit(); I got a http 200 status which is good. But in PHP I can't really get the file with $_FILES['calendarFile'] it is issues the warning undefined index. It works well in all browser version except for IE < 9. Any idea of how to fix this? Forgot to mention that inputAppend() is a DOM creation function I'm using. It creates an input Element and add the attributes using jquery selectors. There is definetly not wrong with it. PHP Code $errorMessage = 'invalid File'; if ($_FILES["calendarFile"]["size"] < 100000 && //Undefined Index Warning in PHP ($_FILES['calendarFile']['type'] == 'text/calendar' || $_FILES['file']['type'] == 'text/x-vcalendar')){ if ($_FILES["calendarFile"]["error"] > 0){ $errorMessage = $_FILES["calendarFile"]["error"]; }else{ $timeStamp = time(); $errorMessage = 'The file was succesfully uploaded!'; move_uploaded_file( $_FILES["calendarFile"]["tmp_name"], "upload/$timeStamp"."-".$_FILES['calendarFile']['name']); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7553341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merge tool for c# code Can anyone recommend a merge tool that's specifically designed for merging C# code? The features I'm after: * *Can identify code constructs (classes, methods, ...) *Can detect reorders of those constructs *Ignore reorder-only differences *3-way merge *Compilation errors highlighted on-the-fly in the result pane. Basically, I'm looking for a tool that's much more specific than classic file merge tools like Winmerge. The problem with general-purpose merge tools is that they detect changes line by line which makes it extremely hard to identify blocks of code that has been moved around but that are still perfectly valid, and more importantly, to identify compilation errors in the result. A: What about Code Compare? The features you asked for are in the Pro Edition (see feature comparison) which is 49.90$.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to select last 3 minutes' records from MySQL with PHP this is my SQL table: +----------------+----------------+-----------+------------------------+ | User_Name | Password | IP | Login_Time | +----------------+----------------+-----------+------------------------+ | rthrthrhrt | fjdjetje5e | 127.0.0.1 | 2011-09-24 18:02:06 | | Empty | Empty | 127.0.0.1 | 2011-09-24 18:10:01 | | Empty | Empty | 127.0.0.1 | 2011-09-24 18:04:00 | | rsyrt | rwytw4364 | 127.0.0.1 | 2011-09-24 18:08:59 | | eryrjrj5 | Empty | 127.0.0.1 | 2011-09-24 18:03:56 | | reutreuetry | reuretyre | 127.0.0.1 | 2011-09-24 18:06:53 | | Empty | rthrtrt | 127.0.0.1 | 2011-09-24 18:05:51 | | djdjgdjh | 66735 | 127.0.0.1 | 2011-09-24 18:09:49 | | fgjdgjdhg | Empty | 127.0.0.1 | 2011-09-24 18:07:46 | | Empty | Empty | 127.0.0.1 | 2011-09-24 18:11:43 | +----------------+----------------+-----------+------------------------+ I am developing a brute force addon with PHP and MySQL. I would like to select last 3 minutes' records. for example (what i'd like to do?): time is now: 2011-09-26 9:45:00. i would like to select all records between 2011-09-26 9:45:00 and 2011-09-26 9:42:00. A: This query will work even if your table is not updated... select * from myTable where Login_time > select max(time) - interval 3 minute ; A: Use this sql query: select * from myTable where Login_time > date_sub(now(), interval 3 minute) ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7553346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Date array sorting issue, iPhone sdk I have an array that contains different date values. And I have used the following code to sort the date array, its done. combinedArr = [[NSMutableArray alloc]init]; NSInteger counts = [pbTitle count]; for (int i = 0; i < counts; i++) { CustomObject *customobject2 = [CustomObject customObjectWithName: [pbTitle objectAtIndex:i] andDate:[pbstartDate objectAtIndex:i]]; [combinedArr addObject:customobject2]; } [combinedArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [[(CustomObject*)obj1 date]compare: [(CustomObject*)obj2 date]]; }]; NSLog(@"Results: %@", combinedArr); Now the result is in the combinedArr, I need to check the each value with current system time and need to load into two different arrays, and load these two arrays into two sections of a tableView. How can I implement that? Please help me to find a solution. A: I think that the simplest and the fastest (shorter running time) solution is to create 2 separate arrays from the beginning and sort each one separately. Like this: NSDate *currentDate = [NSDate date]; NSMutableArray *pastArray = [[NSMutableArray alloc] init]; NSMutableArray *futureArray = [[NSMutableArray alloc] init]; NSInteger counts = [pbTitle count]; // Fill the arrays for (int i = 0; i < counts; i++) { NSDate *customOnjectDate = [pbstartDate objectAtIndex:i]; CustomObject *customobject2 = [CustomObject customObjectWithName:[pbTitle objectAtIndex:i] andDate:customOnjectDate]; NSMutableArray *array = ([customOnjectDate compare:currentDate] == NSOrderedAscending ? pastArray : futureArray); [array addObject:customobject2]; } // Sort the arrays [pastArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [[obj1 date] compare:[obj2 date]]; }]; [futureArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [[obj1 date] compare:[obj2 date]]; }]; // Use the arrays NSLog(@"pastArray: %@", pastArray); NSLog(@"futureArray: %@", futureArray); // Don't forget to release the arrays after you use them [pastArray release]; [futureArray release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7553350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monitor start and close of process? Is there a way to monitor processes in the Mac OS X before they Start & End? I have a dynamic which I would like to inject in few selected processes before the start, so that hooking can be performed. And would like to do the reverse when application quits, i.e. when application quits I want to unload that library from those process & thus perform unhooking. What can be the best solution for my situation? A: In Carbon, you can register for the kEventClassApplication/kEventAppLaunched event. For quitting, I think looking for an event might not be the best approach; you may not be able to respond in time before the process actually ends. It may be better to have your injected code install an atexit handler or something. A: When application quits it unload's that library from those process automatically. I had a bug which prevented calling of destructor from dylib.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery UI tabs - getting URL of tab loaded with Ajax I have jQuery UI tabs using AJAX. My problem is I can't seem to retrieve the url which was loaded inside a tab. For example - I get URL of loaded tab like this var links = $("#tabs > ul").find("li a"); var selectedTab = $("#tabs").tabs('option', 'selected'); var url = $.data(links[selectedTab], 'load.tabs'); Where url is the url of currently opened tab. In the tab I have an AJAX call, which calls the same url but with some parameters, i.e. $.ajax({ method: 'GET', url = url+'?parameter=value' }); Once this call is executed, a newly created URL is called, tab is reloaded, but the variable which retrieves the loaded tab url remains the same, which means my parameters are missing. Ideas? A: $("#tabs").tabs({ load: function(event, ui){ var anchor = ui.tab.find(".ui-tabs-anchor"); var url = anchor.attr('href'); } }); This will save the current tab URL in variable url A: you can keep a global variable for the URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7553363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with editing edittext in ExpandableListView I have 3 group containing 3 child which has EditText , when I click on EditText the software keyboard pop's out, at that time the expandable list is redrawn When the I am done with text editing , software keypad is closed at that time I need to store the value of EditText present in the all 3 child of all 3 group, since on the redraw of list the edited values are not got stored. Any suggestion for using EditText in ExpandableListView. A: I don't know if is the best solution, but what I did is to use another list to store the values of each EditText, let me know if you find something better
{ "language": "en", "url": "https://stackoverflow.com/questions/7553366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }