text
stringlengths
8
267k
meta
dict
Q: Tomcat/jsp/servlet /web.xml issue I am working on a project for school and am completely frustrated. The project is to get a simple JSP/Servlet demo working on our personal websites and after probably 20+ hours of work I am still unsuccessful in getting this accomplished. The really frustrating thing I've been given all the code and still can't really get this to work. Well, that isn't totally true. I have gotten it to work on my local tomcat server, but I can't replicate that magic on my personal website. So, here is what I have. First, the code. This assignment consists of two classes for servlets and two jsps and a web.xml file. Here is the first servlet called ControllerServlet.java package test; // Import the servlet classes import javax.servlet.*; import javax.servlet.http.*; // Import the standard Java classes import java.io.*; import java.util.*; /** * Controller Servlet */ public class ControllerServlet extends HttpServlet { private static String HELLO_JSP = "hello.jsp"; private static String GOODBYE_JSP = "goodbye.jsp"; private static String OTHER_JSP = "main.jsp"; public void init() throws ServletException { // Typically initialize your request to page mappings here } public void service( HttpServletRequest req, HttpServletResponse res ) throws ServletException { try { // Get the path - this is our key to our Request map String pathInfo = req.getPathInfo(); // Find out what the user is requesting String jsp = null; if( pathInfo.equalsIgnoreCase( "/hello" ) ) { String name = req.getParameter( "name" ); PersonBean person = new PersonBean( name ); HttpSession session = req.getSession(); session.setAttribute( "person", person ); jsp = HELLO_JSP; } else if( pathInfo.equalsIgnoreCase( "/goodbye" ) ) { HttpSession session = req.getSession(); PersonBean person = ( PersonBean )session.getAttribute( "person" ); req.setAttribute( "person", person ); session.removeAttribute( "person" ); jsp = GOODBYE_JSP; } else { jsp = OTHER_JSP; } // Foward the request to the jsp RequestDispatcher dispatcher = req.getRequestDispatcher( "/" + jsp ); dispatcher.forward( req, res ); } catch( IOException ioe ) { throw new ServletException( ioe ); } } } Now the PersonBean.java: package test; public class PersonBean implements java.io.Serializable { private String name; public PersonBean() { } public PersonBean( String name ) { this.name = name; } public String getName() { return this.name; } public void setName( String name ) { this.name = name; } } Now the hello.jsp: <jsp:useBean id="person" class="test.PersonBean" scope="session" /> <HTML> <HEAD> <TITLE>Hello, <jsp:getProperty name="person" property="name" /></TITLE> </HEAD> <BODY> <P>Hello, <jsp:getProperty name="person" property="name" /></P> <A HREF="goodbye">Goodbye</A> </BODY> </HTML> And the goodbye.jsp <jsp:useBean id="person" class="test.PersonBean" scope="session" /> <HTML> <HEAD> <TITLE>Good bye, <jsp:getProperty name="person" property="name" /></TITLE> </HEAD> <BODY> <P>Good bye, <jsp:getProperty name="person" property="name" /></P> </BODY> </HTML> Lastly my web xml file: <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>deploy</display-name> <servlet> <description> </description> <display-name>ControllerServlet</display-name> <servlet-name>ControllerServlet</servlet-name> <servlet-class>test.ControllerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ControllerServlet</servlet-name> <url-pattern>/testing/*</url-pattern> </servlet-mapping> </web-app> My web server's file manager has a folder called WEB-INF under the public_html section so in that file folder I placed the two jsps and the web xml file. Under that was a preexisting folder called classes which I made a new folder in called test and in that folder placed the two class files. I would think that going to mysite.com/testing/hello?name=Bradley would result in the correct thing happening, but unfortunately I get a 404 error saying that url testing/hello is not found. Does anyone have any suggestions as to why and can't make this happen? A: The servlet class declaration in web.xml is wrong. You're put ControllerServlet in a package test. So the proper servlet class declaration should be: <servlet-class>test.ControllerServlet</servlet-class> How you got it to work at local environment is beyond me. Perhaps the package was initially not there at all, or perhaps you removed the package from the servlet class declaration, or perhaps you've 2 servlet classes in both the default and test package. Update: based on the code given as far (and assuming that you fixed the servlet declaration in web.xml), here's how the folder structure should look like: public_html |-- WEB-INF | |-- classes | | `-- test | | |-- ControllerServlet.class | | `-- PersonBean.class | `-- web.xml |-- goodbye.jsp |-- hello.jsp `-- main.jsp A: Several things you say make me a little nervous about your questions. * *It common to use a build tool (e.g. Ant or Maven). You do not mention what build tool you are using. *It is usual to create a WAR file and deploy it to your application server (e.g. Tomcat). Although possible, it is unusual to copy class files onto your application server by hand (if you did this I think you would need to restart Tomcat to recognise this new application). *public_html does not sound like Tomcat, it sounds more like Apache. Usually Tomcat web applications are found under a directory called webapps. Your web application should consist of something like: ~webapps/deploy/WEB-INF/web.xml ~webapps/deploy/WEB-INF/classes/test/ControllerServlet.class ~webapps/deploy/WEB-INF/classes/test/PersonBean.class ~webapps/deploy/hello.jsp ~webapps/deploy/goodbye.jsp ~webapps/deploy/main.jsp ~webapps/deploy/index.jsp Usually your war let us call it deploy.war (named after the display-name in your web.xml) would contain everything in the deploy directory above. This WAR file would be deployed to Tomcat. Deployment can be done by copying the WAR file into the webapps directory of Tomcat or by using the Tomcat Manager App. index.jsp is usually the default landing page for web applications (you can change this in your web.xml).
{ "language": "en", "url": "https://stackoverflow.com/questions/7535629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Convert first letter of string to lower case I'm looking for a way to convert the first letter of a string to a lower case letter. The code I'm using pulls a random String from an array, displays the string in a text view, and then uses it to display an image. All of the strings in the array have their first letter capitalized but image files stored in the app cannot have capital letters, of course. String source = "drawable/" //monb is randomly selected from an array, not hardcoded as it is here String monb = "Picture"; //I need code here that will take monb and convert it from "Picture" to "picture" String uri = source + monb; int imageResource = getResources().getIdentifier(uri, null, getPackageName()); ImageView imageView = (ImageView) findViewById(R.id.monpic); Drawable image = getResources().getDrawable(imageResource); imageView.setImageDrawable(image); Thanks! A: public static String uncapitalize(String s) { if (s!=null && s.length() > 0) { return s.substring(0, 1).toLowerCase() + s.substring(1); } else return s; } A: Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using various CaseFormat conversions. import com.google.common.base.CaseFormat; public class CaseFormatTest { /** * @param args */ public static void main(String[] args) { String str = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "studentName"); System.out.println(str); //STUDENT_NAME str = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "STUDENT_NAME"); System.out.println(str); //studentName str = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "student-name"); System.out.println(str); //StudentName str = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "StudentName"); System.out.println(str); //student-name } } Output Like: STUDENT_NAME studentName StudentName student-name A: if (monb.length() <= 1) { monb = monb.toLowerCase(); } else { monb = monb.substring(0, 1).toLowerCase() + monb.substring(1); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Put PDF into NSData How do I put my PDF into NSData? I have the location of the PDF as a string in my Documents Directory of the app. When I try to email it, I see the PDF in the body of the email (vs seeing an attachment icon. I don't know if that's normal or not). But when I receive the email on the other end, it does not have a PDF extension. What am I doing wrong? Thanks. NSString *documentsDirectory = [self GetURLForPDF]; // I know this name is bad since it is really a NSString NSLog(@"DocumentsDirectory: %@", documentsDirectory); NSString *pdfName = [NSString stringWithFormat:@"%@/%@.pdf", documentsDirectory, title]; NSLog(@"pdfName: %@", pdfName); NSData *pdfData = [NSData dataWithContentsOfFile:pdfName]; [mailComposer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:title]; [self presentModalViewController:mailComposer animated:YES]; A: Based on how the pdfName variable is being set, it looks like your "title" value does not include the PDF suffix. Have you tried: NSString *documentsDirectory = [self GetURLForPDF]; // I know this name is bad since it is really a NSString NSLog(@"DocumentsDirectory: %@", documentsDirectory); NSString *fullTitle = [NSString stringWithFormat:@"%@.pdf", title]; NSString *pdfName = [NSString stringWithFormat:@"%@/%@", documentsDirectory, fullTitle]; NSLog(@"pdfName: %@", pdfName); NSData *pdfData = [NSData dataWithContentsOfFile:pdfName]; [mailComposer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:fullTitle]; [self presentModalViewController:mailComposer animated:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7535635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Question regarding NTFS Change Journal USN records This maybe a somewhat silly question, but I haven't been able to find the answer anywhere. Is there any way to find out what the last record in the change journal is? When we run the FSTCL query for the first time it takes too long to enumerate all the records. Is there a easy way to find it? A: FSCTL_QUERY_USN_JOURNAL returns the USN that will be used for the next record (NextUsn). The last record will normally be NextUsn minus 1. To play it safe, you could use FSCTL_ENUM_USN_DATA with USN filtering to look for NextUsn minus 1, and if it doesn't exist look for NextUsn minus 2, then minus 4, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Content disappears for fraction of a second on offline web app load I've observed this on iOS 4.3 to 5.0. When you create a even a simple offline web app, meaning one HTML file + few assets such as CSS and JS (all present in the cache manifest), it works offline (I tested in Airplane Mode) – BUT, when you add such an app to your home screen and open it in fullscreen mode, it first displays initial content, then everything disappears (page becomes white) for half a second or more, then content reappears again. You can see this by adding Glyphboard, a well-known and useful offline web app, to your iOS home screen and launching it a few times. You should see the white flash effect every time you load it. This is a big problem because it gives away the non-nativeness of an app and gives the impression that the app is non-optimized for performance and buggy. I've tried finding reports about this but all I can find is rumors and misconceptions about the iOS 4.3 JavaScript rendering engine fiasco, which doesn't need at all be related to this issue. But in iOS version 3 I distincly remember not ever seeing the white flash. A: Clearing the screen and other artifacts while rendering is a common issue of HTML rendering due to the progressive nature of HTML. The concept is that the browser should draw as early and often as possible and render styles/scripts/content as they become available. It's possible the markup has an issue where all rendering is delayed until some content or a script is available. This could happen if: * *You have dynamic heights based on image dimensions but you haven't set the image dimensions in the markup or CSS. *Your layout is based on tables and you aren't using 'table-layout:fixed` in CSS. *Your HTML uses inline scripts with document.write(). *You have some kind of onLoad() function that reveals/modifies content. *You link to an external stylesheet. *You're using uncacheable external content or you've disabled caching. *You're using external content that's returning 404 or isn't available offline. Has your HTML/CSS changed between testing IOS versions? A: I've found this to be caused by the use of: <meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=0"> With a minimal page, I get a white flash between the apple-touch-startup-image and the page contents if I use the viewport meta tag. If I take out the tag, no flash. It's possible to work around the problem by setting the tag programatically. A: I think what happens here is that iOS takes a screenshot from the page when it is added to the main menu. Then this screenshot is displayed during the application loads (WebKit loads). WebKit starts rendering the page and the page itself is constructed in such a way that the page content is not instantly available, leading to a white flash which is a rendered page when page content is not yet there, You can avoid the problem to a certain level by building your JS/CSS so that it loads the initial HTML view fast and then lazily loads / builds the rest of the resources on the background. Also you can set a custom loading screen instead of the default screenshot iOS uses from the page. Maybe if you can take yourself a screenshot of your app and then have something like this: <body style="background: white url('my-initial-loading-screen.png')" /> ... and make sure image is available and comes from manifest. Or even better, have loading screen which does not require any external resources to show (just plain HTML) so you know the browser doesn't need to load anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How smart is MongoDB? There seems to be almost no documentation about how to design databases for MongoDB. So I thought I'll start by posting my questions here. Assume this collection (fruits_inventory) as an example: { "name" : "Orange", "type" : "citric", "available" : 3 } { "name" : "Apple", "type" : "pome", "available" : 0 "note" : "Not shipping this month" } { "name" : "Pear", "type" : "pome", "available" : 2 } (No indexes set) 1) Field selection db.fruits_inventory.findOne({name:"Orange"},{"note":1}); Will this query seek for a document containing only a field name with value Orange and return with the first hit, even if it has no note field set? Or will it keep searching for a document that does contains a note field? 2) With unique indexes If I set a unique index on name, would the answer for the previous question change? Only these two questions for now. Answers will be greatly appreciated. A: I wrote the following script: // sofruit.js db = db.getSiblingDB('test'); db.fruits_inventory.drop(); db.fruits_inventory.save({ "name" : "Orange", "type" : "citric", "available" : 3 }); db.fruits_inventory.save({ "name" : "Apple", "type" : "pome", "available" : 0, "note" : "Not shipping this month" }); db.fruits_inventory.save({ "name" : "Pear", "type" : "pome", "available" : 2 }); var a1 = db.fruits_inventory.findOne({name:"Orange"},{"note":1}); db.fruits_inventory.ensureIndex({name:1}, {unique:true}); var a2 = db.fruits_inventory.findOne({name:"Orange"},{"note":1}); Then I ran it from the mongo shell and got: > load('../mongojs/sofruit.js'); > a1 { "_id" : ObjectId("4e7d119e9b3e59bf2e0c5199") } > a2 { "_id" : ObjectId("4e7d119e9b3e59bf2e0c5199") } > So, the answer is "Yes," it will return the first hit, even if it has no "note" field set. Adding an index doesn't change that. A: You can connect directly to mongodb and check it: MongoDB shell version: 2.0.0 connecting to: test > use test switched to db test > db.fruits_inventory.save({ ... "name" : "Orange", ... "type" : "citric", ... "available" : 3 ... }); > db.fruits_inventory.save({ ... "name" : "Pear", ... "type" : "pome", ... "available" : 2 ... }) > db.fruits_inventory.save({ ... "name" : "Apple", ... "type" : "pome", ... "available" : 0, ... "note" : "Not shipping this month" ... }) > db.fruits_inventory.find() { "_id" : ObjectId("4e7d0fa5626e0ab7b5074bb0"), "name" : "Orange", "type" : "citric", "available" : 3 } { "_id" : ObjectId("4e7d101b626e0ab7b5074bb1"), "name" : "Pear", "type" : "pome", "available" : 2 } { "_id" : ObjectId("4e7d1059626e0ab7b5074bb2"), "name" : "Apple", "type" : "pome", "available" : 0, "note" : "Not shipping this month" } > db.fruits_inventory.find({name: "Orange"},{"note":1}) { "_id" : ObjectId("4e7d0fa5626e0ab7b5074bb0") } > db.fruits_inventory.ensureIndex({name:1}, {unique:true}) > db.fruits_inventory.find({name: "Orange"},{"note":1}) { "_id" : ObjectId("4e7d0fa5626e0ab7b5074bb0") } So in answer to your question, when you query for the note field, it will just return the id and having a unique index makes no difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Remove a tracking from a git branch I have a "feature/admin" branch that is tracking multiple branches (origin/feature/admin and development, the latter being local) - I want to remove the local tracking (so my local branch only tracks the remote branch origin/feature/admin). I've tried removing it with git branch -dr development, but... error: remote branch 'development' not found. Any suggestions? A: I found the answer to this little dilemma. In the Git Config file of the repo, I deleted these two lines (using Gity): Keys: branch.feature/admin.remote branch.feature/admin.merge Values: . refs/heads/development (respectively) That removed the local tracking. I'm guessing the "." indicates local. A: The name "development" isn't a remote branch, since it doesn't include the name of a remote. Take a look at the output of git branch -a: * develop master remotes/origin/HEAD -> origin/master remotes/origin/develop remotes/origin/master The remote branches all start with the remotes/ prefix. So to delete the remote "develop" branch, I would run: git branch -dr origin/develop Although, having done this, the branch will come back next time I do a git pull.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Updating DBGrids in Master-Detail views when updating Cells in Delphi I am using TADOConn and TADODataSet units pulling data and connected to TDataSources and TDBGrids. I have my DBGrids displaying information properly and editing information in the detail view accurately reflects in the backing database. What I would like to do is have it so that an update to a field in the detail DBGrid causes a refresh on both data sets so that the most up-to-date data is always displayed. I have tried putting the refresh calls in several event handlers at various levels of DB access but they all seem to have a similar (but different) issue of reentry. The best I've been able to come up with so far is getting the Master view updated by calling refresh on the details DBGrid.onColExit event. If I leave the refresh calls out all together the updated information isn't displayed until the next time the application is run. Any ideas of how to achieve this? Am I going about it the wrong why? Thanks in advance. A: You imply that the changes you make in the DBGrid are posted to the database but are not displayed in the grid or maintained in its dataset and that you must get them back from the database. All the dataset components I have used maintain its copy of the data including all the changes that passed through it to the database. If you expect the data to be changed by triggers or another process, you may need to refresh the data. Then you will have to deal with the possibility that the current record position is lost, i.e. the current record was deleted in the database. I would try using the Dataset.AfterPost event to initiate the refresh. And I would consider using a Timer to delay the refresh if strange things happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Positive Look ahead in Regular Expressions? I'm trying to extract some characters or words from a string using regular expressions.. Examples of my string contains "Size: M" or "Size: Medium" and I want to extract "M" and "Medium" These can be anywhere within a long string so... I was trying to use the following but it brings back the colon. :\s\w Result : M But I just want the size and no the colon, I was looking at positive look ahead but not having any luck still excluding the colon. A: Use a look-behind so the whole regex matches what you want (no need to use matching groups) (?<=Size: )\w+ Explanation: * *(?<=Size: ) means the chars immediately preceding the match must be the literal "Size: ", and importantly is non-capturing *\w+ means "a word" A: You will just want to use a capturing group: Size:\s(\w) And then the letter will be contained in the first capture group. You didn't specify what language you are using, but any decent language will have the concept of capturing groups.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fault free ColdFusion app update process When updating a ColdFusion website, with svn or git, there is a moment where half of the repo is updated and the other half is not, during which a request could occur, which could mean epic fails in some cases. So it seems like I need a way of pausing the requests made while svn/git is updating the folder which a website's source resides. After which point I can have a updated version number trigger the app to update itself before responding to any requests. It's a short amount of time, but could cause many different problems depending on the app. Does anyone have any useful advice? A: For our applications we follow Adam's advice and remove a node from the load balancer; however, for those who only have one server there is an easy solution. * *Login to the ColdFusion Administrator *Click "Caching" on the left side bar *Ensure the "Trusted Cache" setting is selected. *Going forward, after you have completed a code checkout you will "Clear the Template Cache" which can be achieved on the "Caching" page, using the CFAdmin API or using the Adobe Air ColdFusion Server Manager application. This setting will ensure your new CFML code is not "live" until you clear the template cache after a successful code checkout from your SCM. Additionally, this can bring a performance improvement as much as 40% since ColdFusion will no longer check your .cfc/.cfm files for changes. All production servers should run with this setting checked. A: Typically this sort of problem is mitigated when you use a cluster. (But not the primary reason to use one.) You drain all connections from one node, remove it from the cluster, update it, put it back into the cluster, remove another, and repeat, until all nodes are updated. You don't have to do them all in serial, there are plenty of ways to do it if you have several nodes. But that's the general idea. A: If you have control of the web server, then you can re-route public requests to another folder that contains a maintenance message only. Otherwise, you can use onRequestStart to redirect all requests to a maintenance.cfm file. A: This is just a thought I don't know if it would work. But what if you were, at the beginning of your deployment process, to replace your Application.cfc with a new one that had this in the onRequestStart() method? <cffunction name="onRequestStart"> <cfset sleep(5000) /> </cffunction> Then when the deployment is done, replace the cfc again with the original. You might even be able to make it cleaner with a cfinclude. <cffunction name="onRequestStart"> <cfinclude template="sleep.cfm" /> </cffunction> Then you could just replace the sleep.cfm file with an empty file when you don't want the sleep() to happen
{ "language": "en", "url": "https://stackoverflow.com/questions/7535667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: auto-Writing/auto-Inputting application for a lousy routine web-based submitions? I've started learning python for a week, as always love to learn as much languages as I can ; as python is one of the easiest languages, but still there's lots of things teachers won't tell. Interacting with web pages is an obvious example; registration in forums and other websites gives a headache, so building a simple python application that just can READ LABELS, and input INFORMATION such as First Name, Last Name, Sex, and Address in their TEXT BOXES, then Submit the page at the end would be fantastic. Another silly thing, but I MUST know, is how to contact a website first. If you can provide me with any tips, or help, I appreciate your contribution. A: For a simply contacting the website, consider the requests or twill libraries. For screen-scraping, BeautifulSoup is your friend. If third-party libraries really aren't an option, though, you'll need to delve into the htmllib, httplib, urllib, and urllib2 Python modules.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About TidHttp, mshtml, ActiveX, COMObj in Firemonkey (Delphi) I was reviewing the following interesting article, "Extract Links from HTML page using Delphi", and I tested in Firemonkey and it's very useful, however this code uses objects from Mshtml, ActiveX, and COMObj, so my questions are: * *do those objects above make less cross-platform for a Firemonkey project? if so, How could I get the same functionality using resources targeted for Firemonkey platform? *How I can emulate a little webbrowser in firemonkey? Thanks in advance. Note: ChromiumEmbedded object does't work for Firemonkey. A: MSHTML, ActiveX, and ComObj are all Windows-specific, and therefore are not cross-platform in any way. There are no cross-platform HTML viewers for FireMonkey yet, AFAIK (it's been asked at the Embarcadero Delphi forums). TIdHTTP is available for Win32, Win64, and OSX; it's not available yet for iOS - see this post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Executing a javascript that is injected as a script element via bookmarklet? I am using bookmarklet to inject a element in document with a custom JS script file. I did it like this: var newscript = document.createElement('script'); newscript.type = 'text/javascript'; newscript.async = true; newscript.src = 'http://www.myurl.com/my_js_script.js'; var oldscript = document.getElementsByTagName('script')[0]; oldscript.parentNode.insertBefore(newscript, oldscript); But I can't figure out how to actually execute it. Can someone tell me how can I execute that JS file? Note: Since this can be a Greasemonkey script as well, I am tagging this question for Greasemonkey as well. A: Script tags are automatically downloaded and executed when they're added to the document. Note, however, that the script you're using may fail if the document you're injecting into doesn't already contain any <script> tags, as oldscript will be undefined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: bash: passing paths with spaces as parameters? I have a bash script that recieves a set of files from the user. These files are sometimes under directories with spaces in their names. Unfortunately unlike this question all the filenames are passed via the command line interface. Let's assume the paths are correctly quoted as they are passed in by the user, so spaces (save for quoted spaces) are delimiters between paths. How would I forward these parameters to a subroutine within my bash script in a way that preserves the quoted spaces? A: You want "$@", which has the special syntax of expanding $@ but preserving the white-space quoting of the caller (it does not create a single giant string with all the arguments in it). So someone can call your script like: bash-script.sh AFile "Another File With Spaces" Then in your script you can do things like: for f in "$@"; do echo "$f"; done and get two lines of output (not 5). Read the paragraph about the Special Parameter "@" here: http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters A: #! /bin/bash for fname in "$@"; do process-one-file-at-a-time "$fname" done Note the excessive use of quotes. It's all necessary. Passing all the arguments to another program is even simpler: process-all-together "$@" The tricky case is when you want to split the arguments in half. That requires a lot more code in a simple POSIX shell. But maybe the Bash has some special features. A: Bravo @Roland . Thans a lot for your solution It has really worked! I wrote a simple script function that opens a given path with nautilus. And I've just nested a function with this "helper"-for-loop into the main function: fmp () { fmp2() { nautilus "$@"; }; for fname in "$@"; do fmp2 "$fname"; done; } Now I'm able to make all my scripts work handling with paths just by turning them into nested functions wrapped by a function with this helper-for-loop. A: "$var" For example, $ var='foo bar' $ perl -E'say "<<$_>>" for @ARGV' $var <<foo>> <<bar>> $ perl -E'say "<<$_>>" for @ARGV' "$var" <<foo bar>>
{ "language": "en", "url": "https://stackoverflow.com/questions/7535677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to retrieve class values from WEKA using MATLAB I'm trying to retrieve classes from WEKA using MATLAB and WEKA API. All looks fine but classes are always 0. Any idea ?? My data set has 241 atributes, applying WEKA to this dataset I'm obtaining correct results. 1st train and test objects are created than classifier is build and classifyInstance performed. But this give wrong result train = [xtrain ytrain]; test = [xtest]; save ('train.txt','train','-ASCII'); save ('test.txt','test','-ASCII'); %## paths WEKA_HOME = 'C:\Program Files\Weka-3-7'; javaaddpath([WEKA_HOME '\weka.jar']); fName = 'train.txt'; %## read file loader = weka.core.converters.MatlabLoader(); loader.setFile( java.io.File(fName) ); train = loader.getDataSet(); train.setClassIndex( train.numAttributes()-1 ); % setting class as nominal v(1) = java.lang.String('-R'); v(2) = java.lang.String('242'); options = cat(1,v(1:end)); filter = weka.filters.unsupervised.attribute.NumericToNominal(); filter.setOptions(options); filter.setInputFormat(train); train = filter.useFilter(train, filter); fName = 'test.txt'; %## read file loader = weka.core.converters.MatlabLoader(); loader.setFile( java.io.File(fName) ); test = loader.getDataSet(); %## dataset relationName = char(test.relationName); numAttr = test.numAttributes; numInst = test.numInstances; %## classification classifier = weka.classifiers.trees.J48(); classifier.buildClassifier( train ); fprintf('Classifier: %s %s\n%s', ... char(classifier.getClass().getName()), ... char(weka.core.Utils.joinOptions(classifier.getOptions())), ... char(classifier.toString()) ) classes =[]; for i=1:numInst classes(i) = classifier.classifyInstance(test.instance(i-1)); end Here is a new code but still not working - classes = 0. Output from Weka for the same algo and data set is OK === Detailed Accuracy By Class === TP Rate FP Rate Precision Recall F-Measure ROC Area Class 0.99 0.015 0.985 0.99 0.988 0.991 0 0.985 0.01 0.99 0.985 0.988 0.991 1 Weighted Avg. 0.988 0.012 0.988 0.988 0.988 0.991 === Confusion Matrix === a b <-- classified as 1012 10 | a = 0 15 1003 | b = 1   ytest1 = ones(size(xtest,1),1); train = [xtrain ytrain]; test = [xtest ytest1]; save ('train.txt','train','-ASCII'); save ('test.txt','test','-ASCII'); %## paths WEKA_HOME = 'C:\Program Files\Weka-3-7'; javaaddpath([WEKA_HOME '\weka.jar']); fName = 'train.txt'; %## read file loader = weka.core.converters.MatlabLoader(); loader.setFile( java.io.File(fName) ); train = loader.getDataSet(); train.setClassIndex( train.numAttributes()-1 ); v(1) = java.lang.String('-R'); v(2) = java.lang.String('242'); options = cat(1,v(1:end)); filter = weka.filters.unsupervised.attribute.NumericToNominal(); filter.setOptions(options); filter.setInputFormat(train); train = filter.useFilter(train, filter); fName = 'test.txt'; %## read file loader = weka.core.converters.MatlabLoader(); loader.setFile( java.io.File(fName) ); test = loader.getDataSet(); filter = weka.filters.unsupervised.attribute.NumericToNominal(); filter.setOptions( weka.core.Utils.splitOptions('-R last') ); filter.setInputFormat(test); test = filter.useFilter(test, filter); %## dataset relationName = char(test.relationName); numAttr = test.numAttributes; numInst = test.numInstances; %## classification classifier = weka.classifiers.trees.J48(); classifier.buildClassifier( train ); fprintf('Classifier: %s %s\n%s', ... char(classifier.getClass().getName()), ... char(weka.core.Utils.joinOptions(classifier.getOptions())), ... char(classifier.toString()) ) classes = zeros(numInst,1); for i=1:numInst classes(i) = classifier.classifyInstance(test.instance(i-1)); end here is a code snippet for class distribution in Java // output predictions System.out.println("# - actual - predicted - error - distribution"); for (int i = 0; i < test.numInstances(); i++) { double pred = cls.classifyInstance(test.instance(i)); double[] dist = cls.distributionForInstance(test.instance(i)); System.out.print((i+1)); System.out.print(" - "); System.out.print(test.instance(i).toString(test.classIndex())); System.out.print(" - "); System.out.print(test.classAttribute().value((int) pred)); System.out.print(" - "); if (pred != test.instance(i).classValue()) System.out.print("yes"); else System.out.print("no"); System.out.print(" - "); System.out.print(Utils.arrayToString(dist)); System.out.println(); I converted it to MATLAB code like this classes = zeros(numInst,1); for i=1:numInst pred = classifier.classifyInstance(test.instance(i-1)); classes(i) = str2num(char(test.classAttribute().value(( pred)))); end but classes are output incorrectly. In your answer you dont show that pred contains classes and predProb probabilities. Just print it !!! A: Training and testing data must have the same number of attributes. So in your case, even if you don't know the actual class of the test data, just use dummy values: ytest = ones(size(xtest,1),1); %# dummy class values for test data train = [xtrain ytrain]; test = [xtest ytest]; save ('train.txt','train','-ASCII'); save ('test.txt','test','-ASCII'); Don't forget to convert it to a nominal attribute when you load the test dataset (like you did for the training dataset): filter = weka.filters.unsupervised.attribute.NumericToNominal(); filter.setOptions( weka.core.Utils.splitOptions('-R last') ); filter.setInputFormat(test); test = filter.useFilter(test, filter); Finally, you can call the trained J48 classifier to predict the class values for the test instances: classes = zeros(numInst,1); for i=1:numInst classes(i) = classifier.classifyInstance(test.instance(i-1)); end EDIT It is difficult to tell without knowing the data you are working with.. So let me illustrate with a complete example. I am going to be creating the datasets in MATLAB out of the Fisher Iris data (4 attributes, 150 instances, 3 classes). %# load dataset (data + labels) load fisheriris X = meas; Y = grp2idx(species); %# partition the data into training/testing c = cvpartition(Y, 'holdout',1/3); xtrain = X(c.training,:); ytrain = Y(c.training); xtest = X(c.test,:); ytest = Y(c.test); %# or dummy values %# save as space-delimited text file train = [xtrain ytrain]; test = [xtest ytest]; save train.txt train -ascii save test.txt test -ascii I should mention here that it is important to make sure that the class values are fully represented in each of the two datasets before using the NumericToNominal filter. Otherwise, the train and test sets could be incompatible. What I mean is that you must have at least one instance from every class value in each. Thus if you are using dummy values, maybe we can do this: ytest = ones(size(xtest,1),1); v = unique(Y); ytest(1:numel(v)) = v; Next, lets read the newly created files using Weka API. We convert the last attribute from numeric to nominal (to enable classification): %# read train/test files using Weka fName = 'train.txt'; loader = weka.core.converters.MatlabLoader(); loader.setFile( java.io.File(fName) ); train = loader.getDataSet(); train.setClassIndex( train.numAttributes()-1 ); fName = 'test.txt'; loader = weka.core.converters.MatlabLoader(); loader.setFile( java.io.File(fName) ); test = loader.getDataSet(); test.setClassIndex( test.numAttributes()-1 ); %# convert last attribute (class) from numeric to nominal filter = weka.filters.unsupervised.attribute.NumericToNominal(); filter.setOptions( weka.core.Utils.splitOptions('-R last') ); filter.setInputFormat(train); train = filter.useFilter(train, filter); filter = weka.filters.unsupervised.attribute.NumericToNominal(); filter.setOptions( weka.core.Utils.splitOptions('-R last') ); filter.setInputFormat(test); test = filter.useFilter(test, filter); Now we train a J48 classifier and use it to predict the class of the test instances: %# train a J48 tree classifier = weka.classifiers.trees.J48(); classifier.setOptions( weka.core.Utils.splitOptions('-c last -C 0.25 -M 2') ); classifier.buildClassifier( train ); %# classify test instances numInst = test.numInstances(); pred = zeros(numInst,1); predProbs = zeros(numInst, train.numClasses()); for i=1:numInst pred(i) = classifier.classifyInstance( test.instance(i-1) ); predProbs(i,:) = classifier.distributionForInstance( test.instance(i-1) ); end Finally, we evaluate the trained model performance over the test data (this should look similar to what you see in Weka Explorer). Obviously this only makes sense if the test instances have the true class value (not dummy values): eval = weka.classifiers.Evaluation(train); eval.evaluateModel(classifier, test, javaArray('java.lang.Object',1)); fprintf('=== Run information ===\n\n') fprintf('Scheme: %s %s\n', ... char(classifier.getClass().getName()), ... char(weka.core.Utils.joinOptions(classifier.getOptions())) ) fprintf('Relation: %s\n', char(train.relationName)) fprintf('Instances: %d\n', train.numInstances) fprintf('Attributes: %d\n\n', train.numAttributes) fprintf('=== Classifier model ===\n\n') disp( char(classifier.toString()) ) fprintf('=== Summary ===\n') disp( char(eval.toSummaryString()) ) disp( char(eval.toClassDetailsString()) ) disp( char(eval.toMatrixString()) ) The output in MATLAB for the example above: === Run information === Scheme: weka.classifiers.trees.J48 -C 0.25 -M 2 Relation: train.txt-weka.filters.unsupervised.attribute.NumericToNominal-Rlast Instances: 100 Attributes: 5 === Classifier model === J48 pruned tree ------------------ att_4 <= 0.6: 1 (33.0) att_4 > 0.6 | att_3 <= 4.8 | | att_4 <= 1.6: 2 (32.0) | | att_4 > 1.6: 3 (3.0/1.0) | att_3 > 4.8: 3 (32.0) Number of Leaves : 4 Size of the tree : 7 === Summary === Correctly Classified Instances 46 92 % Incorrectly Classified Instances 4 8 % Kappa statistic 0.8802 Mean absolute error 0.0578 Root mean squared error 0.2341 Relative absolute error 12.9975 % Root relative squared error 49.6536 % Coverage of cases (0.95 level) 92 % Mean rel. region size (0.95 level) 34 % Total Number of Instances 50 === Detailed Accuracy By Class === TP Rate FP Rate Precision Recall F-Measure ROC Area Class 1 0 1 1 1 1 1 0.765 0 1 0.765 0.867 0.879 2 1 0.118 0.8 1 0.889 0.938 3 Weighted Avg. 0.92 0.038 0.936 0.92 0.919 0.939 === Confusion Matrix === a b c <-- classified as 17 0 0 | a = 1 0 13 4 | b = 2 0 0 16 | c = 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7535689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Pass data into change event callback? Using backbone.js - I want to bind an event to any change in the model and the collections/models that are nested inside it. Right now I do an @bind 'change', () -> when initializing the base model. How can I pass data on any change, even that of deep nested models? Does the change event carry variables with it? I need things like the model's collection, id, attributes, etc. Thanks. A: Does the change event carry variables with it? Yes, the change event gets two arguments: First, the model itself; second, the new attribute value. There are several methods available on the model that are aimed specifically at getting information during a change event. See the docs on hasChanged, changedAttributes, previous, and previousAttributes. So for instance, to access the previous attributes of a model each time it changes, you'd write @bind 'change', (model) -> prevAttrs = model.previousAttributes() ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7535691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parser ASP page with PHP With this code <?php /*GET ALL LINKS FROM http://www.w3schools.com/asp/default.asp*/ $page = file_get_contents('http://www.codacons.it/rassegna_quest.asp?idSez=14'); preg_match_all("/<a.*>(.*?)<\/a>/", $page, $matches, PREG_SET_ORDER); echo "All links : <br/>"; foreach($matches as $match){ echo $match[1]."<br/>"; } ?> But it not parse this link from this page http://www.codacons.it/rassegna_quest.asp?idSez=14 'Questionario': OFFICINE PER L'ASSISTENZA E MANUTENZIONI VEICOLI 'Questionario': RIVENDITORE AUTO USATE 'Questionario': RACCOLTA RICICLATA DEI RIFIUTI DI IMBALLAGGI IN PLASTICA 'Questionario': DONNE E POLITICA Why ??? A: I guess I should start with the typical "Don't parse HTML with regex". This would be easy with XPath (using DOMXpath): $dom = new DOMDocument(); @$dom->loadHTML($page); $dom_xpath = new DOMXPath($dom); $entries = $dom_xpath->evaluate("//a"); foreach ($entries as $entry) { print $entry->nodeValue; } But if you must go the regex route, I imagine the greedy star .* is the source of your problems. Try this: preg_match_all("@<a[^>]+>(.+?)</a>@/", $page, $matches, PREG_SET_ORDER); A: Ah, whatever... $page = file_get_contents('http://www.codacons.it/rassegna_quest.asp?idSez=14'); preg_match_all('#<a href="articolo(.*?)" title="Dettaglio notizia">(.*?)</a>#is', $page, $matches); $count = count($matches[1]); for($i = 0; $i < $count; $i++){ echo '<a href="articolo'.$matches[1][$i].'">'.trim(strip_tags(preg_replace('#(\s){2,}#is', '', $matches[2][$i]))).'</a>'; } Result: <a href="articolo.asp?idInfo=138400&amp;id=">'Questionario':OFFICINE PER L'ASSISTENZA E MANUTENZIONI VEICOLI</a> <a href="articolo.asp?idInfo=138437&amp;id=">'Questionario':RIVENDITORE AUTO USATE</a> <a href="articolo.asp?idInfo=127900&amp;id=">'Questionario':RACCOLTA RICICLATA DEI RIFIUTI DI IMBALLAGGI IN PLASTICA</a> <a href="articolo.asp?idInfo=138861&amp;id=">'Questionario':DONNE E POLITICA</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7535692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Universal app splash screen errors I have created a universal app in x code 4 and am attempting to use their "launch images". I am however running into an issue where once the iPad splash screen displays it will flash to the iPhone splash screen quickly before going into the application. Has anyone else run into this and is there a fix? Thanks! A: I experienced this on a universal app, but it was because I implemented a custom fade sequence that referenced the iPhone default.png during launch (even on an iPad). Once I figured that out, I just set a check for whether the device was an iPad, and if so, disabled the fade call. Do you reference the file in any way aside from the typical launch?
{ "language": "en", "url": "https://stackoverflow.com/questions/7535694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to infer the type of an object and use that type in a generic parameter during construction Is there another way of declaring my ProductController for the logger that is being injected? public class ProductController : Controller { private readonly LoggingInterface.ILogger<ProductController> _logger; private readonly IProductRepository _productRepository; public ProductController(LoggingInterface.ILogger<ProductController> logger, IProductRepository productRepository) { _logger = logger; _productRepository = productRepository; } { Thank you, Stephen A: Inference requires the use of an open generic. There are none in this sample A: If I'm not mistaken, what you're looking to do (wishing you could do) is something like: class ProductController<T> : Controller where T : ProductController { ILogger<T> _logger; ... etc } I think that you can get a fairly flexible interface if you pull back a little from your design. You have three parts here -- a controller, a logger, and the object of the controller and logger, which I'll call a data transfer object. So, you have "controller of product" and "logger of product" (which you're currently calling "logger of controller of product"). Let's say that you have this DTO object structure: public class DataTransferBase { /*This is what both logger and controller operate on*/ } public class Product : DataTransferBase { } Now, instead of the logger concerning itself with controllers, why not have the logger and controller both concern themselves with DTOs? So logger is like: public interface ILogger { void Log(string message); } public interface ILogger<T> : ILogger where T : DataTransferBase { void Log(T item); } public class FileLogger<T> : ILogger<T> where T : DataTransferBase { public virtual void Log(T item) { /* Write item.ToString() to a file or something */ } public void Log(string message) { /* Write the string to a file */ } } ... and controller is like: public interface IController<T> where T : DataTransferBase {} public class Controller<T> : IController<T> where T : DataTransferBase { /// <summary>Initializes a new instance of the ProductController class.</summary> public Controller(ILogger<T> logger) { } public virtual List<T> GetItems() { return new List<T>(); } } What you have here now is a logger that will operate on any DTO and a controller that will operate on any DTO, and that controller happens to take as a constructor parameter, a logger that will operate on the same DTO that it does. Now, you can have more specific implementations if you want: public class ProductFileLogger : FileLogger<Product> { public override void Log(Product item) { /* Get all specific with item */} } and public class ProductController : Controller<Product> { /// <summary> /// Initializes a new instance of the ProductController class. /// </summary> public ProductController(ILogger<Product> productLogger) : base(productLogger) { } public override List<Product> GetItems() { return new List<Product>(); } } And, you can wire these up as specifically or generally as you please: public class Client { private void DoSomething() { IController<Product> myController = new ProductController(new ProductFileLogger()); //If you want to be specific IController<Product> myController2 = new Controller<Product>(new ProductFileLogger()); //If you want a generic controller and specific logger IController<Product> myController3 = new Controller<Product>(new FileLogger<Product>()); //If you want to be as generic as possible } } Please note, that I just kind of whipped this up on the fly, so it may not be optimal, but I'm just trying to convey the general idea. You can't declare a class with a generic type of itself (as far as I know), but you can have two classes interact (controller and logger) that operate on the same generic type. That is, IController can own an ILogger and when you instantiate IController, you force its logger to operate on the same type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Subscribe to all messages from NServiceBus I'd like to subscribe to all messages being sent across the NServiceBus system, for the purpose of logging and monitoring. However trying to listen for IMessage doesn't work, ideas? A: NServiceBus has explicit support for auditing through the ForwardReceivedMessagesTo configuration option. Have your admins configure each of your endpoints to forward the messages to a central audit queue. A: * *Write to the event log in all your IMessageHandler implementations. *Get SCOM to monitor the event logs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Objective C - UITabViewController disable tabBar I'm using a UITabBarController in my app. How can I disable people from clicking the tabs? Trying to disallow people from clicking away to another section before some of the things that is going on is done. Thank you, Tee A: Figured it out. UITabBarController.tabbar.userInteractionEnabled = NO;//disable UITabBarController.tabbar.userInteractionEnabled = YES;//enable A: You really shouldn't do that, it's very counterintuitive to the user. Instead of temporarily disabling user interaction with tabbar, present your content in a modal view (it completely overlaps the tabbar making user unable to change the tab).
{ "language": "en", "url": "https://stackoverflow.com/questions/7535701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3 Make Text into a Clickable Link I've made a Rails 3 app and I've got a form on my page in which I have users copy and paste a link and then submit it (much like Reddit) and then ideally, the link would appear on the main page for other users to click on. However, whenever users paste the URL's into my form, the link is not clickable, it is only text. Does anyone know any solutions for this? Any help would be greatly appreciated! Thank you! A: So say your object is in @post In the display, do <%= link_to @post.url, @post.url %> That should "linkify" your URL so that users can click it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Source property of Silverlight object <div id="silverlightControlHost" > <object id="idThObject" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/MySolution.xap"/> <!--<param name="source" value="http://www.mysite.com/ClientBin/MySolution.xap"/> **NOT WORK**--> ... </div> Hi to ALL ! My Silverlight object exist on sever side in folder and when I try to load it like this : <param name="source" value="http://www.mysite.com/ClientBin/WebSolution.xap" /> This is doesn't work, but it I load this locally : <param name="source" value="ClientBin/MySolution.xap"/>, it's work fine. So what can I do to load my *.xap file from server or I don't have any chance to do it ? A: Please check that you have added the required mimetypes for silverlight in IIS on the server. map the following. * *.xap application/x-silverlight-app *.xaml application/xaml+xml *.xbap application/x-ms-xbap A: I didn't change any values of any type in html code. Visual Studio 2010 create standard template : <div id="silverlightControlHost" style="font-size: small;color: red;"> <object id="idThObject" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/WebSolution.xap"/> <param name="onerror" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="3.0.40818.0" /> <param name="autoUpgrade" value="true" <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0" style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/> </a> </object><iframe id='_sl_historyFrame' style='visibility:hidden;height:0;width:0;border:0px'></iframe></div> Only one point : provider of my site yahoo.com. So by default this guys don't use IIS. So you think this is problem ? That Apache doesn't know this : < ...data="data:application/x-silverlight," type="application/x-silverlight-2"/> look like I have to move to another provider, which support IIS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails Searchable Plugin with a logical OR I am using the Searchable plugin's query builder to try and build a query that searches some content and only returns objects that the user is the audience of or the audience is global. The code I would like to have would be similar to: { term("content", content) or { term('reach', 'global') term('audience$user', User) } } But there is no 'or' for this, how do I say that I want one of my field to have a term AND have one of two other conditions met with the searchable's query builder DSL? This seems like a dumb question, but I've been searching for quite a while and can't find an answer. A: I would use the grammar of the searchable plugin: search("+content:${content} +(reach:global OR audience.user.id:${user.id})") Not sure what you meant with 'audience$user' though. Look here for details: http://grails.org/Searchable+Plugin+-+Searching+-+String+Queries http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Boolean%20operators A: This is a very late answer, but the correct way with the builder would be { must(term("content", content)) must { term('reach', 'global') term('audience$user', User) } } apart from that I'm also not sure what you mean with audience$user. See http://grails.1312388.n4.nabble.com/Searchable-plugin-s-query-builder-nested-or-query-td1388307.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7535707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I check if the android phone is charging I am writing an android application. I would like to know how can I check if the phone is charging when my application starts? I have read this How to know if the phone is charging But this only register and get notified when there is a change in charging state of the phone (from charging to stop charging or vice versa). But what if the phone is charging when my application starts, how can I cover that case? I have looked up PowerManager and USBManager in android. Neither has API which provides what I need. Thank you. A: It has become much more simple API 23 onwards, you can check using an object of BatteryManger and call the isCharging function. BatteryManager myBatteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE); public boolean isUSBCharging(){ return myBatteryManager.isCharging(); } https://developer.android.com/reference/android/os/BatteryManager.html#isCharging() A: This question provides the code you might be looking for: Event ACTION_POWER_CONNECTED is not sent to my BroadcastReceiver There's also a ACTION_POWER_DISCONNECTED action. This question is telling that the broadcast is sticky, so even available when you miss the broadcast: Android Battery in SDK
{ "language": "en", "url": "https://stackoverflow.com/questions/7535713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Convert 8 bit ( 16 Color Palette ) PNG to proper 4 bit ( 16 color Palette ) with Java or Python? I have a bunch of images, to many to do by hand that are 16 color 8 bit PNG format that I need in 16 4 bit format, they all have the same palette. I am scouring Google for the best library to use, but I am not finding much on this specific problem so I am coming here for hopefully some more targeted solutions. I am trying to use PIL based on other answers I have found here, but not having any luck. img = Image.open('DownArrow_focused.png') img = img.point(lambda i: i * 16, "L") img.save('DownArrow_focused.png', 'PNG') but this gives me a grayscale image, not what I want. PIL won't work, trying PyPNG. GIMP does this, but I have hundreds of these things I need to batch process them. And get batches of these to convert, so it isn't a one time thing. A Java based solution would be acceptable as well, pretty much anything I can run from the command line on a Linux/OSX machine will be acceptable. A: In PNG the palette is always stored in RGB8 (3 bytes for each index=color), with an arbitrary (up to 256) number of entries. If you currently have a 8 bit image with a 16-colors palette (16 total entries), you dont need to alter the pallete, only to repack the pixel bytes (two indexes per byte). If so, I think you could do it with PNGJ with this code (untested): public static void reencode(String orig, String dest) { PngReader png1 = FileHelper.createPngReader(new File(orig)); ImageInfo pnginfo1 = png1.imgInfo; ImageInfo pnginfo2 = new ImageInfo(pnginfo1.cols, pnginfo1.rows, 4, false,false,true); PngWriter png2 = FileHelper.createPngWriter(new File(dest), pnginfo2, false); png2.copyChunksFirst(png1, ChunksToWrite.COPY_ALL); ImageLine l2 = new ImageLine(pnginfo2); for (int row = 0; row < pnginfo1.rows; row++) { ImageLine l1 = png1.readRow(row); l2.tf_pack(l1.scanline, false); l2.setRown(row); png2.writeRow(l2); } png1.end(); png2.copyChunksLast(png1, ChunksToWrite.COPY_ALL); png2.end(); System.out.println("Done"); } Elsewhere, if your current pallette has 16 "used" colors (but its length is greater because it includes unused colors), you need to do some work, modifying the palette chunk (but it also can be done). A: Call Netpbm programs http://netpbm.sourceforge.net/ from a Python script using the following commands: $ pngtopnm test.png | pnmquant 16 | pnmtopng > test16.png $ file test16.png test16.png: PNG image data, 700 x 303, 4-bit colormap, non-interlaced And GIMP reports test16.png as having Color space: Indexed color (16 colors), which I guess is what you want. This is not a pure Python solution but PIL is also not pure Python and has dependencies on shared libraries too. I think you cannot avoid a dependency on some external image software.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why do I get an extra element at the end in JSON? I'm working on some website, and am using JSON. My problem is the JSON.parse method, I use it to send a simple array, and append to an array the values. And I always get an extra element at the end that us just commas. here is the simplified code: responseText = '["dummy1", "dummy2", "dummy3", "dummy4"]'; var clientList=[]; try { JSON.parse(responseText, function(key, val){clientList.push(val)}); } catch (e) { alert('no'); } alert(clientList.length); First in IE its not working at all (exception is thrown). Second chrome the result is that clientList is an array of 5 strings, while the last one is ',,, '. Why is that extra value there? Can I get rid of it (without just popping the array at the end)? And what is wrong with IE? A: This will work: responseText = '["dummy1", "dummy2", "dummy3", "dummy4"]'; var clientList=[]; try { clientList = JSON.parse(responseText); } catch (e) { alert('no'); } IE doesn't have JSON as a default in the browser. You need a library like json2. As for your question, that callback function is really in order to transform your object not build it. For example: var transformed = JSON.parse('{"p": 5}', function(k, v) { if (k === "") return v; return v * 2; }); // transformed is { p: 10 } From parse A: There are differences in using JSON under different browsers. One way is to do what IAbstractDownvoteFactory said. Another way is to use jQuery library and clientList = $.parseJSON(responseText); should do the job under any browser (although I did not test it under IE).
{ "language": "en", "url": "https://stackoverflow.com/questions/7535724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is garbage collection detrimental to the performance of this type of program I'm building a program that will live on an AWS EC2 instance (probably) be invoked periodically via a cron job. The program will 'crawl'/'poll' specific websites that we've partnered with and index/aggregate their content and update our database. I'm thinking java is a perfect fit for a language to program this application in. Some members of our engineering team are concerned about the performance detriment of java's garbage collection feature, and are suggesting using C++. Are these valid concerns? This is an application that will be invoked possible once every 30 minutes via cron job, and as long as it finishes its task within that time frame the performance is acceptable I would assume. I'm not sure if garbage collection would be a performance issue, since I would assume the server will have plenty of memory and the actual act of tracking how many objects point to an area of memory and then declaring that memory free when it reaches 0 doesn't seem too detrimental to me. A: Fetching and parsing websites will take way more time than the garbage collector, its impact will be probably neliglible. Moreover, the automatic memory management is often more efficient when dealing with a lot of small objects (such as strings) than a manual memory management via new/delete. Not talking about the fact that the garbage collected memory is easier to use. A: I don't have any hard numbers to back this up, but code that does a lot of small string manipulations (lots of small allocations and deallocations in a short period of time) should be much faster in a garbage-collected environment. The reason is that modern GC's "re-pack" the heap on a regular basis, by moving objects from an "eden" space to survivor spaces and then to a tenured object heap, and modern GC's are heavily optimized for the case where many small objects are allocated and then deallocated quickly. For example, constructing a new string in Java (on any modern JVM) is as fast as a stack allocation in C++. By contrast, unless you're doing fancy string-pooling stuff in C++, you'll be really taxing your allocator with lots of small and quick allocations. Plus, there are several other good reasons to consider Java for this sort of app: it has better out-of-the-box support for network protocols, which you'll need for fetching website data, and it is much more robust against the possibility of buffer overflows in the face of malicious content. A: Garbage collection (GC) is fundamentally a space-time tradeoff. The more memory you have, the less time your program will need to spend performing garbage collection. As long as you have a lot of memory available relative to the maximum live size (total memory in use), the main performance hit of GC -- whole-heap collections -- should be a rare event. Java's other advantages (notably robustness, security, portability, and an excellent networking library) make this a no-brainer. For some hard data to share with your colleagues showing that GC performs as well as malloc/free with plenty of available RAM, see: "Quantifying the Performance of Garbage Collection vs. Explicit Memory Management", Matthew Hertz and Emery D. Berger, OOPSLA 2005. This paper provides empirical answers to an age-old question: is garbage collection faster/slower/the same speed as malloc/free? We introduce oracular memory management, an approach that lets us measure unaltered Java programs as if they used malloc and free. The result: a good GC can match the performance of a good allocator, but it takes 5X more space. If physical memory is tight, however, conventional garbage collectors suffer an order-of-magnitude performance penalty. Paper: PDF Presentation slides: PPT, PDF A: No, your concerns are most likely unfounded. GC can be a concern, when dealing with large heaps & fractured memory (requires a stop the world collection) or medium lived objects that are promoted to old generation but then quickly de-referenced (requires excessive GC, but can be fixed by resizing ratio of new:old space). A web crawler is very unlikely to fit either of the above two profiles - you probably don't need a massive old generation and should have relatively short lived objects (page representation in memory while you parse out data) and this will be efficiently dealt with in the young generation collector. We have an in-house crawler (Java) that can happily handle 2 million pages per day, including some additional post-processing per page, on commodity hardware (2G RAM), the main constraint is bandwidth. GC is a non-issue. As others have mentioned, GC is rarely an issue for throughput sensitive applications (such as a crawler) but it can (if one is not careful) be an issue for latency sensitive apps (such as a trading platform). A: The typical concern C++ programmers have for GC is one of latency. That is, as you run a program, periodic GCs interrupt the mutator and cause spikes in latency. Back when I used to run Java web applications for a living, I had a couple customers who would see latency spikes in the logs and complain about it — and my job was to tune the GC to minimize the impact of those spikes. There are some relatively complicated advances in GC over the years to make monstrous Java applications run with consistently low latency, and I'm impressed with the work of the engineers at Sun (now Oracle) who made that possible. However, GC has always been very good at handling tasks with high throughput, where latency is not a concern. This includes cron jobs. Your engineers have unfounded concerns. Note: A simple experimental GC reduced the cost of memory allocation / freeing to less than two instructions on average, which improved throughput, but this design is fairly esoteric and requires a lot of memory, which you don't have on EC2. The simplest GCs around offer a tradeoff between large heap (high latency, high throughput) and small heap (lower latency, lower throughput). It takes some profiling to get it right for a particular application and workload, but these simple GCs are very forgiving in a large heap / high throughput / high latency configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: jquery select div inside div I am trying to get this to alert only the div clicked on, vs alerting the div clicked and then the container div's. when I click on the third div I would like it to only alert "third". thanks for the help. <div id="first"> <div id="second"> <div id="third"> third div </div> second div </div> first div </div> $("div").click(function() { alert(this.id); }); A: Demo $("div").click(function(e) { alert(this.id); e.stopPropagation(); }) that will do it. A: event.stopPropagation(); $("div").click(function(event) { alert(this.id); event.stopPropagation(); }) A: $("div").click(function(event) { alert(this.id); event.stopPropagation(); }) A: $("div").click(function() { alert(this.id); return false; })
{ "language": "en", "url": "https://stackoverflow.com/questions/7535734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python sys.exit() help? I am working in Python and am trying to have a line of code execute and after it executes I am calling sys.exit() to have the script itself "exit." However, it seems that sys.exit() is executing before the line of code above it executes. Below is the code I am trying to implement: if something == True: self.redirect('http://www.google.com/') sys.exit() The script is exiting before it is redirecting. I need the redirect to complete and then have sys.exit() execute. I CANNOT use the sleep command due to nature of the other code being implemented. Can anyone give me some help as how to fix/workaround this issue? A: There is probably some buffering or asynchrony in self.redirect(). People often run into a similar problem when they do a print, followed by sys.exit(): the print output gets buffered, and then the process exits before the in-process output buffer is flushed). You can work around this by flushing buffers and/or waiting for the asynchronous task to complete. Its not clear from the question what magic redirect is doing, though. A: Try using the atexit module to register a cleanup function to be run just before sys.exit() is called. To register the redirect function as the cleanup function: import atexit atexit.register(redirect, 'http://www.google.com') Note: the arguments that are passed to the redirect function are included after the function object. We don't need parentheses here because we're passing it the function object, not actually calling the function. Also, this won't help you if your redirect method is not working properly. I would ensure that your redirect method is working by explicitly calling it from a Python interpreter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using --no-rdoc and --no-ri with bundler When using gem install gem_name I can pass --no-rdoc and --no-ri switches to skip generating RDoc/RI documentation for the gem on install. Is there a similar way to do this with bundle install? A: Bundler doesn't include rdoc and ri. There is nothing you need to do. A: See https://stackoverflow.com/a/7662245/109618 for a better ~/.gemrc: install: --no-rdoc --no-ri update: --no-rdoc --no-ri A: Make a file ~/.gemrc and put this in it: gem: --no-rdoc --no-ri That should make it apply whenever you run the gem command. (Even from bundle install) A: The up-to-date setting for ~/.gemrc is gem: --no-document But as pointed out, this is already bundler's default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "123" }
Q: Organizing static data in C++ I'm working on some embedded software where there is some static information about "products". Since the information for a certain product never changes during execution I would like to initialize these data structures at compile time to save some space on the stack/heap. I made a Product class for the data, intending to make a huge array of all the products in the system and then do lookups in this structure, but I haven't figured out quite how to get it working. The arrays are giving me loads of trouble. Some psuedo code: class Product { int m_price; int m_availability[]; // invalid, need to set a size ... etc // Constructor grabbing values for all members Product(int p, int a[], ...); } static const Product products[] = { Product(99, {52,30,63, 49}, ...), // invalid syntax ... } Is there a way to making something like this work? The only thing I can think of would be to organize by attribute and skip the whole Product object. I feel that would make the whole thing harder to understand and maintain though. Does anyone have any suggestions on how I might best organize this kind of data? Thank you. A: An old school C style static array of structs sounds like a perfect match to your requirements. Initializes at compile time, zero runtime overhead, no use of stack or heap. It's not a co-incidence that C is still a major player in the embedded world. So (one recipe - plenty of scope to change the details of this); // in .h file class Product { public: // putting this first means the class is really a struct int m_price; int m_availability[4]; //.... (more) }; extern const Product product_array[]; extern const int product_array_nbr; // in .cpp file const Product product_array[] = { { 23, {56,1,2,4}, //....(more) }, { 24, {65,1,2,4}, //....(more) }, //....(more) }; const int product_array_nbr = sizeof(product_array)/sizeof(product_array[0]); A: A couple of years ago when I was working in embedded we needed to explicitly control the memory allocation of our structures. Imagine this type of struct : .h file template<class T,uint16 u16Entries> class CMemoryStruct { public: /** *Default c'tor needed for every template */ CMemoryStruct(){}; /** *Default d'tor */ ~CMemoryStruct(){}; /** *Array which hold u16Entries of T objects. It is defined by the two template parameters, T can be of any type */ static T aoMemBlock[u16Entries]; /** *Starting address of the above specified array used for fast freeing of allocated memory */ static const void* pvStartAddress; /** *Ending address of the above specified array used for fast freeing of allocated memory */ static const void* pvEndAddress; /** *Size of one T object in bytes used for determining the array to which the necessary method will be invoked */ static const size_t sizeOfEntry; /** *Bitset of u16Entries which has the same size as the Array of the class and it is used to specify whether *a particular entry of the templated array is occupied or not */ static std::bitset<u16Entries> oVacancy; }; /** *Define an array of Type[u16Entries] */ template<class Type,uint16 u16Entries> Type CMemoryStruct<Type,u16Entries>::aoMemBlock[u16Entries]; /** *Define a const variable of a template class */ template<class Type,uint16 u16Entries> const void* CMemoryStruct<Type,u16Entries>::pvStartAddress=&CMemoryStruct<Type,u16Entries>::aoMemBlock[0]; template<class Type,uint16 u16Entries> const void* CMemoryStruct<Type,u16Entries>::pvEndAddress=&CMemoryStruct<Type,u16Entries>::aoMemBlock[u16Entries-1]; template<class Type,uint16 u16Entries> const size_t CMemoryStruct<Type,u16Entries>::sizeOfEntry=sizeof(Type); /** *Define a bitset inside a template class... */ template<class Type,uint16 u16Entries> std::bitset<u16Entries> CMemoryStruct<Type,u16Entries>::oVacancy; Depending on your compiler and environment you could manipulate the area of where the static allocation take place. In our case we moved this to the ROM which was plenty. Also note that depending on your compiler i.e. Greenhills compilers, you may need to use the export keyword and define your static members to the .cpp file. You can use the start and end pointers to navigate through the data. If your compiler supports full STL you may want to use std::vectors with custom allocators and overloaded new operators which would save your memory to somewhere else than the stack. In our case the new operators were overloaded in such a way that all the memory allocation was done on predefined memory structures. Hope I gave you an idea. A: In C++98/03, you cannot initialize arrays in a constructor initializer. In C++11, this has been fixed with uniform initialization: class Product { int m_availability[4]; public: Product() : m_availability{52,30,63, 49} { } }; If you need the data to be provided in the constructor, use a vector instead: class Product { const std::vector<int> m_availability; public: Product(std::initializer_list<int> il) : m_availability(il) { } }; Usage: extern const Product p1({1,2,3}); A: Memory for the static variables is still reserved when the code is actually executing -- you won't be saving space on the stack. You might want to consider use of vectors instead of arrays -- they're easier to pass and process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I delete values in MySQL according to primary key on another table Example my db structure olddb & newdb newdb ID email Name ----------------------- 1 john@yahoo.com John 2 peter@yahoo.com Peter olddb ID email ------------------- 1 john@yahoo.com 2 peter@yahoo.com 3 rambo@hello.com 4 super@duper.com Now I want compare olddb with newdb and delete from olddb which email doesn't have email in newdb Let me know DELETE FROM olddb, newdb USING olddb INNER JOIN newdb USING(email) WHERE olddb.email <> newdb.email A: DELETE FROM oldb WHERE olddb.email NOT IN (SELECT email FROM newdb); There are probably other ways to do it, but that will work. A: This will give you a list of all emails from oldtbl which are not on newtbl: SELECT * FROM oldtbl WHERE id NOT IN ( SELECT id FROM newtbl ) Note: oldtbl and newtbl because I found your naming scheme confusing. We are talkind about tables, not databases. To delete those rows on oldtbl, just change SELECT * with DELETE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a better Solr and P2P integration option? In thinking about my applications network service needs using the Java language I've more or less boiled it down to a combination of using Solr, P2P and REST. An automated notifier service would be good to include too. Although I like JXTA I'm not sure it is doing so well these days after the Oracle Java buyout, apparently there is now a Chaupel project but it looks inactive for the most part. Solr on the other hand is doing very well. Since my network is for the most part based on Solr and now a P2P API that is struggling (JXTA) I'm wondering if there are other alternatives for implementing a P2P like layer. Essentially, I want users to be able to post and search/retrieve documents from centralized server based Solr index/s PLUS be able to make user peer groups and collaborate anytime which in my mind seems to be activity that is decentralized. Maybe what I have in mind for the P2P functionality can be done through a server too? Are there any Solr and P2P projects in the works? I keep hearing about Apache Camel these days, is it of any use in my scenario? Besides the MsgConnect API which has a licensing fee are there any active and robust P2P APIs that I could trust enough to include with my application? A: If you are looking for p2p middlaweres, check out FreePastry, XMPP and some other JMS compatible, like Java JMS, ActiveMQ, HornetQ. And about the Sorl, you can use it on them, i do not think that already exists a p2p middleware with native integration with sorl.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should these expressions evaluate differently? I was somewhat confused until I found the bug in my code. I had to change a.matched_images.count #True when variable is 0 to a.matched_images.count > 0 #False when variable is 0 Since I quickly wanted to know whether an object had any images, the first code will appear like the photo has images since the expression evaluates to True when the meaning really is false ("no images" / 0 images) Did I understand this correctly and can you please answer or comment if these expressions should evaluate to different values. A: What is the nature of count? If it's a basic Python number, then if count is the same as if count != 0. On the other hand, if count is a custom class then it needs to implement either __nonzero__ or __len__ for Python 2.x, or __bool__ or __len__ for Python 3.x. If those methods are not defined, then every instance of that class is considered True. A: Without knowing what count is, it's hard to answer, but this excerpt may be of use to you:. The following values are considered false: * *None *False *zero of any numeric type, for example, 0, 0L, 0.0, 0j. *any empty sequence, for example, '', (), []. *any empty mapping, for example, {}. *instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1] All other values are considered true — so objects of many types are always true. A: >>> bool(0) False So.. no, if it were an int that wouldn't matter. Please do some tracing, print out what count actually is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: An API to do game AI research in shooters I'm looking to do a machine learning related course project. I'm basically looking for a framework for a top view 2d shooter game, and apply machine learning algorithms to it. There is a framework available to do research in car racing, called TORCS, and I was looking something similar to this, but for shooters. Basically I would like a high level API to make the bot move, shoot, pick weapons etc. Some of the work that could be done: Lets say you need to model how your bot will fight during combat. You use a neural network to map enemy position, bot's position, bot's ammo, etc to how you should move, and what weapon you should choose. Is there any (preferable 2D, Python) framework which will help me to do this? A: * *Robocode in Java or .Net. *Marvin's Arena in C#, VB, C++ *Brood Wars API, for Starcraft. *Pogamut 3 GameBots2004 for Unreal Tournament and so. *Planet Wars / Galcon Clone AI. 2D but no a shooter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python - Converting a Number to a Letter without an if statement I am making a program for my own purposes (a naming program) that completely generates a random name. The problem is I cannot assign a number to a letter, so as a being 1 and z being 26, or a being 0 and z being 25. It gives me a SyntaxError. I need to assign this because the random integer (1,26) triggers a letter (if the random integer is 1, select A) and prints the name. EDIT: I have implemented your advice, and it works, I am grateful for this, but I wish to have my program create readable names, or more procedural. Here is an example of a name after I tweaked my program: ddjau. Now that doesn't look like a name, so I want it my program to work as if it were creating REAL names, like Samuel or other common names. Thanks! EDIT (2): Thanks, Adam, but I need a sort of 'seed' for the user to enter for the start of the name is. (Seed = A, Name = Adam. Seed = G, Name = George.) Should I do this by searching the file line by line, at the very beginning? If so, how do I do this? A: chr (see here) and ord (see here) are the two functions you're looking for (though you already seem to know about the latter). Follow those links for a more detailed explanation. The first gives you a one-character string based on the integer, the second does the reverse operaion (technically, it handles Unicode as well, which chr doesn't, though you have unichr for that if you need it). You can base your code on the following: ch = "E" print ord (ch) - ord ("A") + 1 # should give 5 for the fifth letter val = 7 print chr (val + ord ("A") - 1) # should give G, the seventh letter A: Short Answer Look into Python dictionaries to allow the 1 = 'a' type assignments. Below I have working example that would generate a random name based on gender and a 'litter'. Disclaimer I do not fully understand (via the code) what you're trying to accomplish with char/ord and a random letter. Also note having absolutely no idea of your design goals or requirements, I have made the example more complex than it may need to be for instructional purposes. Additional Resources * Python Docs for dictionary * Using Python dictionary relationship to search both ways In response to the last edit If you are looking to build random 'real' names, I think your best bet will be to use a large list of names and just pick a random one. If I were you I'd look into something linking to the census results: males and females. Note that male_names.txt and female_names.txt are a copy of the list found at the census website. As a disclaimer, I'm sure there is a more efficient way to load / read the file. Just use this example as a proof on concept. Update Here's a quick and dirty way to seed the random values. Again I am not sure that this is the most pythonic way or most efficient way, but it works. Example import random import time def get_random_name(gender, seed): if(gender == 'male'): file = 'male_names.txt' elif(gender == 'female'): file = 'female_names.txt' fid = open(file,'r') names = [] total_names = 0 for line in fid: if(line.lower().startswith(seed)): names.append(line) total_names = total_names + 1 random_index = random.randint(0,total_names) return names[random_index] if (__name__ == "__main__"): print 'Welcome to Name Database 2.2\n' print '1. Boy' print '2. Girl' bog = raw_input('\nGender: ') print 'What should the name start with?' print 'A, Ab, Abc, B, Ba, Br, etc...' print '' l = raw_input('Leter(s): ').lower() new_name = '' if bog == '1': # Boy print get_random_name('male',l) elif bog == '2': print get_random_name('female',l) Output Welcome to Name Database 2.2 1. Boy 2. Girl Gender: 2 What should the name start with? A, Ab, Abc, B, Ba, Br, etc... Leter(s): br BRITTA A: I'm not entirely sure what you're trying to do, but you can convert a number into a letter with the chr() function. chr() takes an ASCII code, so if you want to use the range [0, 25] instead you can adapt it like so: chr(25 + ord('a')) # 'z'
{ "language": "en", "url": "https://stackoverflow.com/questions/7535769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL statement's placeholders that is not replaced leads to "Cannot update '@columnName'; field not updateable" I'm writing some code updating database with a SQL statement that has some placeholders . But it doesn't seem to update these placeholders. I got the following error: Cannot update '@columnName'; field not updateable Here is the method: public void updateDoctorTableField(string columnName, string newValue, string vendorNumber) { sqlStatement = "update Doctor set @columnName = @newValue where `VENDOR #` = @vendorNumber;"; try { _command = new OleDbCommand(sqlStatement, _connection); _command.Parameters.Add("@columnName", OleDbType.WChar).Value = columnName; _command.Parameters.Add("@newValue", OleDbType.WChar).Value = newValue; _command.Parameters.Add("@vendorNumber", OleDbType.WChar).Value = vendorNumber; _command.ExecuteNonQuery(); } catch (Exception ex) { processExeption(ex); } finally { _connection.Close(); } } A: Not all parts of the query are parameterisable. You can't parametrise the name of the column. This needs to be specified explicitly in your query text. If this is sent via user input you need to take care against SQL Injection. In fact in any event it would be best to check it against a whitelist of known valid column names. A: The reason the language does not allow for parameters for things like table names, column names and such is exactly the same reason why your C# program does not allow for substitution of variables in the code. Basically your question can be rephrased like this in a C# program: class MyClass { int x; float y; string z; void DoSomething(string variableName) { this.@variable = ... } } MyCLass my = new MyClass(); my.DoSomething("x"); // expect this to manuipulate my.x my.DoSomething("y"); // expect this to manuipulate my.y my.DoSomething("z"); // expect this to manuipulate my.z This obviously won't compile, because the compiler cannot generate the code. Same for T-SQL: the compiler cannot generate the code to locate the column "@columnName" in your case. And just as in C# you would use reflection to do this kind of tricks, in T-SQL you would use dynamic SQL to achieve the same. You can (and should) use the QUOTENAME function when building your dynamic SQL to guard against SQL injection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Date parsing problem with Jackson 1.8.5 Recently (in the last couple hours or so) I started getting this exception stack: org.codehaus.jackson.JsonParseException: Numeric value (1316835995324) out of range of int at [Source: java.io.StringReader@5b082d45; line: 1, column: 642] at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1291) at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:385) at org.codehaus.jackson.impl.JsonNumericParserBase.convertNumberToInt(JsonNumericParserBase.java:462) at org.codehaus.jackson.impl.JsonNumericParserBase.getIntValue(JsonNumericParserBase.java:257) at org.codehaus.jackson.map.deser.StdDeserializer._parseInteger(StdDeserializer.java:237) at org.codehaus.jackson.map.deser.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:838) at org.codehaus.jackson.map.deser.StdDeserializer$IntegerDeserializer.deserialize(StdDeserializer.java:825) at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252) at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:356) at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494) at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:120) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:97) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252) at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:499) at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494) at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350) at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252) at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:499) at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494) at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:120) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:97) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252) at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:499) at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494) at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350) at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252) at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:499) at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494) at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:120) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:97) at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:252) at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:499) at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:494) at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350) at org.codehaus.jackson.map.ObjectReader._bindAndClose(ObjectReader.java:477) at org.codehaus.jackson.map.ObjectReader.readValue(ObjectReader.java:253) This is happening while deserializing a java.util.Date. The interesing part is that there are other similar Dates in the input stream before this one and they do not cause any problems. In addition, I did not change the fields of the object that is being serialized and deserialized. Does anyone have any idea why Jackson is trying to deserialize this particular Date value into an int (and not into a long)? Thanks in advance for any insight. EDIT: I debugged this a little and it looks like this is the first Date that Jackson is trying to process, even though it still comes later in the stream. I also saw that Jackson is trying to force this number into an int, even though earlier in the processing it is detected properly as a long. EDIT 2: I debugged this more and figured out the following: Serialization/deserialization works fine as long as I do not have a setter that takes an input parameter, like this: public void setSomeValue(int param) { // stuff this.date = <result_value> } The moment I introduce this setter, Jackson executes a different code path and ends up in the block where it tries to put a long (the java.util.Date) into an int. EDIT 3: Changing the setter name to something unrelated to the field name works around the problem. I would still prefer to know if the original way is working as intended (if so, what is the idea behind it) or a bug. A: Right -- type that is expected is determined by mutator with highest priority. So since your setter claims type is 'int', that's what Jackson treats it as. It actually must, since it will call that setter; so even if you happen to have a field with different type (or getter that returns Date), it won't help a lot since you can not pass Date as an 'int' to set method. INT_MIN Minimum value for a variable of type int. –2147483648 INT_MAX Maximum value for a variable of type int. 2147483647 A: yep, check the setter, change int to long: public void setSomeValue(long param) { this.date = param; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there something incorrect with this code? I don't believe I should have to create a new instance of object to modify collection I am experiencing some weird behavior that disappears/reappears based on whether this dictionary is a new instance of the object, or the old instance of the object. Let me provide all the code first. /// <summary> /// Removes a control from monitoring/Session/Database based on ID. /// </summary> public static void Remove<T>(ICormantControl<T> control) { _logger.InfoFormat("Removing {0}", control.ID); SerializableDictionary<string, T> states = new SerializableDictionary<string,T>(GetStates<SerializableDictionary<string, T>>()); ((IDictionary)states).Remove(control.ID); SetStates(states); } /// <summary> /// Retrieves information on an object. If the object is cached to Session then the /// cached object is retrieved. Else, it is retrieved from the database. /// </summary> /// <typeparam name="T"> The type of object expected to get back.</typeparam> /// <returns> Collection of data for the specific object type.</returns> public static T GetStates<T>() where T : new() { T states = new T(); string stateName = GetStateNameFromType(typeof(T)); if (!Equals(SessionRepository.Instance.GetSession(stateName), null)) { states = (T)SessionRepository.Instance.GetSession(stateName); } else { XmlSerializer serializer = new XmlSerializer(states.GetType()); string data = DatabaseRepository.Instance.GetWebLayoutData(stateName); if (!string.IsNullOrEmpty(data)) { byte[] dataAsArray = Convert.FromBase64String(data); MemoryStream stream = new MemoryStream(dataAsArray); states = (T)serializer.Deserialize(stream); } SessionRepository.Instance.SetSession(stateName, states); } return states; } public static void SetStates<T>(T states) where T : new() { string stateName = GetStateNameFromType(typeof(T)); SessionRepository.Instance.SetSession(stateName, states); if (shouldWriteToDatabase) DatabaseRepository.Instance.SaveToDatabase(stateName, states); } /// <summary> /// Recreates the page state recursively by creating a control and looking for its known children. /// </summary> /// <param name="pane"> Pane having children added to it.</param> private void RegeneratePaneChildren(CormantRadPane pane) { _logger.InfoFormat("Initializing paneToResize children for paneToResize {0}", pane.ID); foreach (var splitterState in StateManager.GetStates<SerializableDictionary<string, RadSplitterSetting>>()) { RadSplitterSetting splitterSetting = splitterState.Value; if (!splitterSetting.ParentID.Contains(pane.ID)) continue; CormantRadSplitter splitter = new CormantRadSplitter(splitterSetting); pane.UpdatePanel.ContentTemplateContainer.Controls.AddAt(0, splitter); //Visibility will fight with splitter if you don't re-add like this. RegenerateSplitterChildren(splitter); } } /// <summary> /// Recreates the page state recursively by creating a control and looking for its known children. /// </summary> /// <param name="splitter"> Splitter having children added to it. </param> public void RegenerateSplitterChildren(RadSplitter splitter) { _logger.InfoFormat("Initializing splitter children for splitter {0}", splitter.ID); foreach (var paneState in StateManager.GetStates<SerializableDictionary<string, RadPaneSetting>>() .Where(paneState => paneState.Value.ParentID.Contains(splitter.ID))) { RadPaneSetting paneSetting = paneState.Value; CormantRadPane pane = new CormantRadPane(paneSetting); StyledUpdatePanel updatePanel = pane.CreateUpdatePanel(paneSetting.UpdatePanelID); pane.Controls.Add(updatePanel); splitter.Controls.Add(pane); RegeneratePaneChildren(pane); InsertSplitBar(splitter); } } The key line to look at in all of this is: SerializableDictionary<string, T> states = new SerializableDictionary<string,T>(GetStates<SerializableDictionary<string, T>>()); If this line of code is modified such that it does not create a new instance of states (instead using the object saved in Session) my code gets 'desynched' and I experience odd behavior with my Regeneration methods. An object that is supposed to have 'ObjectA' as a parent instead has 'ObjectB' as a parent. There's a lot of collection-modification going on... I'm removing a control from states and re-saving it...but I can't see where I do anything explicitly incorrect in this code. Yet, I still feel that I should be able to express the above line of code without creating a new instance of the object. If anyone sees an obvious blunder I'd love to hear it. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AVAudioPlayer setVoume:x, when x > 1.0 I have been working with AVAudioPlayer on the iPad (original version) running IOS 4.3.3 The documentation for the volume property states: "The playback gain for the audio player, ranging from 0.0 through 1.0." Curiously it seems to allow you to use a value > 1.0, with the expected effect (the volume is increased accordingly). This means if you are playing a quieter track, you can (for example) mix it at volume 2.0 with the line [myPlayer setVolume:2.0]; Reading back the volume property returns 2.0 as the current value. so my question is: is this a mistake in the documentation, or a bug we can expect to be rectified in later releases? It does turn out to be a useful feature, however does have potential to increase the playback volume to "over zero", should the audio being played happen to contain samples which when multiplied by the volume are over the supported bit resolution. In my app i am planning on using it to "level match" playback levels after scanning the audio. Otherwise I'd need to turn down "loud" tracks to a predetermined nominal zero value, and not turn down the "quiet" tracks as much. It makes more sense to be able to increase the volume of the quieter tracks to actual "zero", thus giving more overall dynamic range.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Scala searches for an obscure Main class I have what should be a simple scala script that looks as follows: object SaveTaggedSenseTask { def main(args: Array[String]) { val reader:SenseEvalAllWordsDocumentReader = new SenseEvalAllWordsDocumentReader() reader.parse(args(0)) println(reader.sentences) reader.sentences() } } The SenseEvalAllWordsDocumentReader is a java defined class that is just a wrapper for a SAX parser. Calling sentences should simply return a java List of of another java defined class called Sentence. If i run this code using scala -cp jar-with-everything.jar SaveTaggedSenseTask.scala path/to/file.xml I get the following horrible mess of an output: java.lang.ClassNotFoundException: Main (args = /home/stevens35/senseEval/senseEval3-allwords/english-all-words.xml, classpath = /tmp/scalascript7300484879512233483.tmp:/usr/java/jdk1.6.0_26/jre/lib/resources.jar:/usr/java/jdk1.6.0_26/jre/lib/rt.jar:/usr/java/jdk1.6.0_26/jre/lib/jsse.jar:/usr/java/jdk1.6.0_26/jre/lib/jce.jar:/usr/java/jdk1.6.0_26/jre/lib/charsets.jar:/home/stevens35/devel/src/scala-2.9.1.final/lib/jline.jar:/home/stevens35/devel/src/scala-2.9.1.final/lib/scala-compiler.jar:/home/stevens35/devel/src/scala-2.9.1.final/lib/scala-dbc.jar:/home/stevens35/devel/src/scala-2.9.1.final/lib/scala-library.jar:/home/stevens35/devel/src/scala-2.9.1.final/lib/scalap.jar:/home/stevens35/devel/src/scala-2.9.1.final/lib/scala-swing.jar:/usr/java/jdk1.6.0_26/jre/lib/ext/sunjce_provider.jar:/usr/java/jdk1.6.0_26/jre/lib/ext/sunpkcs11.jar:/usr/java/jdk1.6.0_26/jre/lib/ext/localedata.jar:/usr/java/jdk1.6.0_26/jre/lib/ext/dnsns.jar:/home/stevens35/devel/C-Cat/wordnet/.:/home/stevens35/devel/C-Cat/wordnet/target/extendOntology-wordnet-1.0-jar-with-dependencies.jar:/home/stevens35/devel/C-Cat/wordnet/../data/target/extendOntology-data-1.0.jar) at scala.tools.nsc.util.ScalaClassLoader$URLClassLoader.run(ScalaClassLoader.scala:103) at scala.tools.nsc.ObjectRunner$.run(ObjectRunner.scala:33) at scala.tools.nsc.ObjectRunner$.runAndCatch(ObjectRunner.scala:40) at scala.tools.nsc.ScriptRunner.scala$tools$nsc$ScriptRunner$$runCompiled(ScriptRunner.scala:171) at scala.tools.nsc.ScriptRunner$$anonfun$runScript$1.apply(ScriptRunner.scala:188) at scala.tools.nsc.ScriptRunner$$anonfun$runScript$1.apply(ScriptRunner.scala:188) at scala.tools.nsc.ScriptRunner$$anonfun$withCompiledScript$1.apply$mcZ$sp(ScriptRunner.scala:157) at scala.tools.nsc.ScriptRunner$$anonfun$withCompiledScript$1.apply(ScriptRunner.scala:131) at scala.tools.nsc.ScriptRunner$$anonfun$withCompiledScript$1.apply(ScriptRunner.scala:131) at scala.tools.nsc.util.package$.waitingForThreads(package.scala:26) at scala.tools.nsc.ScriptRunner.withCompiledScript(ScriptRunner.scala:130) at scala.tools.nsc.ScriptRunner.runScript(ScriptRunner.scala:188) at scala.tools.nsc.ScriptRunner.runScriptAndCatch(ScriptRunner.scala:201) at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:58) at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:80) at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:89) at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala) I'm assuming that this means scala is looking for some class named Main and can't find it, but I can't figure out why it would even think of looking for this. Furthermore, if i delete the reader.sentences() line, or do something like call size() on it, the problem goes away. I can only guess that scala is somehow inferring that a class named Main should exist due to this call, but I don't see any obvious workaround. Thoughts? Any help is greatly appreciated. A: You are conflating Scala script and scala program. When using object and def main, you should compile the program with scalac, and then call it with scala passing the name of the object that contains the main method. When calling as a script, you should remove object and def main, and just put your program. The arguments will still be in args. Now, one of the features of Scala 2.9.1 is that one could mix script and program invocation, but it is obviously not working here for some reason. I suggest you pick one way of doing things, and stick to that. A: Your script defines the object SaveTaggedSenseTask, but doesn't execute anything. Just add SaveTaggedSenseTask.main(args) to the end of the script file. Or you can remove the object and def statements, like @daniel-c-sobral suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android efficient storage of two images which are similar Application size on a phone needs to be as small as possible. If I have an image of a sword and then a very similar image of that same sword except that I've changed the color or added flames or changed the picture of the jewel or whatever, how do store things as efficiently as possible? One possibility is to store the differences graphically. I'd store just the image differences and then combine the two images at runtime. I've already asked a question on the graphic design stackexchange site about how to do that. Another possibility would be that there is that apk already does this or that there is already a file format or method people use to store similar images in android. Any suggestions? Are there tools that I could use to take two pngs and generate a difference file or a file format for storing similar images or something? A: I'd solve this problem at a higher level. For example, do the color change at run-time (maybe store the image with a very specific color like some ugly shade of green that you know is the color to be fixed at run-time with white or red or blue or whatever actual color you want). Then you could generate several image buffers at load-time. For compositing the two images, just store the 'jewel' image separately, and draw it over the basic sword. Again, you could create a new image at load-time, or just do the overdraw at run-time. This will help reduce your application's footprint on flash, but will not reduce the memory footprint when the app is active. A: I believe your idea of storing the delta between 2 images to be quite good. You would then compress the resulting delta file with a simple entropy coder, such as Huffman, and you are pretty likely to achieve a strong compression ratio if similarities with base image are important. If the similarity are really very strong, you could even try a Range Coder, to achieve less-than-one-bit-per-pixel performance. The difference however might be noticeable only for larger images (i.e higher definition than a 12x12 sprite). These ideas however will require you or someone to write for you such function's code. This should be quite straightforward. A: An very easy approach to do this is to use an ImagePack ( one image containing many ) - so you can easy leverage the PNG or JPG compression algorithms for your purpose. You then split the images before drawing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Beanshell will not allow me to add jars to the "default" JRE classloader? I have a question about Beanshell that I can't find an answer to anywhere. I am only able to run Beanshell scripts in 1 of 2 ways: * *Where Classpath is defined before invoking Beanshell and Beanshell uses the JRE default classloader. *Where no classpath is defined at all before starting Beanshell and then I use addClassPath() and importCommands() to dynamically build the classpath within Beanshell's classloader. This method does not seem to inherit a jars that were part of the default JRE classloader. After much experimentation, I have learned that I am unable to start a script with a pre-defined Classpath and then be able to add to the classpath by using addClassPath(). I don't know if this is as-designed or if I am doing something wrong? It is very easy to see for yourself what my problem is. For example, here is the script: ::Test.bat (where bsh.jar exists in JRE/lib/ext directory) @echo off set JAVA_HOME=C:\JDK1.6.0_27 :: first invoke: this first command works %JAVA_HOME%\jre\bin\java.exe bsh.Interpreter Test.bsh :: second invoke: this command fails %JAVA_HOME%\jre\bin\java.exe -cp ant.jar bsh.Interpreter Test.bsh The second invoke causes this error: Evaluation Error: Sourced file: Test.bsh : Command not found: helloWorld() : at Line: 5 : in file: Test.bsh : helloWorld ( ) Test.bat launches this Beanshell script: // Test.bsh System.out.println("Trying to load commands at: " + "bin" ); addClassPath("bin"); importCommands("bin"); helloWorld(); And, this is my helloWorld.bsh script: // File: helloWorld.bsh helloWorld() { System.out.println("Hello World!"); } A: Your Test.bsh has a slight error: importCommands looks for a directory called "bin" in the class path and loads all .bsh files from there, so what you should add to addClassPath is the current directory: // Test.bsh System.out.println("Trying to load commands at: " + "bin" ); addClassPath("."); // current directory importCommands("bin"); helloWorld(); The code you had works in the first case because the current directory is in the default system class path. The problem is that the -cp switch overrides the default class path, so importCommands no longer has any way to find the bin directory. Alternatively you can add . to the classpath on the JVM level: %JAVA_HOME%\jre\bin\java.exe -cp .;ant.jar bsh.Interpreter Test.bsh
{ "language": "en", "url": "https://stackoverflow.com/questions/7535802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you add an external package to a GoClipse project for Google App Engine? I've compiled Goauth so that I can use OAuth in my Go Google App Engine project. Where do I put the goauth.a file so that I can both use it in the project, and have it available when deploying to the GAE servers? I can get it working locally if I put it in a subfolder of $GOROOT/pkg, but then it can't be found when compiling at deployment time. GoClipse sets up a project with lots of folders, I'm not really sure what their purpose is, where should I put goauth.a and how do I import it? A: To fix this I ended up including the source for the package in the directory tree for my app, as mentioned in this thread on the google-appengine-go group http://groups.google.com/group/google-appengine-go/browse_thread/thread/1fe745debc678afb Here is the important part of the thread: You may include as many packages as necessary. Packages are imported by path relative to the base directory (the one that has your app.yaml file), so if you have the following: helloworld/app.yaml helloworld/hello/hello.go // package hello helloworld/world/world.go // package world you can import "world" in hello and import "hello" in world. If you are including a third-party library, it might look something like this: helloworld/app.yaml helloworld/hello/hello.go // package hello helloworld/world/world.go // package world helloworld/goprotobuf.googlecode.com/proto/*.go // package proto Then you can, as normal, import "goprotobuf.googlecode.com/proto".
{ "language": "en", "url": "https://stackoverflow.com/questions/7535803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Latex, display a long image in multiple page? (Please don't move my post to Tex, I can't post image there.) I have a long UML diagram, I use the following code. The figure is about two and a half page long, but only the first page is showing, and the lower part of the figure is missing. How do I display the whole diagram in multiple page? Exactly what code should I add? \usepackage{graphicx} ...... \includegraphics[height= 81.3cm, width=18cm]{myImage.png} \captionof{figure}{Sequence Diagram} Screenshot: A: You can use the viewport option of \includegraphics to display a specific portion of the image. By using this command three times you can display your image in three portions. The viewport option takes 4 arguments: * *The first two values are the (x,y) coordinates (in pixels) of the lower left corner of the portion of the image file you want to include. *The second two values are the coordinates of the upper right corner. For example, the command \includegraphics*[viewport=0 0 100 100]{myImage.png} would display the bottom-left corner of the image. Note that you need the * in order to actually crop the image; otherwise it will only be shifted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: When to force LINQ query evaluation? What's the accepted practice on forcing evaluation of LINQ queries with methods like ToArray() and are there general heuristics for composing optimal chains of queries? I often try to do everything in a single pass because I've noticed in those instances that AsParallel() does a really good job in speeding up the computation. In cases where the queries perform computations with no side-effects but several passes are required to get the right data out is forcing the computation with ToArray() the right way to go or is it better to leave the query in lazy form? A: If you are not averse to using an 'experimental' library, you could use the EnumerableEx.Memoize extension method from the Interactive Extensions library. This method provides a best-of-both-worlds option where the underlying sequence is computed on-demand, but is not re-computed on subequent passes. Another small benefit, in my opinion, is that the return type is not a mutable collection, as it would be with ToArray or ToList. A: Keep the queries in lazy form until you start to evaluate the query multiple times, or even earlier if you need them in another form or you are in danger of variables captured in closures changing their values. You may want to evaluate when the query contains complex projections which you want to avoid performing multiple times (e.g. constructing complex objects for sequences with lots of elements). In this case evaluating once and iterating many times is much saner. You may need the results in another form if you want to return them or pass them to another API that expects a specific type of collection. You may want or need to prevent accessing modified closures if the query captures variables which are not local in scope. Until the query is actually evaluated, you are in danger of other code changing their values "behind your back"; when the evaluation happens, it will use these values instead of those present when the query was constructed. (However, this can be worked around by making a copy of those values in another variable that does have local scope). A: You would normally only use ToArray() when you need to use an array, like with an API that expects an array. As long as you don't need to access the results of a query, and you're not confined to some kind of connection context (like the case may be in LINQ to SQL or LINQ to Entities), then you might as well just keep the query in lazy form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is code execution slower when called remotely? (.net remoting) I have a sub in my VB.NET (framework 2) program. This sub does not return any value, it just perform various checks on a local DB. The program calls the sub just after starts, and it takes about 6 seconds to complete. The program also acts as a net remoting server. Clients can connect to it and call the sub. When a remote client calls the sub it takes about 28 seconds to complete. Why is that? In both cases the sub is executed locally in the server, but when called remotely it takes a lot more time, even if the task is exactly the same. Is somehow the code executed in a much slower thread when called using .net remoting? Do you know why this happens? Do you know how to solve it? Thank you for any help! EDIT: I am very sorry for the lack of information. I thought it would be enough. OK here it goes… This is a VB sub, it does not return any value. Network is fast, the problem is not to reach the remote computer, the problem is that the code seems to take a lot more to complete if called remotely. If you really want to know, the main part of the sub is a loop that copies values from a DAO (yes DAO) recordset to a collection: Sub MySub 'This sub can be called both remotemy and locally. Dim IDsAtTable As New Dictionary(Of Integer, Integer) ‘Open database and fast stuff. ‘{…} ‘POINT A RS = DB.OpenRecordset("SELECT ID FROM " & Table & " WHERE IDSucursalFuente=" & IDThisSucursal & " ORDER BY ID") Fld = RS.Fields("ID") Do While Not RS.EOF ID = Fld.Value If Not IDsAtTable.ContainsKey(ID) Then IDsAtTable.Add(ID, ID) RS.MoveNext() Loop RS.Close() RS = Nothing ‘POINT B 'Check elements stored at IDsAtTable, this is fast. ‘Close database and fast stuff. ‘{…} End Sub In both cases (when called remotely and when called locally on the server) the code works with the same DB (hosted on the server), in the same state (I mean closed at the beginning) with the exact same records. If you measure time from POINT A to POINT B it takes a lot more time if the sub was called remotely, but as you can see, there is no network involved. To me it should take the same amount of time but that’s not the case. I only call the sub 2 times. One locally by the server process itself, and one by the remote client. Server's processor load is the same. There is just one client calling the sub at a given time. I don’t know if .NET framework does other stuff behind the scenes when executes code that was called remotely, or if the thread created for a remote call is much slower.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# LockBits perfomance (int[,] to byte[]) Graphics g; using (var bmp = new Bitmap(_frame, _height, PixelFormat.Format24bppRgb)) { var data = bmp.LockBits(new Rectangle(0, 0, _frame, _height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); var bmpWidth = data.Stride; var bytes = bmpWidth * _height; var rgb = new byte[bytes]; var ptr = data.Scan0; Marshal.Copy(ptr, rgb, 0, bytes); for (var i = 0; i < _frame; i++) { var i3 = (i << 1) + i; for (var j = 0; j < _height; j++) { var ij = j * bmpWidth + i3; var val = (byte)(_values[i, j]); rgb[ij] = val; rgb[ij + 1] = val; rgb[ij + 2] = val; } } Marshal.Copy(rgb, 0, ptr, bytes); bmp.UnlockBits(data); g = _box.CreateGraphics(); g.InterpolationMode = InterpolationMode.NearestNeighbor; g.DrawImage(bmp, 0, 0, _box.Width, _box.Height); } g.Dispose(); I use this code to convert an array of RGB values ​​(grayscale) in the PictureBox, but it's slow. Please tell me my mistakes. At the moment, an array of 441 000 items handled for 35 ms. I need to handle an array of 4 million for the same time. A: You can skip the first Array.Copy where you copy the data from the image to the array, as you will be overwriting all the data in the array anyway. That will shave off something like 25% of time, but if you want it faster you will have to use an unsafe code block so that you can use pointers. That way you can get around the range checking when you access arrays, and you can write the data directly into the image data instead of copying it. A: I totally agree with Guffa's answer. Using an unsafe code block will speed up things. To further improve performance, you could execute your for loop in parallel by using the Parallel class in the .Net framework. For large bitmaps this improves performance. Here is a small code sample: using (Bitmap bmp = (Bitmap)Image.FromFile(@"mybitmap.bmp")) { int width = bmp.Width; int height = bmp.Height; BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); byte* s0 = (byte*)bd.Scan0.ToPointer(); int stride = bd.Stride; Parallel.For(0, height, (y1) => { int posY = y1*stride; byte* cpp = s0 + posY; for (int x = 0; x < width; x++) { // Set your pixel values here. cpp[0] = 255; cpp[1] = 255; cpp[2] = 255; cpp += 3; } }); bmp.UnlockBits(bd); } To keep the example simple I've set the pixel values to a constant value. Note, to compile the example above you have to allow unsafe code. Hope, this helps. A: In addition to Guffa's excellent advice, I would suggest that you profile your code to see where it's taking the time. Be sure that when you're timing this, you are running in release mode without the debugger attached. I wouldn't be surprised if the call to DrawImage is taking up most of the time. You're scaling the image there, which can be pretty expensive. How large is the box that you're drawing the image to? Finally, although this won't affect performance, you should change your code to read: using (Graphics g = _box.CreateGraphics()) { g.InterpolationMode = InterpolationMode.NearestNeighbor; g.DrawImage(bmp, 0, 0, _box.Width, _box.Height); } And get rid of the first and last lines in your example. A: Try this using unsafe code: byte* rp0; int* vp0; fixed (byte* rp1 = rgb) { rp0 = rp1; fixed (int* vp1 = _values) { vp0 = vp1; Parallel.For(0, _width, (i) => { var val = (byte)vp0[i]; rp0[i] = val; rp0[i + 1] = val; rp0[i + 2] = val; }); } } Runs very fast for me A: My understanding is that multidimentional (square) arrays are pretty slow in .Net. You might try changing your _values array to be a single dimension array instead. Here is one reference, there are many more if you search: http://odetocode.com/articles/253.aspx Array perf example. using System; using System.Diagnostics; class Program { static void Main(string[] args) { int w = 1000; int h = 1000; int c = 1000; TestL(w, h); TestM(w, h); var swl = Stopwatch.StartNew(); for (int i = 0; i < c; i++) { TestL(w, h); } swl.Stop(); var swm = Stopwatch.StartNew(); for (int i = 0; i < c; i++) { TestM(w, h); } swm.Stop(); Console.WriteLine(swl.Elapsed); Console.WriteLine(swm.Elapsed); Console.ReadLine(); } static void TestL(int w, int h) { byte[] b = new byte[w * h]; int q = 0; for (int x = 0; x < w; x++) for (int y = 0; y < h; y++) b[q++] = 1; } static void TestM(int w, int h) { byte[,] b = new byte[w, h]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) b[y, x] = 1; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: BeautifulStoneSoup - how to unescape and add closing tags I'm editing the original post here to clarify and hopefully I have boiled it down into something more manageable. I have a string of xml that looks something like: <foo id="foo"> <row> &lt;img alt="jules.png" src="http://localhost/jules.png" height="1024" width="764"&gt; </row> <row> &lt;img alt="hairfire.png" src="http://localhost/hairfire.png" height="225" width="225"&gt; </row> </foo> So, I'm doing something like: xml = BeautifulStoneSoup(someXml, selfClosingTags=['img'], convertEntities=BeautifulSoup.HTML_ENTITIES) The result of that is something like: <foo id="foo"> <row> <img alt="jules.png" src="http://localhost/jules.png" height="1024" width="764"> </row> <row> <img alt="hairfire.png" src="http://localhost/hairfire.png" height="225" width="225"> </row> </foo> Notice there are no closing tags on the img tags in each . Not sure this is my issue, but possible. When I try and do: images = xml.findAll('img') it's is yielding an empty list. Any ideas why BeautifulStoneSoup wouldn't find my images in this snippet of xml? A: The reason you are not finding the img tags is because BeautifulSoup is treating them as the text part of the "row" tag. Converting entities just changes the strings, it doesn't change the underlying structure of the document. The following isn't a great solution (it parses the document twice), but it worked when I tested it on your sample xml. The idea here is to convert the text to bad xml, then have beautiful soup clean it up again. soup = BeautifulSoup(BeautifulSoup(text,convertEntities=BeautifulSoup.HTML_ENTITIES).prettify()) print soup.findAll('img')
{ "language": "en", "url": "https://stackoverflow.com/questions/7535815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using if (!bool) vs if (bool == false) in C# Is there any sort of style consensus on the following two coding styles? I'm more curious if this is the sort of thing where one is generally preferred in good code in C#, or if this the sort of thing that gets decided when picking a style for a coding project. Style 1: Using the ! sign to indicate a not in a conditional if (!myBool) { //Do Stuff... } Style 2: Using == false to indicate a check for falsehood in a conditional if (myBool == false) { //Do Stuff... } Thanks! A: I don't know of any language for which the latter is preferred. Use the former. Warning! There's a reason for this! This indeed does what you expect, in most languages: if (x == false) ... But in e.g. C++, because true is just a synonym for 1 (so 2 isn't true or false), this doesn't work: if (x != true) ... although it's fine in C#. In fact, it can also get tricky in .NET -- you can trick a boolean to take an integer value, and mess it up with bitwise arithmetic (e.g. a & b can be false when a is 1 and b is 2, even though both are "true"). In general, just use the former instead of worrying about boolean literals. A: The normal convention is if (!myBool) The one place where I don't go this route is with nullable booleans. In that case I will do if (myBool == true) { } Which is equivalent to if (myBool.HasValue && myBool.Value) A: if(!myBool) { // Do Stuff here... } This is the preferred version, as since you already have a bool variable that contains a true or false, there is no reason to do an additional evaluation in the if statement. Update Based on what aquinas has stated, this format is good to use unless you do have a nullable boolean (ex: bool? myBool). If this is the case, use the former: bool? myBool if (myBool == false) { // Do stuff here... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: I am trying to put tabs within an accordion I downloaded the accordion and tabs from the jQueryUI website. Pretty simple stuff - didn't really do any programming of my own, just nested the tabs within the accordion. Now, the tabs work just fine for the default accordion (the one that appears onload) but they will not show up within the accordion when you click on another pane of the accordion. Could anyone help me with this problem? Thanks! Let me know if you need more info. I am a big noobie. A: Check out this fiddle I suspect the reason it wasn't working for you is because the tabs need to have unique id's. Since there are multiple "tab" sections, I gave them a class of tabs instead of an id, that way you can select all of them when you initialize the tabs. Your JS would simply look like this. $("#accordion").accordion({ autoHeight: false }); $(".tabs").tabs(); Your HTML would look like this <div id="accordion"> <h3><a href="#">Section 1</a></h3> <div> <div class="tabs"> <ul> <li><a href="#tabs-1">Nunc tincidunt</a></li> <li><a href="#tabs-2">Proin dolor</a></li> <li><a href="#tabs-3">Aenean lacinia</a></li> </ul> <div id="tabs-1"> <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p> </div> <div id="tabs-2"> <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p> </div> <div id="tabs-3"> <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p> <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p> </div> </div> </div> <h3><a href="#">Section 2</a></h3> <div> <div class="tabs"> <ul> <li><a href="#tabs-4">Nunc tincidunt</a></li> <li><a href="#tabs-5">Proin dolor</a></li> <li><a href="#tabs-6">Aenean lacinia</a></li> </ul> <div id="tabs-4"> <p>Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.</p> </div> <div id="tabs-5"> <p>Morbi tincidunt, dui sit amet facilisis feugiat, odio metus gravida ante, ut pharetra massa metus id nunc. Duis scelerisque molestie turpis. Sed fringilla, massa eget luctus malesuada, metus eros molestie lectus, ut tempus eros massa ut dolor. Aenean aliquet fringilla sem. Suspendisse sed ligula in ligula suscipit aliquam. Praesent in eros vestibulum mi adipiscing adipiscing. Morbi facilisis. Curabitur ornare consequat nunc. Aenean vel metus. Ut posuere viverra nulla. Aliquam erat volutpat. Pellentesque convallis. Maecenas feugiat, tellus pellentesque pretium posuere, felis lorem euismod felis, eu ornare leo nisi vel felis. Mauris consectetur tortor et purus.</p> </div> <div id="tabs-6"> <p>Mauris eleifend est et turpis. Duis id erat. Suspendisse potenti. Aliquam vulputate, pede vel vehicula accumsan, mi neque rutrum erat, eu congue orci lorem eget lorem. Vestibulum non ante. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce sodales. Quisque eu urna vel enim commodo pellentesque. Praesent eu risus hendrerit ligula tempus pretium. Curabitur lorem enim, pretium nec, feugiat nec, luctus a, lacus.</p> <p>Duis cursus. Maecenas ligula eros, blandit nec, pharetra at, semper at, magna. Nullam ac lacus. Nulla facilisi. Praesent viverra justo vitae neque. Praesent blandit adipiscing velit. Suspendisse potenti. Donec mattis, pede vel pharetra blandit, magna ligula faucibus eros, id euismod lacus dolor eget odio. Nam scelerisque. Donec non libero sed nulla mattis commodo. Ut sagittis. Donec nisi lectus, feugiat porttitor, tempor ac, tempor vitae, pede. Aenean vehicula velit eu tellus interdum rutrum. Maecenas commodo. Pellentesque nec elit. Fusce in lacus. Vivamus a libero vitae lectus hendrerit hendrerit.</p> </div> </div> </div> <h3><a href="#">Section 3</a></h3> <div> <p> Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis. Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui. </p> <ul> <li>List item one</li> <li>List item two</li> <li>List item three</li> </ul> </div> <h3><a href="#">Section 4</a></h3> <div> <p> Cras dictum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia mauris vel est. </p> <p> Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p> </div> </div>
{ "language": "la", "url": "https://stackoverflow.com/questions/7535829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I detect if the computer is playing any sound? I want to programmatically detect if a (local) computer (not mobile device) is playing any sound or music. Preferably via some high level api from Java or Python or a similar language. A: I have never done it, but as a first approach I would open (open as input, not output) a fake recording stream on the master windows playback lineout device (instead the normal use of opening the mic or linein device for recording). I would then monitor the captured frames. If for a certain time there are values over some small threshold, I would infer there is sound.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hadoop java mapper -copyFromLocal heap size error As part of my Java mapper I have a command executes some code on the local node and copies a local output file to the hadoop fs. Unfortunately I'm getting the following output: Error occurred during initialization of VM Could not reserve enough space for object heap I've tried adjusting mapred.map.child.java.opts to -Xmx512M, but unfortunately no luck. When I ssh into the node, I can run the -copyFromLocal command without any issues. The ouput files are also quite small like around 100kb. Any help would be greatly appreciated! A: An infinite loop in the mapper or reducer can cause Out of memory errors. I ran into an OoM once when I had a while-loop with iterator.hasNext() as the condition, for the reducer values, and was not calling iterator.next() inside the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Avoiding SQL injection when saving user-agent using ASP.net I'm saving the browser user-agent of my users for stats purposes. As you already know, user-agent can be modified. I would like to know if I should do anything to protect against SQL Injection. I'm using Stored Procedures for inserting. Many thanks. A: Use parameters with stored procedures or use parameters with dynamic SQL. Here's the example from MSDN: SqlDataAdapter dataAdapter = new SqlDataAdapter( "SELECT CustomerID INTO #Temp1 FROM Customers " + "WHERE CustomerID > @custIDParm; SELECT CompanyName FROM Customers " + "WHERE Country = @countryParm and CustomerID IN " + "(SELECT CustomerID FROM #Temp1);", connection); SqlParameter custIDParm = dataAdapter.SelectCommand.Parameters.Add( "@custIDParm", SqlDbType.NChar, 5); custIDParm.Value = customerID.Text; SqlParameter countryParm = dataAdapter.SelectCommand.Parameters.Add( "@countryParm", SqlDbType.NVarChar, 15); countryParm.Value = country.Text; connection.Open(); DataSet dataSet = new DataSet(); dataAdapter.Fill(dataSet); A: Use a prepared statement. Make sure you use a prepared statement for all SQL operations, even if the data comes out of the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R idiom for %*% using xts I am working with some code that uses the %*% operator to apply vectors of weights to vectors representing time series. I would like to use xts for the time series, but the %*% operator is not understanding that it should ignore the xts index values. I know I can use coredata() to pull out my series values as a vector, operate on the values, and merge them back in, but I was wondering whether there was a good native xts function I should be using. EDIT: code sample illustrating the difference I'm seeing in behavior. library(xts) data(sample_matrix) s<-as.xts(sample_matrix) o_xts<-s$Open c_xts<-coredata(s$Open) len <-length(c_xts) len2<-len/2 xx<-c_xts[1:len] outp<-0*0:len2 outp[2] <- xx%*%exp((1:(2*len2))*1.i*pi/len2) #completes without issue len <-length(o_xts) len2<-len/2 yy<-o_xts[1:len] outp<-0*0:len2 outp[2] <- yy%*%exp((1:(2*len2))*1.i*pi/len2) Warning message: In outp[2] <- yy %*% exp((1:(2 * len2)) * (0+1i) * pi/len2) : number of items to replace is not a multiple of replacement length A: If you check help("[.xts") you'll notice that drop defaults to FALSE. For ordinary matrices the default is TRUE. str(o_xts[1:len]) # An ‘xts’ object from 2007-01-02 to 2007-06-30 containing: # Data: num [1:180, 1] 50 50.2 50.4 50.4 50.2 ... # - attr(*, "dimnames")=List of 2 # ..$ : NULL # ..$ : chr "Open" # Indexed by objects of class: [POSIXct,POSIXt] TZ: # xts Attributes: # NULL str(c_xts[1:len]) # num [1:180] 50 50.2 50.4 50.4 50.2 ... That means that your xx is a 180 element vector whereas your yy is a 180 x 1 matrix. To get the same behaviour in both cases you could use yy <- o_xts[1:len, drop=TRUE]. A: I have not (yet) seen any evidence to support the premise of the question, and when I do my own simple test on the first example in help(xts) I come up with contrary evidence: > data(sample_matrix) > sample.xts <- as.xts(sample_matrix, descr='my new xts object') > str(coredata(sample.xts)) num [1:180, 1:4] 50 50.2 50.4 50.4 50.2 ... - attr(*, "dimnames")=List of 2 ..$ : NULL ..$ : chr [1:4] "Open" "High" "Low" "Close" > str(coredata(sample.xts) %*% c(3, 3,3,3) ) num [1:180, 1] 601 604 604 604 602 ... > str(sample.xts %*% c(3, 3,3,3) ) num [1:180, 1] 601 604 604 604 602 ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7535836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get a two column jquery autocomplete? I have two lists of things that I want to search through for an auto complete box on my site. One is a list of stores, and the other is a list of searches that other people have done for products. I would like autocomplete to display two columns, one column for the first search set and the other column for the other search set. For instance, someone searching shoes should see "shoebuy, payless shoes, shoemall, etc..." in the left list , then "shoe, shoes, shoe rack, shoe polish, etc.." in the second column. How can I do this? A: I doubt something like this already exists. What you can do is create a CSS two-column layout within a div that is displayed under the text field whenever it is changed. That way, you can populate each column individually, even using the same AJAX request: <input id="autocompleteField" type="text" /> <div class="autocomplete"> <div class="autoLeft"></div> <div class="autoRight"></div> </div> $("#autocompleteField").change(function () { $.get("url", $(this).val(), function(response) { $(".autoLeft").html(response.left); $(".autoRight").html(response.right); }, "json"); }); A: You could just trigger a search in a second input (hidden)... here is what I put together (demo): HTML var stores = [ 'shoes', 'shoes!', 'shoebuy', 'payless shoes', 'shoemall', 'shoes galore' ], searches = [ 'shoe', 'shoes', 'shoe rack', 'shoe polish', 'shoe horn' ], storeBox = $('#stores'), searchBox = $('#searches'), closeDropdowns = function() { searchBox.autocomplete('close'); storeBox.autocomplete('close'); }; storeBox.autocomplete({ source: stores, search: function(event, ui) { // initiate search in second autocomplete with the same value searchBox.autocomplete('search', this.value); }, select: function() { closeDropdowns(); }, close: function() { closeDropdowns(); } }); searchBox.autocomplete({ source: searches, select: function(event, ui) { storeBox.val(ui.item.value); searchBox.autocomplete('close'); storeBox.autocomplete('close'); }, close: function() { closeDropdowns(); } }); A: I have a slightly different idea, i can't be bothered to write the code right now (since its 2am) but ill give you the concept: (I am assuming your using JqueryUI.autocomplete) so you need to intercept the create event (look at the documentation of the categories section in JqueryUI autocomplete to figure this out). So on the create event you want to add two div's inside of the div that is the autocomplete bar/window/whatever and float them with width:50%;. then when you retrieve the values (via ajax) check a "category" (i.e. listLeft or listRight) and then use .append to add to each list accordingly, and make sure you give them the class of autocompleteButton or whatever its called. graphical representation:
{ "language": "en", "url": "https://stackoverflow.com/questions/7535845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SVN GIT local custom changes I'm in such situation: There is open source project still developed by 3rd party. I'm using it and have my custom source code changes on top of it. I don't want to commit anything back to 3rd party repository. Only get the newest updates. From the other side I want to re-distribute source code (3rd party code and my changes) to other locations. I.e. if there is a bugfix update from 3rd party I want just update my main repository and re-distribute the changes to other locations. The same applies when I do some custom updates. I've been thinking here for a while, but could not find most suitable solution. My idea: * *updates from 3th party using SVN to $REPODIR *$REPODIR will be my GIT repository - all other locations will pull then changes from here. *I will do my local changes and push them to $REPODIR Somebody have a better solution or has solved similar problem other way ? A: The git-svn command will help you with this. I'm using it for all SVN repos I have to work with, works like a charm! The following commands should get you started: mkdir svn-checkout cd svn-checkout git svn init --stdlayout < your SVN URL > git svn fetch Now take a big break, fetching may take days (!) depending on the number of revisions, branches and tags in the SVN repository. After that, issue git gc and take another big break. You might want to watch memory consumption. Good news is that setup has to be done only once. After that, the entire repository is on your local machine -- diff, log and annotate can be carried out without bothering the SVN server. After setup, you can start editing the code and commit using git. Whenever you want to get the latest updates from SVN, run git svn rebase The result is a git repo that has the current SVN state plus your changes. You might have to resolve conflicts introduced by your changes, though. See http://justaddwater.dk/2009/03/09/using-git-for-svn-repositories-workflow/ for a more elaborate explanation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why doesn't this closure modify the variable in the enclosing scope? This bit of Python does not work: def make_incrementer(start): def closure(): # I know I could write 'x = start' and use x - that's not my point though (: while True: yield start start += 1 return closure x = make_incrementer(100) iter = x() print iter.next() # Exception: UnboundLocalError: local variable 'start' referenced before assignment I know how to fix that error, but bear with me: This code works fine: def test(start): def closure(): return start return closure x = test(999) print x() # prints 999 Why can I read the start variable inside a closure but not write to it? What language rule is causing this handling of the start variable? Update: I found this SO post relevant (the answer more than the question): Read/Write Python Closures A: Example def make_incrementer(start): def closure(): # I know I could write 'x = start' and use x - that's not my point though (: while True: yield start[0] start[0] += 1 return closure x = make_incrementer([100]) iter = x() print iter.next() A: Whenever you assign a variable inside of a function it will be a local variable for that function. The line start += 1 is assigning a new value to start, so start is a local variable. Since a local variable start exists the function will not attempt to look in the global scope for start when you first try to access it, hence the error you are seeing. In 3.x your code example will work if you use the nonlocal keyword: def make_incrementer(start): def closure(): nonlocal start while True: yield start start += 1 return closure On 2.x you can often get around similar issues by using the global keyword, but that does not work here because start is not a global variable. In this scenario you can either do something like what you suggested (x = start), or use a mutable variable where you modify and yield an internal value. def make_incrementer(start): start = [start] def closure(): while True: yield start[0] start[0] += 1 return closure A: In Python 3.x you can use the nonlocal keyword to rebind names not in the local scope. In 2.x your only options are modifying (or mutating) the closure variables, adding instance variables to the inner function, or (as you don't want to do) creating a local variable... # modifying --> call like x = make_incrementer([100]) def make_incrementer(start): def closure(): # I know I could write 'x = start' and use x - that's not my point though (: while True: yield start[0] start[0] += 1 return closure # adding instance variables --> call like x = make_incrementer(100) def make_incrementer(start): def closure(): while True: yield closure.start closure.start += 1 closure.start = start return closure # creating local variable --> call like x = make_incrementer(100) def make_incrementer(start): def closure(start=start): while True: yield start start += 1 return closure A: There are two "better" / more Pythonic ways to do this on Python 2.x than using a container just to get around the lack of a nonlocal keyword. One you mentioned in a comment in your code -- bind to a local variable. There is another way to do that: Using a default argument def make_incrementer(start): def closure(start = start): while True: yield start start += 1 return closure x = make_incrementer(100) iter = x() print iter.next() This has all the benefits of a local variable without an additional line of code. It also happens on the x = make_incrememter(100) line rather than the iter = x() line, which may or may not matter depending on the situation. You can also use the "don't actually assign to the referenced variable" method, in a more elegant way than using a container: Using a function attribute def make_incrementer(start): def closure(): # You can still do x = closure.start if you want to rebind to local scope while True: yield closure.start closure.start += 1 closure.start = start return closure x = make_incrementer(100) iter = x() print iter.next() This works in all recent versions of Python and utilizes the fact that in this situation, you already have an object you know the name of you can references attributes on -- there is no need to create a new container for just this purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: vim bindkey-snipplet to shift a hole block of code around I've just made a little snipplet on my keybindings.vim to shift a hole block of code around. It works basically the same way I do it in the old fashioned manual way ( on normal mode, {V} to select the hole block on visual mode, then > and < to move through indentation, and :m+ and :m-2 to move down or up ). The problem I'm getting is that it works only to move around through indentation (horizontally), but for vertical move, it does not work. I just can't find the reason, as doing exactly the same sequence manually (as I'm used to), it works like a charm. First of all: I've tested the snipplet on Vim 7.2 (on Linux) and Vim 7.3 (on MacOS). Second: I know If I put a: vnoremap < <gv ...and a: vnoremap > >gv ...in my keymaps, I'll be able to move visual-selected blocks without loosing the visual selection... in spite of this, I'd like to get this working so I don't have to take care of the visual selection with a manual ESC {jV}k Can anybody tell me what am I doing wrong? I thank you all in advance! Regards! "============================================================================ "Ctrl + Shift + > [normal or insert mode] - move entire block around "============================================================================ nnoremap <silent> <C-S-Right> :let savecur=getpos(".")<CR>{V}><CR> \:call setpos('.', savecur)<CR>4l inoremap <silent> <C-S-Right> <Esc>:let savecur=getpos(".")<CR>{V}><CR> \:call setpos('.', savecur)<CR>5li nnoremap <silent> <C-S-Left> :let savecur=getpos(".")<CR>{V}<<CR> \:call setpos('.', savecur)<CR>4h inoremap <silent> <C-S-Left> <Esc>:let savecur=getpos(".")<CR>{V}<<CR> \:call setpos('.', savecur)<CR>3hi nnoremap <silent> <C-S-Up> :let savecur=getpos(".")<CR>{V}:m-2<CR> \:call setpos('.', savecur)<CR>k inoremap <silent> <C-S-Up> <Esc>:let savecur=getpos(".")<CR>{V}:m-2<CR> \:call setpos('.', savecur)<CR>ki nnoremap <silent> <C-S-Down> :let savecur=getpos(".")<CR>{V}:m+<CR> \:call setpos('.', savecur)<CR>j inoremap <silent> <C-S-Down> <Esc>:let savecur=getpos(".")<CR>{V}:m+<CR> \:call setpos('.', savecur)<CR>ji "============================================================================ A: Change the :move commands used in those mappings for moving a paragraph down from :m+ to :m'>+.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LINQ aggregating multiple IEnumerables into one? I have a Dictionary defined as <int, IEnumerable<char>>. Lets say the data is populated like: 1, a b c d e 2, f g h i j 3, k l m n o If I have an IEnumerable consisting of 1 & 3, what would the LINQ look like to return 'a b c d e k l m n o' (assuming space represents an iteration). A: SelectMany is indeed what you want, but IMHO it's more readable to use the comprehension syntax and let it do the mapping for you, so something like: var dict = ... // dictionary var keys = ... // enumerable with 1 and 3 in it var result = from key in keys from val in dict[key] select val; It's easier (again, IMHO) to toss an 'orderby' in there as well if/as needed. Of course, if you find the extension method version simpler to read/parse, then by all means, use that instead. :) A: If you want a KeyNotFoundException if a key is not found: IEnumerable<char> result = keys.SelectMany(key => d[key]); If you want to silently ignore keys that are not found: IEnumerable<char> result = keys.Where(key => d.ContainsKey(key)) .SelectMany(key => d[key]); A: Assuming that you have var someEnumerables = new Dictionary<int, IEnumerable<char>>(); then // Flattened will be an enumeration of the values ordered first by the key var flattened = someEnumerables.OrderBy(kvp => kvp.Key).SelectMany(kvp => kvp.Value) A: You need a Where clause to filter the keys contained in the dictionary, and a SelectMany clause to get a single enumerable list from each list contained in the dictionary. Dictionary<int, IEnumerable<char>> dict; // contains all of your key-value pairs IEnumerable<int> keys; // contains the keys you want to filter by IEnumerable<char> data = dict.Where(kvp => keys.Contains(kvp.Key)) .SelectMany(kvp => kvp.Value); // or, alternatively: IEnumerable<char> data = keys.SelectMany(i => dict[i]); Note that the second query will throw an exception if you have a key in the keys enumerable that doesn't exist in your dictionary. A: As you mentioned in your comment, you can use a SelectMany to aggregate an IEnumerable of IEnumerables into a single IEnumerable. However, you can also use Concat to combine two separate collections into a single selection (or you can chain it to combine as many as you'd like). A: It's unclear if you want only the 1 & 3 lines or all of them (1, 2 and 3). Here's the solution for both Dictionary<int, string> map = ...; // 1 and 3 only IEnumerable<char> result1 = map .Where(x => x.Key == 1 || x.Key == 3) .OrderyBy(x => x.Key) .SelectMany(x => x.Value) // All IEnumerable<char> result2 = map .OrderyBy(x => x.Key) .SelectMany(x => x.Value)
{ "language": "en", "url": "https://stackoverflow.com/questions/7535863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MVC3 Export to File Design I have a strongly typed View that displays a Model using ASP.NET MVC3. I want to add a link so the user can download the model displayed in the view into a CSV file. I was thinking the link would point to another action on the controller that took the model as an argument. What's the best practice? * *Should I be using jQuery .post, Html.ActionLink, etc.? *How do I pass the model that is displayed on the view back to the controller? I read something that made me think you can't pass the model back to the controller. I guess an alternative would be to get the data that hydrated the model from the database again, but that means a round trip to the database. *An alternative to passing the model back to the controller is to pass the div element back to the controller. This may not get exactly what I want (and seems hacky). Thanks for your input! A: You should create an action method that returns a custom ViewResult for your CSV file. That method could accept the same parameter used to return the model for the display action method and use it to retrieve the model (from a repository, for example) and return a file result. To implement that functionality, you would have to create a custom CsvFileResult class deriving from System.Web.Mvc.FileResult (that itself derives from System.Web.Mvc.ActionResult). The constructor of that class should take your model, create the comma separated output and return a file result with the MIME type text/csv. As an example, your Controller could look like this: public class ModelController : Controller { private readonly IModelRepository _modelRepository; public DemoController(IModelRepository modelRepository) { _modelRepository = modelRepository; } public ActionResult Display(int id) { var model = _modelRepository.Retrieve(id); return View(model); } public FileResult ExportCsvFile(int id) { var model = _modelRepository.Retrieve(id); return new CsvFileResult(model); } } On the client, you could output a link to the ExportCsvFile action method using the ActionLink helper method and the overload accepting parameter values: @Html.Helper("ExportCsvFile", "Model", new { id = Model.ModelID }) A: You could store the model as json on the client, then post back and convert to csv from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery callback and return to the first call? I for this function to load an external page. Page URL grab from DIV id. $(".contentArea").load($('.contentArea').attr('id'), function(){ The page loaded, got a datatable so I added it to the callback. $('.datatable').dataTable( { Inside the datatable, I got an editor button, so I used the datatable callback function to call the editor without page refresh: "fnDrawCallback": function(){ $(".contentEditor").click(function() { $(".contentArea").load($('.contentEditor').attr('id'), function(){ On this stange, content editor was loaded using the same way I used to load the page containing the datatable. (Page URL passed on the button ID). I got stuck now. On this editor, I need submit the form, I want it submitted using jquery load so the page don't get refreshed, after the form is submitted, I want send the surfer back to the datatable page (the one that was first loaded when the page was loaded). And I will perform the action necessary to update the edited content. Any help? Thanks. * *Im using datatable server side ajax load. That is why I used the callback. $(".contentArea").load($('.contentArea').attr('id'), function(){ $('.datatable').dataTable( { "bJQueryUI": true, "sScrollX": "", "bSortClasses": false, "aaSorting": [[0,'asc']], "bAutoWidth": true, "bInfo": true, "sScrollY": "100%", "sScrollX": "100%", "bScrollCollapse": true, "sPaginationType": "full_numbers", "bRetrieve": true, "bProcessing": true, "bServerSide": true, "sAjaxSource": $('.datatable').attr('id'), "fnDrawCallback": function(){ $(".contentEditor").click(function() { $(".contentArea").load($('.contentEditor').attr('id'), function(){ $( "select, input:checkbox, input:radio, input:file").uniform(), $( ".datepicker" ).datepicker({dateFormat: 'yy-mm-dd' }), $("#validation").validationEngine(), $('input[title]').tipsy(), $('textarea.tinymce').tinymce({ // Location of TinyMCE script script_url : '../scripts/tinyeditor/tiny_mce.js', // General options theme : "advanced", plugins : "table,advhr,advimage,advlink,inlinepopups,preview,media,paste,fullscreen,visualchars,xhtmlxtras", // Theme options theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,forecolor,backcolor", theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,removeformat,|,hr,|,undo,redo,|,sub,sup,|,charmap,|,cite", theme_advanced_buttons3 : "tablecontrols,|,link,unlink,anchor,|,image,preview,media,|,cleanup,code,fullscreen", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : true }); }); }); }}); }); A: To submit the form, use $.post() along with $(form).serialize(). Then, in the success handler of $.post(), use .load() again. $.post(url, $("#myForm").serialize(), function(data) { $(".contentArea").load(...); }); Or, if the content returned from submitting the form is the html you want to display in .contentArea, you can save yourself the extra call to .load() by just using the returned html in .contentArea: $.post(url, $("#myForm").serialize(), function(data) { $(".contentArea").html(data); }); Edit: Create functions to handle the different tasks. By the way, don't use id to store the url. Create a custom attribute... maybe contentUrl. var contentArea = $(".contentArea"); function loadContent(url, success) { contentArea.load(url, success); } function loadDataTable() { loadContent(contentArea.attr("contentUrl"), initDataTable); } function initDataTable() { $(".datatable").dataTable({ ..., fnDrawCallback: bindContentEditor }); } function bindContentEditor() { $(".contentEditor").click(contentEditorClick); } function contentEditorClick(e) { loadContent($(".contentEditor").attr("contentUrl"), initContentEditor); } function initContentEditor() { ... $(".submitBtn").click(postContentEditor); } function postContentEditor() { $.post("/postUrl", $(".contentArea form").serialize(), loadDataTable); } loadDataTable(); I've broken it down into perhaps too many individual functions, but the point is just not to over-use anonymous functions, especially when you want to re-use functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android button latency? I've been working on a drum machine app, and the latency between the time you press the button and the time the sound plays is unbearable. I have seen some people use multitouch and gridviews, and make several buttons able to be pressed at the same time, but I honestly have no knowledge of those. How could I set up multitouch or gridviews to reduce the latency? A: I would guess the multitouchable buttons are a very custom implementation. You won't ever be able to touch two ordinary buttons simultaneosly, since they are made for single touch and are based on focus gain etc. Here's my idea behind a multitouchable implementation: You create a very custom view which will draw all buttons you need. This view should override onTouchEvent and react on multitouch. I never tried that, but this is the only option I can think of.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: load file on hover using jQuery I want to load an external file (using jQuery) when the user hovers a div. I tried loading it like a css file on hover but no luck. (Also, I can load a css file on hover, right? That code I tried for that is below.) $(document).ready(function () { $("#f1_container2").hover(function () { $('head').append('<link rel="stylesheet" href="theme/supersized.shutter.css" type="text/css" media="screen" />'); }); }); A: You can load content using $(".target").load("file.html"), where file.html is an HTML fragment containing some markup. Since CSS is passive (it doesn't do anything until someone uses it), it can sit in the head in the first place. That way, when you hover over a div, you can do $(".target").addClass("newClass") to apply some groovy styling. hover() can also take a SECOND function, which is invoked when the mouse leaves the target, so you can undo whatever you did on the mouseover. A: The document has already been loaded and rendered when you append the code for the stylesheet. The browser has already retrieved the needed resources and won't retrieve a file because you appended some code. I would recommend, as mentioned, pre-loading your images or using another technique to retrieve the file on hover. I believe something like this may work. $(document).ready(function () { $("#f1_container2").hover(function () { // The easy way //$('head').append('<img src="images/sprite.gif">'); // The cool way var $img = $('<img>', { src: 'images/sprite.gif', load: function() { $(this).fadeIn('slow'); }, css: { display: 'none' } }).appendTo('body'); // append to where needed }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7535884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting JSUnit, Ant & Hudson working I'm trying to get my JSUnit tests to run on Hudson. But the browser keeps timing out: [junit] INFO: Launching Internet Explorer on http://localhost/jsunit/testRunner.html?testPage=localhost/jsunit/tests/jsUnitOnLoadTests.html&autoRun=true&browserId=0&submitResults=localhost:8081/jsunit/acceptor [junit] 24/09/2011 9:29:14 AM net.jsunit.TestRunManager runTests [junit] INFO: Waiting for Internet Explorer to submit result [junit] 24/09/2011 9:30:15 AM net.jsunit.TimeoutChecker run [junit] WARNING: Browser Internet Explorer timed out after 60 seconds I get the same result if I use IE, Firefox or Chrome. If I run ANT from the command line, it get a result as expected: [junit] INFO: Launching Internet Explorer on http://localhost/jsunit/testRuner.html?testPage=localhost/jsunit/tests/jsUnitOnLoadTests.html&autoRun=true&broserId=0&submitResults=localhost:8081/jsunit/acceptor [junit] 24/09/2011 9:28:58 AM net.jsunit.TestRunManager runTests [junit] INFO: Waiting for Internet Explorer to submit result [junit] - Could not load portlet-api, disabling webwork's portlet support. [junit] 24/09/2011 9:29:00 AM net.jsunit.action.ResultAcceptorAction execute [junit] INFO: Received submission from browser Internet Explorer The unit tests I'm using are the defaults that come with JSUnit: failingTest.html & jsUnitOnLoadTests.html I don't think its a permission thing, (since I can run it from the command line). OS: Windows 7, Java 1.6.0 update 26, ANT 1.8.2 A: Ok, it turns out that it was a permissions issue. To get this to run, I had to change the Service Account Hudson was using to one with elevated permissions. Stop / Restart service and it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python sort unique list of lists' items I can't seem to find a question on SO about my particular problem, so forgive me if this has been asked before! Anyway, I'm writing a script to loop through a set of URL's and give me a list of unique urls with unique parameters. The trouble I'm having is actually comparing the parameters to eliminate multiple duplicates. It's a bit hard to explain, so some examples are probably in order: Say I have a list of URL's like this * *hxxp://www.somesite.com/page.php?id=3&title=derp *hxxp://www.somesite.com/page.php?id=4&title=blah *hxxp://www.somesite.com/page.php?id=3&c=32&title=thing *hxxp://www.somesite.com/page.php?b=33&id=3 I have it parsing each URL into a list of lists, so eventually I have a list like this: sort = [['id', 'title'], ['id', 'c', 'title'], ['b', 'id']] I nee to figure out a way to give me just 2 lists in my list at that point: new = [['id', 'c', 'title'], ['b', 'id']] As of right now I've got a bit to sort it out a little, I know I'm close and I've been slamming my head against this for a couple days now :(. Any ideas? Thanks in advance! :) EDIT: Sorry for not being clear! This script is aimed at finding unique entry points for web applications post-spidering. Basically if a URL has 3 unique entry points ['id', 'c', 'title'] I'd prefer that to the same link with 2 unique entry points, such as: ['id', 'title'] So I need my new list of lists to eliminate the one with 2 and prefer the one with 3 ONLY if the smaller variables are in the larger set. If it's still unclear let me know, and thank you for the quick responses! :) A: I'll assume that subsets are considered "duplicates" (non-commutatively, of course)... Start by converting each query into a set and ordering them all from largest to smallest. Then add each query to a new list if it isn't a subset of an already-added query. Since any set is a subset of itself, this logic covers exact duplicates: a = [] for q in sorted((set(q) for q in sort), key=len, reverse=True): if not any(q.issubset(Q) for Q in a): a.append(q) a = [list(q) for q in a] # Back to lists, if you want
{ "language": "en", "url": "https://stackoverflow.com/questions/7535889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Xcode: Why doesn't this code work for saving UITextField using NSUserDefaults? I have an UITextField inside an UITableViewCell. What I want't is for the app to save the text the user inputs. I've tried by making the UITextField call a action with this code: [TextField addTarget:self action:@selector(saveTextField:) forControlEvents:UIControlEventEditingDidEndOnExit]; However this action that it load doesn't work correctly: - (IBAction)saveTextField:(id)sender { NSString *TextFieldString = [[NSString alloc] initWithString:TextField.text]; [TextField setText:TextFieldString]; NSUserDefaults *UserSettings = [NSUserDefaults standardUserDefaults]; [UserSettings setObject:TextField forKey:@"TextField"]; } When I exit the UITextField by trying to hide the keyboard by clicking "Done" I get this message: *** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSInvalidArgumentException> *** -[NSPlaceholderString initWithString:]: nil argument and nothing happens in the app. Any thoughts? Thanks in advance :) A: I use the exact same functionality in one of my apps, and this is the code I use: [[NSUserDefaults standardUserDefaults]setObject: textField.text forKey:@"TextField"]; Basically, I don't think the first two lines in your saveTextField method where you alloc a new string are necessary. A: To begin with: thanks for your effort and time :) Turns out the problem wasn't with the code that saves and loads it. The problem was that I only created one UITextfield which I then put into every UITableViewCell and that was the problem. So I created individual UITextFields for every UITableViewCells and that fixed the problem :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7535894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read binary file I need help with an issue that i have. I want to read a binary file. The content of the file are: 0000000010001100 I'm using the following code to reach my goal: InputStream is = new FileInputStream(new File("/test.bin")); DataInputStream din = new DataInputStream(is); System.out.println(din.readByte() & 0xFF); I was expecting that the output was 0, because an unsigned byte of eight zeros is 0. But the code prints 48. Can someone tell me what i am doing wrong and explain me how can i have an output of 48 ? A: Are you sure you didn't inadvertenly save a '0' as the first character in the file? The ASCII for the text character '0' is 48.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unobtrusive Windows Notifications I'm looking for a simple solution to create an unobtrusive notification program for windows using c++/QT/WinAPI/SDL or any other quick library. I'm wondering what the fastest method (as far as development goes) to create a simple program that pops a quick window up with access to a larger gui interface if clicked. Is there a quick and easy way to set something up like this? A: You may want to have a look at Growl for Windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How To Signal End Of Data Without Closing NetworkStream in C# I have a client application that serializes a object and sends it to a server application. The server should deserialize the object, make changes to it, then serialize it and send it back. Server Code: TcpClient client = server.AcceptTcpClient(); using(NetworkStream stream = client.GetStream()) { using(StreamReader streamReader = new StreamReader(stream)) { string xmlData = streamReader.ReadToEnd(); } } The ReadToEnd doesn't return unless the client closes the stream. But if the client closes the stream, I can't send a response. Is there a better way to do this? A: You could use a higher level framework like WCF, or if you are hell-bent on managing your own streams, then don't use ReadToEnd()- use ReadLine() (and have the client send messages as lines), or use Read() and have a special character (a sentinel) represent the end of a message. A: You can signal "end of data" by closing only your half of the duplex TCP connection. This is accomplished with Socket.Disconnect. See how it works with this example, which I kept similar to yours. The client sends the data and then calls Disconnect; this allows ReadToEnd to return while still keeping the server's half of the connection open. The server then sends a response and also disconnects, after which both parties can Close their end of the connection to tear it down. static void Main(string[] args) { Action clientCode = () => { var buffer = new byte[100]; var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(IPAddress.Loopback, 6690); clientSocket.Send(buffer); clientSocket.Disconnect(false); Console.WriteLine("Client: message sent and socket disconnected."); while (true) { var bytesRead = clientSocket.Receive(buffer); if (bytesRead == 0) { break; } Console.WriteLine("Client: read " + bytesRead + " bytes."); } clientSocket.Dispose(); }; var server = new TcpListener(IPAddress.Loopback, 6690); var thread = new Thread(new ThreadStart(clientCode)); server.Start(); thread.Start(); var client = server.AcceptTcpClient(); using(NetworkStream stream = client.GetStream()) { using(StreamReader streamReader = new StreamReader(stream)) { var data = streamReader.ReadToEnd(); Console.WriteLine("Server: read " + data.Length + " bytes."); // Since we 're here we know that the client has disconnected. // Send the response before StreamReader is disposed, because // that will cause the socket itself to be closed as well! Thread.Sleep(TimeSpan.FromSeconds(1)); Console.WriteLine("Server: sending response."); stream.Write(new byte[10], 0, 10); Console.WriteLine("Server: closing socket."); } } server.Stop(); Console.WriteLine("Server: waiting for client thread to complete."); thread.Join(); return; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: timeout in MYSQL I have a java application that has long running processes and interact with db. It keeps getting the following: The last packet successfully received from the server was 3,601,168 milliseconds ago. The last packet sent successfully to the server was 3,601,166 milliseconds ago. The remote server has a wait_timeout 354600 which is in seconds. What could be wrong? A: There could be a number of problems, but I don't believe wait_timeout is the culprit if your last packet was sent/received about 3600s ago and wait_timeout is 354600s. You could have lost the connection to the server or any other of a number of things. You need to post more about what your code is doing and more about what you expect to happen and what is actually happening. * *Side question: MySQL was designed to create connections relatively quickly. Have you considered using a connection pool rather than continuously using one connection explicitly? As for Cassio's comment under the question... wait_timeout is in seconds. MySQL Docs - wait_timeout
{ "language": "en", "url": "https://stackoverflow.com/questions/7535902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting EF 4.1 Code First project working I am building a simple application with EF 4.1 Code First, but I am stuck. Here's an ERD of my application Domain Model: In Visual Studio 2010, I have a solution with two projects in it. One project is to house the Domain Model, the other is an MVC3 Web Application to house the application logic. In the Class Libraries (Project 1), I have the following code: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; namespace QuotesDomain { public class QuoteContext : DbContext { public DbSet<Quote> Quotes { get; set; } public DbSet<Author> Authors { get; set; } public DbSet<Language> Languages { get; set; } public DbSet<Tag> Tags { get; set; } public DbSet<QTBridge> QTBridge { get; set; } } public class Quote { public int Id { get; set; } [Required, MaxLength(500)] public string Body { get; set; } public int Likes { get; set; } [Required] public bool isApproved { get; set; } [Required] public DateTime CreatedOn { get; set; } [Required] public virtual Author Author { get; set; } [Required] public virtual Language Language { get; set; } public virtual ICollection<QTBridge> TagsBridge { get; set; } } public class Author { public int Id { get; set; } [Required, MaxLength(30), MinLength(2)] public string FirstName { get; set; } [Required, MaxLength(30), MinLength(2)] public string LastName { get; set; } [Required] public DateTime DOB { get; set; } public DateTime DOD { get; set; } [Required, MaxLength(60), MinLength(2)] public string Occupation { get; set; } [Required, MaxLength(170), MinLength(5)] public string WikiLink { get; set; } public byte[] Image { get; set; } [Required] public bool isApproved { get; set; } [Required] public DateTime CreatedOn { get; set; } public virtual ICollection<Quote> Quotes { get; set; } } public class Language { public int Id { get; set; } [Required, MaxLength(20), MinLength(2)] public string Name { get; set; } public byte[] Image { get; set; } [Required] public DateTime CreatedOn { get; set; } public virtual ICollection<Quote> Quotes { get; set; } } public class Tag { public int Id { get; set; } [Required, MaxLength(40), MinLength(2)] public string Name { get; set; } public byte[] Image { get; set; } [Required] public DateTime CreatedOn { get; set; } public virtual ICollection<QTBridge> QuotesBridge { get; set; } } public class QTBridge { public int Id { get; set; } public int QuoteId { get; set; } public int TagId { get; set; } } } I've been watching some video tutorials, and the above looks good to me, but when I try and run the application, I get the following error: Are my Code First classes correct based on the ERD Diagram? What do I need to do to solve the error? A: Here's the full listing of code for Entities and configuration. public class QuoteContext : DbContext { public DbSet<Quote> Quotes { get; set; } public DbSet<Author> Authors { get; set; } public DbSet<Language> Languages { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //This will create create a join table "QuoteTags" modelBuilder.Entity<Quote>().HasMany(q => q.Tags) .WithMany(t => t.Quotes); } } public class Quote { public int Id { get; set; } [Required, MaxLength(500)] public string Body { get; set; } public int Likes { get; set; } [Required] public bool IsApproved { get; set; } [Required] public DateTime CreatedOn { get; set; } public int AuthorId { get; set; } [ForeignKey("AuthorId")] public virtual Author Author { get; set; } public int LanguageId { get; set; } [ForeignKey("LanguageId")] public virtual Language Language { get; set; } public virtual ICollection<Tag> Tags { get; set; } } public class Author { public int Id { get; set; } [Required, MaxLength(30), MinLength(2)] public string FirstName { get; set; } [Required, MaxLength(30), MinLength(2)] public string LastName { get; set; } [Required] public DateTime DOB { get; set; } public DateTime DOD { get; set; } [Required, MaxLength(60), MinLength(2)] public string Occupation { get; set; } [Required, MaxLength(170), MinLength(5)] public string WikiLink { get; set; } public byte[] Image { get; set; } [Required] public bool IsApproved { get; set; } [Required] public DateTime CreatedOn { get; set; } public virtual ICollection<Quote> Quotes { get; set; } } public class Language { public int Id { get; set; } [Required, MaxLength(20), MinLength(2)] public string Name { get; set; } public byte[] Image { get; set; } [Required] public DateTime CreatedOn { get; set; } public virtual ICollection<Quote> Quotes { get; set; } } public class Tag { public int Id { get; set; } [Required, MaxLength(40), MinLength(2)] public string Name { get; set; } public byte[] Image { get; set; } [Required] public DateTime CreatedOn { get; set; } public virtual ICollection<Quote> Quotes{ get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: soap primitive error I am having some issues with accessing a web service. Getting ClassCastException Error. Consider a scenario that I am trying to access a method of a web-service and the webservice is supposed to return two strings (Lets say String1 and String2). Moreover, I have to provide or pass two parameters (lets say Parameter 1 and Parameter 2 where Parameter 1 should be integer and Parameter 2 should be String) Here is my code public class MyWebService extends Activity { private static final String SOAP_ACTION ="http://www.mywebsite.com/myMethod"; private static final String METHOD_NAME = "MyMethod"; private static final String NAMESPACE = "http://www.myNamespace/"; private static final String URL = "http://mysession.com/myservice.asmx?WSDL"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo pi = new PropertyInfo(); pi.setName("Parameter 1"); pi.setValue(1); pi.setType(pi.INTEGER_CLASS); request.addProperty(pi); PropertyInfo pi2 = new PropertyInfo(); pi2.setName("Parameter 2"); pi2.setValue("Any string"); pi2.setType(pi2.STRING_CLASS); request.addProperty(pi2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet=true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); SoapObject result=(SoapObject)envelope.getResponse(); String string1=result.getProperty(0).toString(); String string2=result.getProperty(1).toString(); } catch (Exception e) { e.printStackTrace(); } } } This is the exception I am getting java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive Can anyone tell me if I am doing something wrong here.. Thanks A: Try this, SoapPrimitive result= (SoapPrimitive)envelope.getResponse(); OR Object result= (Object)envelope.getResponse(); instead of SoapObject result=(SoapObject)envelope.getResponse(); A: Try this: SoapObject request = new SoapObject(SOAP_NAMESPACE,SOAP_METHOD); request.addProperty("name", abcd); request.addProperty("age", 30);
{ "language": "en", "url": "https://stackoverflow.com/questions/7535906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Attaching JQuery Events to "on the fly created" controls I'm appending to an existing div in my page. The appended text contains html code in string. The problem is, events aren't working when I add click on them after appending to page. I guess Jquery loads control on page load and I have to do something to attack the events again. A: Try to use .live() or .delegate for this purpose. A: You are missing delegate(). So if you run $('#workingArea a.doAction').bind('click', function(){ // do stuff }); or the equivalent $('#workingArea a.doAction').click(function(){ // do stuff }); Any a's loaded after that runs don't get the event. If instead you do $('#workingArea').delegate('a.doAction', 'click', function(){ // do stuff }); then those events will be captured for any and all future a.doAction elements that get added, as long as #workingArea exists when it is run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How statics are initialized in C# Ok, I have greatly changed the code to show the actual problem more clearly. I have tested this code, and it definitely fails. public class MyEnumBase { private int _val; private static Dictionary<int, MyEnumBase> ValueMap = new Dictionary<int, MyEnumBase>(); protected MyEnumBase() { _val = ValueMap.Count; ValueMap.Add(_val, this); } public static MyEnumBase ValueOf(int i) { return ValueMap[i]; } public static IEnumerable<MyEnumBase> Values { get { return ValueMap.Values; } } public override string ToString() { return string.Format("MyEnum({0})", _val); } } public class Colors : MyEnumBase { public static readonly Colors Red = new Colors(); public static readonly Colors Green = new Colors(); public static readonly Colors Blue = new Colors(); public static readonly Colors Yellow = new Colors(); } class Program { static void Main(string[] args) { Console.WriteLine("color value of 1 is " + Colors.ValueOf(2)); } } The following code fails because the Colors constructor is never called before ValueOf() is called. Is there a clean way to ensure that all my static fields are called before I call ValueOf? Thanks, ~S A: Static fields get initialized before you use them. Exact time depends on implementation and you should not make any assumptions about it. Static fields initialization: The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. The code that you posted should work: Child.TimesConstructed() will not print 0 if you access one of the children (Child.C1) prior to this call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: -HD image file not found? Why am I getting cocos2d: CCFileUtils: Warning HD file not found: META-hd.png If I definitely have META-hd.png file in my project? What I am doing is running my .tmx tilemap. The map uses a tileset that searches for "META.png" (without -hd suffix since I am expecting cocos2d to automatically put it on). A: I've found the problem. I only do have -hd versions of my files. But I don't have "non-hd" versions. And for some reason, CCFileUtils will throw me errors when I don't have both types in my project. A: Verify that the image is part of the app's target. If it was included as part of a group, and say there was a duplicate on file 10 of 25, the copy stops and files 1-9 are NOT tagged as part of the target. You have to go back and sweep the floor by hand. In Xcode 4 show the assistant editor, and click the resource in the navigator. The target membership will be shown. If your app is not checked, click on that and voilà, the file will now be found. In rare cases, i have had to clean the target and recompile to make this effective. A: If I understand correctly you will have to have a -hd version of the tilemap as well: meta.tmx and meta-hd.tmx. Also be sure that your image file is named META-hd.png and not META-HD.png and both images use the same case: META.png and META-hd.png. The iPhone file system is case sensitive (not the iOS Simulator though).
{ "language": "en", "url": "https://stackoverflow.com/questions/7535920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a variable with $.post for javascript script? Here is my code in my jquery/javascript that is performing the ajax request... else { $.post("http://www.example.com", {email: val}, function(response){ finishAjax('email', response); }); } joinAjax('cemail'); } if (id == 'cemail') { $('#cemailMsg').hide(); var email = $('#email').val(); if (errors.email == false) { if (val != email) { The ajax request is working and all is good, but the next if statement where the argument is: if (errors.email == false) { I need to be able to set this variable from my ajax.php file to either true or false and return it so the javascript can read it. Is this possible?? It is because the ajax is checking if the username is available or not, if not available a form error would be true preventing the form submitting, or if false then the user can submit. My ajax.php file: if ($_REQUEST['email']) { $q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?"); $q -> execute(array($_REQUEST['email'])); if (!$q -> rowCount()) { echo '<div id="emailMsg" class="success">Email OK</div>'; exit(); } else { echo '<div id="emailMsg" class="error">Email taken</div>'; exit(); } } A: Why not have your ajax.php return an associative array like so: echo json_encode(array("email" => "success", "key2" => "val2")); And then use var responseJSON = JSON.parse(response); In the $.post callback function to read the response and act accordingly. You can generate the appropriate markup (divs or whatever) client-side and insert it. A: You may want to back up and determine what you want here. If all you want to do is display a different message depending on the result of the post, return (from the post) the smallest amount of information. In this case the value could simply be boolean. email valid or invalid. I would recommend returning json from your post. If you are returning json, the success method (function(response){}) is where you could operate on or evaluate the response. If you return json (which can be strings from PHP, in this case), it evaluates to JavaScript objects. so if you returned '{"errors":"true"}' it will evaluate to (response.errors === true) within your success method in the post call. 'errors' is undefined, correct? Make it a property of the response json object, and be sure to test for undefined values on the data you get back. Generate HTML or manipulate CSS based on the values you get from the post. In that vein, jquery makes it easy to add HTML to the DOM. Try (can someone fix my formatting and add a code tag if you can edit? I'm on my cell ATM) $('&ltdiv&gt&lt/div&gt', { text : 'your text here', class : 'yourclass' }).appendTo($(element));
{ "language": "en", "url": "https://stackoverflow.com/questions/7535922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting MySQL SQL Modes to be stricter before migrating to SQL Server 2008 We're eventually migrating an application to SQL Server 2008, but before we do that, we're considering setting the MySQL SQL modes to be stricter so that we can test the "looseness" of the existing application before it's migrated to the stricter SQL Server 2008. What are some MySQL SQL modes we can set in order to get it to be more at the strictness level of SQL Server 2008 to help better facilitate the migration eventually? A: The best place to start would be the mode MSSQL This enables: PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, NO_KEY_OPTIONS, NO_TABLE_OPTIONS, NO_FIELD_OPTIONS, NO_AUTO_CREATE_USER Some others that caught my attention while looking through the list of modes where: PAD_CHAR_TO_FULL_LENGTH and ONLY_FULL_GROUP_BY I would also try to import the data into SQLServer 2008 and run queries against both while developing in MySQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to INSERT multiple rows when some might be DUPLICATES of an already-existing row? So I have a checkbox form where users can select multiple values. Then can then go back and select different values. Each value is stored as a row (UserID,value). How do you do that INSERT when some rows might be duplicates of an already-existing row in the table? Should I first delete the existing values and then INSERT the new values? ON DUPLICATE KEY UPDATE seems tricky since I would be INSERTing multiple rows at once, so how would I define and separate just the ones that need UPDATING vs. the ones that need INSERTING? For example, let's say a user makes his first-time selection: INSERT INTO Choices(UserID,value) VALUES ('1','banana'),('1','apple'),('1','orange'),('1','cranberry'),('1','lemon') What if the user goes back later and makes different choices which include SOME of the values in his original query which will thus cause duplicates? How should I handle that best? A: In my opinion, simply deleting the existing choices and then inserting the new ones is the best way to go. It may not be the most efficient overall, but it is simple to code and thus has a much better chance of being correct. Otherwise it is necessary to find the intersection of the new choices and old choices. Then either delete the obsolete ones or change them to the new choices (and then insert/delete depending on if the new set of choices is bigger or smaller than the original set). The added risk of the extra complexity does not seem worth it. Edit As @Andrew points out in the comments, deleting the originals en masse may not be a good plan if these records happened to be "parent" records in a referential integrity definition. My thinking was that this seemed like an unlikely situation based on the OP's description. But it is definitely worth consideration. A: It's not clear to me when you would ever need to update a record in the database in your case. It sounds like you need to maintain a set of choices per user, which the user may on occasion change. Therefore, each time the user provides a new set of choices, any prior set of choices should be discarded. So you would delete all old records, then insert any new ones. You might consider carrying out a comparison of the prior and new choices - either in the server or client code - in order to calculate the minimum set of deletes and/or inserts needed to reduce database writes. But that smells like premature optimisation. Putting all that to one side - if you want a re-insert to be ignored then you should use INSERT IGNORE, then existing rows will be quietly ignored and new ones will be inserted. A: I don't know much about mysql but in MS SQL 2000+ we can execute a stored proc with XML as one of it's parameters. This XML would contain a list of identity-value pairs. We would open this XML as a table using openxml and figure out which rows need to be deleted or inserted using left or right outer join. As of SQL 2008 (I think) we have a new merge statement that let's us perform delete, update and insert row operations in one statement on ONE table. This way we can take advantage of Set mathematical operations from SQL instead of looping through arrays in the application code. You can also keep your select list retrieved from the database in session and compare the "old list" to the "newly selected list" in your application code. You would need to figure out which rows need to be deleted or added. You probably don't need to worry about updates because you are probably only keeping foreign keys in this table and the descriptions are in some kind of a reference table. There is another way in SQL 2008 that involves using user defined data-types as custom tables but I don't know much about it. Personally, I prefer the XML route because you just send the end-state into the sp and your sp automatically figures out which rows need to deleted or inserted. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using a Telerik control inside a repeater I am using the asp.net Repeater control. (My company is heavily invested in that, so I can't change it.) I need a way to create a poup edit window, specific to the row the user clicked on in the repeater, so the user can edit the data in that record. We have the Telerik controls to use, but I don't know which one. I saw the radwindow, but can find no examples of using it in a repeater. Frankly, Telerik documentation is confusing. I prefer to use client-side code, ajax and web-services. I'd like to prevent post-backs. 1) Please give me a reference to a specific example of using the Telerik radwindow inside a repeater for this purpose. OR 2) Clue me in to a better idea. Thank you. A: I don't think there are explicit examples with an asp Repeater, but I found this one with a GridView. The approach should be the same, as it is just another databound control - it shows an easy way to open a RadWindow on the client by passing some parameters (it is actually not possible to open it on the server, it is a client-side object). Some more complex examples I found on their site here and here. They both update a grid, yet they show a nice way to use AJAX to prevent a full postback.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: using 'lighter' weight of a font I'm trying to use the "Helvetica Light" font, which comes bundled with Helvetica. To do this I read that I had to specify "Helvetica Light" AND font-weight: lighter. I've gotten this to work only by doing this (in SASS): p font: "Helvetica Light", Arial, sans-serif font-size: 12px font-weight: lighter and in other instances, h2.light font: Helvetica, Arial, sans-serif font-size: 12px font-weight: lighter (or with font-family instead of font) which is really weird and the only combos that works so far (combining all properties into 'font' doesn't work, and calling the font: as font-family: sometimes doesn't work. In another rule, I wasn't able to get it to work unless I ONLY had font-weight: lighter with no font specified (but it inherited Helvetica). Now I copied the exact same font styles as the p and put it in an h4 and it no longer works. Wtf? What am I doing wrong/why is this so buggy? EDIT: THIS IS NOT A SYNTAX PROBLEM. To the answers below, note that I am using SASS. No semicolons and brackets needed. Also the file I am editing is 5k lines long (a hand me down) and grouped into somewhat organized sections. So I'd like to keep the sections intact until I can refactor it, but then I can't group all the p's and h2.lights together since they are in different sections. Thanks! A: Try this. p font: 'Helvetica Light', 'Helvetica', Arial, sans-serif font-size: 12px font-weight: 100 Just for reference, lighter works relative to the inherited value. It's better to use absolute values. http://www.w3.org/TR/CSS2/fonts.html#font-boldness A: what finally worked for me was to have font-family as Helvetica, and font-weight as lighter (but not the condensed format, which doesn't work). A: Note: this answer was written before the OP specified SASS. It applies to CSS only. A couple of things you should do to clean this up: Semi-colons All your CSS rules should end with a semi-colon, such as font-weight:lighter; Grouping As you have 2 identical CSS rules, the fastest and most concise way to do it is this: p, h2.light, other_rules { font: Helvetica, Arial, sans-serif; font-size: 12px; font-weight: lighter; } Then for the one rule where you want a different font, p{ font: "Helvetica Light", Arial, sans-serif; } Be sure to put your exceptions below the general rules (i.e. in the order I've shown you here) because CSS is implemented in order, and a rule further down the document will take priority. A: Try this: p, h2.light font: "Helvetica Light", Arial, sans-serif font-size: 12px font-weight: lighter A: inheritance, establish a base metric typography, so device doesn't crack-up style intersections body[role="put something here"] h1, p, etc font-size: 62.5% Helvetica light, mix with unix-mac-windows-webfont (webfont needs js, may pull you up over edge font-family Helvetica Light, Helveticaneue Light, Calibri Light, Helveticaneue, Helvetica, Gill Sans, Myriad Pro, Arial, Lucida Grande, sans-serif degrade per Meyer, or try just 2 hl, ss... also, check out your mixin https://github.com/less/less.js/issues/389 Sass for Web Designers by Dan Cedarholm and Chris Coyier
{ "language": "en", "url": "https://stackoverflow.com/questions/7535934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Creating a webservice inside a dll file? Can it be done? I would like to create a c# dll that handles requests. I would like the requests to come as webservice calls so that websites can quickly call the dll. Is there a way to integrate the two - to have the code for the webservice be placed inside of the dll? Or, if the webservice has to be separate - is there a way with visual studio to put the webservice into the project with the dll but tell the compiler to compile it as an external file? That way this would at least help me keep my project structure simple and clean. A: It's unclear to me what you're really trying to do. "A DLL that services requests" can be implemented in any number of ways. One way to implement a Web service in a DLL would be to use an HttpListener. You'll have to supply more information about what exactly you're trying to do before we can provide reasonable answers. A: All you need to do is create a new WCF Service Project. This will cause your services to be created as a separate application under IIS. Both projects would be in the same solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XCode 4 is hiding the results from Find operation Please take a look at this: It says 'Found 6 results in 3 files', but how can I see which files are those and the exact line, you know the usual way. I've haven't set any options or settings anywhere, its just all default settings. This is making me crazy! A: Thanks everyone for taking interest in it, but I think I found the answer. Its as dumb as the question. There is another field to filter the result at bottom and when I cleaned it I got everything back to normal :) Hope this saves somebody hours.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I fetch rand records from a union query? SELECT a, b, c FROM ".TBL_A." WHERE [statement] **`ORDER BY RAND()`** LIMIT 1 UNION (SELECT a, b, c FROM ".TBL_A." WHERE [different statement] ORDER BY RAND() LIMIT 5)"; This query works fine without first ORDER BY RAND(), but what I need is to fetch first rec randomly by first statement and then 5 other random recs by other statement. It seems that I can't use two order by statements on one query... Any thoughts? A: Your approach should work. Perhaps you just need to wrap your selects in an outer select. SELECT * FROM ( SELECT a, b, c FROM your_table WHERE [statement] ORDER BY RAND() LIMIT 1 ) T1 UNION SELECT * FROM ( SELECT a, b, c FROM your_table WHERE [different statement] ORDER BY RAND() LIMIT 5 ) T2 Note. Make sure that you have considered the difference between UNION and UNION ALL. It is a common mistake to get them mixed up. A: you should select it all with out order - and then do big select for the 2 queries with order by. A: Do not use RAND() it is a terrible generator. Use a cryptographically secure generator. Depending on platform it might be arcrand(), reading from /dev/random, openSSL or some other source.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: python subprocess.Popen vs shlex question my sub process command to search first off it only searches one directory that i wrote (s2) omits the first (s1). second i was doing some reading on python docs and got confused. my code def search_entry(self, widget): s1 = subprocess.Popen(['find', '/home/bludiescript/tv-shows', '-type', 'f'], shell=False, stdout=subprocess.PIPE) s2 = subprocess.Popen(['find', '/media/FreeAgent\ GoFlex\ Drive/tobins-media', '-type', 'f'], stdin=s1.stdout, shell=False, stdout=subprocess.PIPE) s1.stdout.close() self.contents = "\n".join(self.list) s2.communicate(self.contents) what i got confused about was with the shlex module and how to use it in place of subprocess.Popen in my code and if it would even make sense. so would some like this work better than what i have cmd = 'find /media/FreeAgent\ GoFlex\ Drive/tobins-media -type f find /home/bludiescript/tv-shows -type f' spl = shlex.split(cmd) s1 = subprocess.Popen(spl, stdout=subprocess.PIPE) self.contents = "\n".join(self.list) s1.communicate(self.contents) thanks again for you input A: It sounds like you want to run a pair of commands and join the output from them: cmds = [ 'find /media/FreeAgent\ GoFlex\ Drive/tobins-media -type f', 'find /home/bludiescript/tv-shows -type f' ] ouput = '\n'.join(subprocess.check_output(shlex.split(cmd)) for cmd in cmds) A: Try os.walk instead of invoking find. This will result in more robust code. The following is equivalent to your first invocation of find: top = '/media/FreeAgent GoFlex Drive/tobins-media' for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: print os.path.join(dirpath, filename) This doesn't answer the question, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqGrid - How to set custom editoptions based on *initial* column values? I am using the open source jqGrid plugin with EF4 and ASP.NET Web Forms. I need to set an input element in an inline-editable grid row based on a column value from the DB. For example, the first row could contain a DDL, the second row could contain a checkbox, etc. I'm trying to achieve this using the custom_element and custom_values, like so: $("#grid1").jqGrid({ url: 'Default.aspx/getGridData', datatype: 'json', ... colModel: [ ... //contains the input type ('select', etc.) { name: 'InputType', hidden:true }, ... //may contain a string of select options ('<option>Option1</option>'...) { name: 'Input', editable:true, edittype:'custom', editoptions:{ custom_element: /* want cell value from InputType column here */ , custom_value: /* want cell value from Input column here */ } }, ... ] }); The jqGrid docs say that I can call custom functions to set custom_element and custom_values, but I don't see how I can capture column values and pass them into my custom functions. For setting custom_values, I did notice Oleg's nice solution using the list: parameter, but that appeared to involve an extra Ajax call. I want to avoid this, as I already have the all data I need from the initial Ajax call for the grid. In summary, I need to do the following while in inline-edit mode: * *dynamically assign an input type from a DB value *dynamically assign input values (for DDL or checkboxes) from a DB string I am also open to skipping the use of custom_element and custom_values, but then I still face the same problem of dynamically setting the edittype and editoptions:{value:} parameters. Any ideas on how to do this? Is there a different approach that I should be taking? UPDATE: Thanks for your efforts to help me out. Per request, here is an abbreviated example of my JSON response: {"d":[ {"Input":null,"InputType":"select"}, {"Input":"From downtown, proceed west on Interstate 70.", "InputType":"text"} ]} With this data, I would want to show an empty select in one row, and a populated text field in the next row. Both would be editable inline. SOLUTION: I have returned to this problem in order to find a solution that does not involve using custom_element and custom_values. Here is my solution (based on the accepted answer below) to changing edittype and editoptions : loadComplete: function () { var rowIds = $("#grid1").jqGrid('getDataIDs'); $.each(rowIds, function (i, row) { var rowData = $("#grid1").getRowData(row); if (rowData.InputType == 'select') { $("#grid1").jqGrid('restoreRow', row); var cm = $("#grid1").jqGrid('getColProp', 'Input'); cm.edittype = 'select'; cm.editoptions = { value: "1:A; 2:B; 3:C" }; $("#grid1").jqGrid('editRow', row); cm.edittype = 'text'; cm.editoptions = null; } }); } Nota Bene: One important thing for me was remembering to set the editoptions back to null, after calling editrow. Also, as Oleg mentioned in the comments, avoiding the use of custom elements allows me to implement datepicker inputs without extra trouble. This was important for my app, so I ended up accepting Oleg's answer, but I still upvoted Walter's answer, as well. If this is bad form, I sincerely apologize. I simply wanted to reward the solution that worked best for me. A: If you use incline editing you call editRow method somewhere directly in your code. Inside of the editRow method all options from the colModel, which are related to editing, will be examined and use. So you can change dynamically any options like editable, edittype or editoptions. The answer shows how one can change editable property. In the same way you can change any other properties. If you want you can set the information about editing type and option inside of loadComplete event handle. It has data parameter which represent the original data sent from the server. So you can extend the data with and other information and set editable, edittype or editoptions for any columns based on the information. A: Try this: 1. Define a handler for the grid's onSelectRow event (onSelectRow_handler) . 2. Inside the onSelectRow handler: 2.1. Set a globally scoped variable (lastRow) to the function's id parameter. 2.2. Call jqGrid's editRow() function to put the grid into edit-mode. This will trigger the function that you have defined as your custom_element renderer (myelem). 3. Inside myelem: call jqGrid's getRowData method to get the row data of the row you just selected for edit. From there you can get the value in the ElementType column and do your logic that decides which element to render. You'll have to tweak my code a bit, as I didn't test it 100% end-to-end. I did verify that everything up to step 3 works. I didn't do any research into how you would code myvalue(). function renderGrid () { $("#grid").jqGrid({ datatype: "local", colNames: ['Id', 'ElementType', 'Name' ], colModel: [ { name: 'Id', index: 'Id', key: true, hidden: true }, { name: 'ElementType', index: 'ElementType', }, { name: 'FullName', index: 'FullName', editable: true, edittype: 'custom', editoptions: { custom_element: myelem, custom_value: myvalue} }], viewrecords: true, caption: "", autowidth: true, height: 'auto', forceFit: true , onSelectRow: onSelectRow_handler }); } var lastRow = null; function onSelectRow_handler(id) { if(id && id!==lastRow){ lastRow=id; } // editRow will send grid into edit mode which will trigger $("#grid").editRow(id, true); } function myelem(value, options) { var data = $("#grid").getRowData(lastRow); // the elementType column contains a key to // indicate what Input Element to render var elementType = data.ElementType; if (elementType == 'text') { var el = document.createElement("input"); el.type = "text"; el.value = value; } if (elementType == 'checkbox') { // etc } return el; } function myvalue(elem, operation, value) { if (operation === 'get') { return $(elem).find("input").val(); } else if (operation === 'set') { $('input', elem).val(value); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jQuery slider - change amount of next / last image shown I'm using the Nivo slider (http://nivo.dev7studios.com) which works perfectly fine for showing one image, but I'm trying to show half of the previous image and half of the next image. I'm open to using others like Slides or the Coin one. Does anyone have ANY idea how to go about this? The closest functionality I've found is this: http://webdesignandsuch.com/posts/fancymoves/index.html but, it's a bit flaky and not the best to work with. I've tried modifying the CSS to lower the size of each panel as well as adjust the positioning via absolute positioning, but I'm having no luck. It's been two weeks I've been working on this. Somebody, please, help! A: MovingBoxes is similar to the other plugin you posted. You can set the panelWidth variable to adjust the width (percent of total width) of the center panel. Or jCarouselLite can show fractions of panels (click on "Fraction Configuration"). A: you can try this. http://www.paulwelsh.info/jquery-plugins/hero-carousel/ The width of the div can be adjusted to your resolution. Hope it helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: die() but only within the tags? If I have code such as: <html> ... <?php .... die(); ?> .... </html> then the entire page execution stops, and the final html does not get shown. is there a way to only leave the php within the enclosing php tags? A: I guess this is based on same condition, otherwise it wouldn't make sense. <html> ... <?php .... if (! condition) { //skip if not needed ... } ?> .... </html> A: Don't ever call die() inside an HTML script. If you are calling die() as part of mysql_query() error checking, for example, you should instead wrap the call in an if() statement. This doesn't only apply to MySQL, of course. You can use this in place of any instance where you would call die(). // Instead of this... $result = mysql_query() or die(); // Do this... $result = mysql_query(...); if (!$result) { $errorstring = "an error occurred producing your data"; } It is generally considered bad practice to include a lot of application logic within the HTML. Instead do these things at the top of the script and store the output in variables for reuse later. A: You can't die() and expect execution will continue. That is illogical and impossible A: what you should do is have an external php script and iframe it into the page, or use jquery to ajax it in. Then if it dies nothing will be displayed in the iframe, or div (if you use jquery), but you can still die
{ "language": "en", "url": "https://stackoverflow.com/questions/7535949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android WebView save Picture I have an application which loads pictures from the Web with WebView and a link. // (in fact an Ajax app with PHP and JavaSCript xmlHttpREquest in a webpage on the Web) So briefly there are images displayed in a WebView in this android app, a simple app. I would like the user to be able to save any images displayed in the WebView to his device with a long click for example, opening a menu or so as in example: in the browser of android it's happening a longclick to save. Many thanks Regards, Rick ref: http://developer.android.com/reference/android/webkit/WebView.html code: package com.example.WebView; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class WebViewActivity extends Activity { /** Called when the activity is first created. */ WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("http://www.example/form.php"); // display some images } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: File protection on remote server Here's the situation. I have a primary web server that needs to be able to access files on a remote web server with PHP. I also have a remote server. The files on the remote server are private. That is, I only want to access them through my PHP script on the primary server. How do I only allow access to a directory of files from the primary server, but deny access to anyone else? A: In your .htaccess file: AuthName "Protected" AuthType Basic <Limit GET POST> order deny,allow deny from all allow from YOUR.SERVER.IP.ADDRESS </Limit> That's how I'd do it. Place that in the .htaccess file in the directory you are trying to protect. Only requests which come from YOUR.SERVER.IP.ADDRESS (obviously change that to your server IP) will be allowed, everyone else gets a 403 error. Given your comments, then you'd want to do it some way with access tokens or something. The way I'd set it up would be to make a PHP script on the remote file server which will serve the files if an access token is matched, and you could just fetch the file with cURL then. If the access token is not matched, set the 403 Forbidden header. Then, they'd only be able to access the files with your access token. To make the token dynamic so it can't be stolen easily, you could take the MD5 hash of a salt plus a dynamic variable that could be shared between servers, like the day of the month. The more frequently the dynamic variable updates, the more frequently the access token updates and the more secure you'll be. Try to keep what you're using for a salt and the hashing algorithm secret, for the best protection. Basic script you could keep on the file server: if($_GET['access'] != md5('aihdhgsa8gas8gasgsa8asgdds' . $YOUR_UPDATING_VALUE)){ //Improper access hash header('HTTP/1.1 403 Forbidden'); die(); } $files = array('blah.png', 'lol.exe'); $file_to_serve = $_GET['file']; if(!in_array($file_to_serve, $files)){ //File isn't in our array header('HTTP/1.1 403 Forbidden'); die(); }else{ die(file_get_contents($file_to_serve)); //Serve however you need. } And on your main server: $file = file_get_contents('http://example.com/serve.php?file=' . $filename . '&access=' . md5('aihdhgsa8gas8gasgsa8asgdds' . $YOUR_UPDATING_VALUE)); These are very rough examples and you'd need to rework the serving and fetching to your system configuration, but you get the point. $YOUR_UPDATING_VALUE should be something both servers can calculate that updates kinda frequently, I'd advise against microtime because there would be a delay in fetching from the other server and it'd always be false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detecting in PHP? I have a script that checks the source of another page, I'm having my code search for <span class="item-header"> in the source. When it finds it, I wan't to print everything that is in the span, but I am not sure how I would do that in PHP? How do I check when to stop printing everything after the span until it finds </span> Here is my code: if (stristr($source, '<span class="item-header">')){ // What to do here? } Any Ideas? :) A: You could use regex, but people will caution against parsing HTML with regex. I would recommend using DOMDocument to parse the HTML and DOMXPath to query the document tree. Try this: $dom = new DOMDocument(); @$dom->loadHTML($page); $dom_xpath = new DOMXPath($dom); $entries = $dom_xpath->evaluate("//span[@class='item-header']"); foreach ($entries as $entry) { print $entry->nodeValue; } A: You would likely be better off using an actual parser instead of regex-based searches. That way you could grab the node for the span and get the text value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Control a C# application from a Public Webpage Possible Duplicate: Run a Method in a C# Application from a Webpage I would like to host a webpage with Buttons, txtbox, etc and when User Clicks a button, it runs a method on the C# application. Also the App can gather the Data from the webpage's txtbox. The Application is located on the user computer. It needs to send and receive Information from the Host. (My Web Host) I have full access to the server. It basically just needs to send and receive simple bools, strings, ints... and for the Website (accessible from anywhere, Mobile phone for example) to have controls that can run Methods on the Application actually running on the computer. So far, I am able to upload and Download from the server via FTP (The app edits 2 html files, and a .txt file) I appreciate any advice you can give. Thank you A: It sounds like you want to have an .ASPX web page that controls a WinForms (traditional Windows application) - for example, the user clicks 'Close' and your WinForm app would close (just an example). To do that you would need to run some sort of inter-process communication, of which there are a number of choices. Prior to .Net 3.0 you would typically use .Net Remoting which has been replaced by Windows Communication Foundation (WCF) as of .Net 3.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with Like Box not pulling current data I have been using Like Box to show our company Facebook feeds on our company portal. The feeds stopped updating on March 24 but we have more current post. Everything seems to be working but current feeds stopped? Did something change with Like Box? Below the “Old Code” is what I have been using, below that is what I got from the “Get Code” today which has the same result… seem to work but no current post. Old Code: <iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2FPowerTradingRadio&amp;width=292&amp;colorscheme=light&amp;show_faces=false&amp;stream=true&amp;header=true&amp;height=427" frameborder="0" scrolling="no" allowtransparency="true" style="border: currentColor; width: 292px; height: 427px; overflow: hidden;"></iframe> New Like Box Code: <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like-box" data-href="http://www.facebook.com/PowerTradingRadio" data-width="292" data-show-faces="false" data-stream="true" data-header="false"></div> A: There are no posts made from the Online Trading Academy (PowerTradingRadio) account after March 24th. All the other posts on the wall are made by individuals and are not shown in the public like box. If you are the owner of the page, you can go to the group page, edit page, click on your settings, and click on 'always comment or post on your page as PowerTradingRadio' or in the top right change your account to use PowerTradingRadio before posting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Php: array function with fopen/fread I'm new to php so please bear with me here. Its a rough example but lets say I have a file (which obviously does't work :), say 1.php, there I have <?php function links1($l1, $l2){echo "<a href='". $l1 ."'><img src='". $l2 ."'/></a>";} $ext_file = '2.php'; $v1 = fopen($ext_file, 'r'); $data = fread($v1, filesize($ext_file)); //i assume some piece of code has to go here?? Or maybe i need a new approach ... ?> where I'm trying to basically read 2.php where I have links1("gg1", "1.jpg"); links1("gg2", "2.jpg"); etc... so that when I open 1.php I would see 1.jpg 2.jpg etc etc... How to do that? And if its possible, how should I modify the code that I could only put gg1 1.jpg gg2 2.jpg gg3 3.jpg gg4 4.jpg .... and it would still work? Thank you guys for help! A: You can simply include 2.php inside 1.php. <?php function links1($l1, $l2){echo "<a href='". $l1 ."'><img src='". $l2 ."'/></a>";} include "2.php"; ?> 2.php should look like: <?php links1("gg1", "1.jpg"); links1("gg2", "2.jpg"); There are 4 different types of include: * *include - include a file, don't error if the file exists (but it does throw a warning). *require - include a file, throw an error if the file does not exist. *include_once - include a file only if it has not been previously included. *require_once - include a file only if it has not been previously required. A: It is possible... $data = file_get_contents('2.php'); $data = explode("\n", $data); foreach($data as $string){ list($l1, $l2) = explode(' ', $string); links1($l1, $l2); } If your line end of line is set to Windows and not UNIX they use "\r\n"...
{ "language": "en", "url": "https://stackoverflow.com/questions/7535975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reusing a jQuery function without causing an error on pages that do not utilize it I use this function to make a help box stay visible when a user scrolls down: var top = $('.help-box').offset().top - parseFloat($('.help-box').css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { var y = $(this).scrollTop(); if (y >= top) { $('.help-box').addClass('fixed'); } else { $('.help-box').removeClass('fixed'); } }); I want to reuse it across several pages, so I included it in my layout (on every page load). The problem now is that I get an error on pages that do not have the help box: $(".help-box").offset() is null Is there a way to write this function so it can be reused without causing an error? I want to avoid selectively including where it's need it as it's easier to just leave the include in my layout. A: var helpBox = $(".help-box"), top; if(helpBox !== null && helpbox != undefined && helpBox.length > 0) { top = helpBox.offset(); } Just check whether you have a helpbox before calling the function. A: Put everything in try-catch block: try { var top = $('.help-box').offset().top - parseFloat($('.help-box').css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { var y = $(this).scrollTop(); if (y >= top) { $('.help-box').addClass('fixed'); } else { $('.help-box').removeClass('fixed'); } }); } catch(err) { } A: var helpBox = $('.help-box'); function initHelpBox(){ var top = helpBox.offset().top - parseFloat(helpBox.css('marginTop').replace(/auto/, 0)); $(window).scroll(function (event) { var y = $(this).scrollTop(); if (y >= top) { helpBox.addClass('fixed'); } else { helpBox.removeClass('fixed'); } }); } if (helpBox.length){initHelpBox()}
{ "language": "en", "url": "https://stackoverflow.com/questions/7535977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CakePHP 2: Html Helper in Email Template I'm having a tough time trying to figure out why I can't use $this->Html->url in the templates for my emails for CakePHP 2.0. The Helpers array is empty in the views. Is this by design or am I missing something? The docs and migration guide don't mention anything around this. The trace looks like: include - APP/View/Emails/html/admin/users_recover.ctp, line 1 View::_render() - CORE/Cake/View/View.php, line 598 View::render() - CORE/Cake/View/View.php, line 365 CakeEmail::_render() - CORE/Cake/Network/Email/CakeEmail.php, line 1300 CakeEmail::send() - CORE/Cake/Network/Email/CakeEmail.php, line 933 UsersController::_sendRecoverEmail() - APP/Controller/UsersController.php, line 186 UsersController::admin_login() - APP/Controller/UsersController.php, line 101 ReflectionMethod::invokeArgs() - [internal], line ?? Controller::invokeAction() - CORE/Cake/Controller/Controller.php, line 476 Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 106 Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 88 [main] - APP/webroot/index.php, line 96 Here is the function that I have sending the recovery email: private function _sendRecoverEmail($email, $recoverKey) { App::uses('CakeEmail', 'Network/Email'); $cakeEmail = new CakeEmail(); $cakeEmail->config('default'); $cakeEmail->to($email); $cakeEmail->subject('Recover Your '. Configure::read('Site.title') . ' Account'); $cakeEmail->template('admin/users_recover'); $cakeEmail->viewVars(array( 'recoverKey' => $recoverKey, )); try { $cakeEmail->send(); } catch (Exception $e) { trigger_error("ERROR in UsersController::sendRecoverEmail: couldn't send email to: {$email}."); return false; } return true; } And finally, the view: <p>Have you been having difficulty getting into your <?php echo Configure::read('Site.title'); ?> account?</p> <?php $url = $this->Html->url(array('action' => 'recover', 'controller' => 'users', $recoveryKey), true); ?> <p>If this is correct, <a href="<?php echo $url; ?>">click here to recover your access and create a new password.</a></p> <p>Your password will remain the same if you ignore it.</p> A: Have you tried setting CakeEmail renderer helpers before calling send()? $cakeEmail->helpers('Html') Bit more info at http://api20.cakephp.org/file/Cake/Network/Email/CakeEmail.php#method-CakeEmailhelpers Another (anti-DRY) option could be to load HtmlHelper inside your templates: <?php $htmlHelper = $this->Helpers->load('Html'); $url = $htmlHelper->url(array('action' => 'recover', 'controller' => 'users', $recoveryKey), true); ?> A: A) Make sure to include the relevant helpers in your controller (Html, in this case) B) Use this book reference to check / set the Html helpers manually working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: cannot making movie from UIImage Array with AVAssetWriter on iphone 3G I am working on an iOS app which make a movie using array of UIImages. Everything work well on iphone 3GS, iphone 4, but cannot on iphone 3, I got this in AVAssetWriterInput.h: Video output settings keys are defined in AVVideoSettings.h. Video output settings with keys from are not currently supported. The only values currently supported for AVVideoCodecKey are AVVideoCodecH264 and AVVideoCodecJPEG. AVVideoCodecH264 is not supported on iPhone 3G. Please anyone could help me an idea? A: The error message is pretty clear. You're trying to encode your video as h264, which is not supported on the iPhone 3G or classic, because it requires special encoding hardware. That's also the reason, the camera app on the 3G can't record videos.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to reset par(mfrow) in R I set par(mfrow =c(1,2)) and now everytime I plot it shows splits it into 2 plots. How can I reset this to only show one plot. Thanks so much. A: You can reset the plot by doing this: dev.off() A: You can reset the mfrow parameter par(mfrow=c(1,1))
{ "language": "en", "url": "https://stackoverflow.com/questions/7535982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "75" }
Q: Indesign Scripting: If selected object is rectangle I'm trying to rewrite the CornerEffects.jsx script in Indesign CS5.5 to make it more user friendly in school, so people know exactly where the first point is and where the last point is etc. The Script has to work in CS3 as well. I need to the options to change only when a rectangle is the selected object and otherwise fallback to the default. I've tried to the following snippet but it just falls back to the default anyway. Thanks, guys. function myDisplayDialog(myObjectList){ if (app.selection.constructor.name == "Rectangle"){ var myStringList = ["all points","first point (top-left)", "last point(top-right)", "second point(bottom-left)", "third point(bottom-right)", "fourth point(top-right)", "first two", "second and third", "last two", "first and last", "odd points", "even points"] } else{ var myStringList = ["all points","first point", "last point", "second point", "third point", "fourth point", "first two", "second and third", "last two", "first and last", "odd points", "even points"] } A: Just looking at it, you would typically use 'selection[0].constructor' rather than 'selection.constructor' but it's hard to say if it will work with this fix. You should be able to step through the code in ExtendScript Toolkit to see where it goes wrong. It might be helpful to break it up into steps to be able to see the values easier. Just out of curiosity, what school is teaching InDesign scripting?
{ "language": "en", "url": "https://stackoverflow.com/questions/7535988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }