text
stringlengths
8
267k
meta
dict
Q: UITableView and CoreDate "Invalid update: invalid number of rows in section" After returning from another view and Saving I have a UITableView that is backed by core data with sections grouped by date. I can delete and add while I'm on the that view just fine. The NSFetchController and the UITableView stay in sync just fine. But then I drill down to an individual object, make changes, save and return. I don't add from the other view, but sometimes delete, most of the the time I'm just making edits to existing records, and none of the edits would cause them to change which section they belonged to. At that point if I try to delete a row I get: Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:974 2011-10-01 14:55:42.691 Lotus Bud[8073:fa03] Serious application error. An exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted). with userInfo (null) What do I need to do to get them back in sync after saving from another view. A: I would suggest listening for the NSManagedObjectContextDidSaveNotification and breaking in the debugger when it is fired. Then you can see what section is being deleted and hopefully backtrace to the source of the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I access windows items(?) from inside a VB.net program I am not really sure how to ask this question. I have been teaching myself vb for about 3 months. The book I am using is pretty good about explaining things and what I can't figure out I can find different examples on the web. I can't find out how to access windows control panels from my app. For example if I type firewall.cpl at the run line it will launch the windows firewall. How do I launch that from my app. A: You can use Process.Start to execute other programs. System.Diagnostics.Process.Start("path to\firewall.cpl")
{ "language": "en", "url": "https://stackoverflow.com/questions/7622337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.net simulate browser back button I'm working on my ASP.NET web project using VS2010, C#, I'm inserting a hyperlink in my page, labeled as BACK, and I want it to act like browser back button, how should I implement it? what is the easiest way? how should I set its navigateURL property? thanks A: <asp:button id="backButton" runat="server" text="Back" OnClientClick="JavaScript:window.history.back(1);return false;"></asp:button> Except that's a button, of course :-( (read the question, Steve) Try navigateurl="javascript:history.go(-1);" A: You don't need ASP.NET, just use this HTML/JScript code: <a href="javascript:history.go(-1)">Back</a> A: @Steve Not sure how to comment on an existing answer but... I figured that I could just for kicks say that you could always make the "button" a "linkbutton": A: If you are using JQuery, you can simply add data-rel="back" to your anchor-tag <a data-rel="back" data-role="button" data-icon="back">Back</a> A: Try this.. private void btnBack_Click(object sender, System.EventArgs e) { string prevPage = Request.UrlReferrer.ToString(); Response.Redirect(prevPage); } or <asp:button id="btnBack" runat="server" text="Back" xmlns:asp="#unknown"> OnClientClick="JavaScript: window.history.back(1); return false;"></asp:button> A: something like this should do <button> @Html.ActionLink("Back", "Index", "Students (your controller name here)", new { id = @Model.Student.Id })</button> ANOTHER WAY <a asp-action="Index" asp-controller="Students" asp-route-studentId="@Model.StduentId" class="btn btn-sm btn-success">Back to List</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7622339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What languages I will need in order to write browser plugin that will work with GMAIL? Possible Duplicate: C# plugin for Google Chrome What language(s) are programs like ActiveInbox written in? I need to write browser plugin, mainly to chrome. This plugin will work with GMAIL. It will track incoming mails and do some actions(put label, delete mail...). - similar what gmail already does by filter option. My question is: what languages I will need to do this, only JavaScript? P.S. I've already asked similar question, but it was closed. I hope this time I explained exactly what I need. Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7622349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why do I continue to receive PHP Deprecated errors despite this ini setting? I've set my error_reporting to error_reporting = E_ALL & ~E_DEPRECATED ^ E_STRICT in php.ini. The numerical value according to phpinfo() is 22527. However we are still logging plenty of [01-Oct-2011 13:06:36] PHP Deprecated: Assigning the return value of new by reference is deprecated in /htdocs/www/site/core.php on line 2381 [01-Oct-2011 13:06:36] PHP Deprecated: Function set_magic_quotes_runtime() is deprecated in /htdocs/www/site/core.php on line 1538 I've seen a few other questions about this, but not with any solutions I haven't tried. We're using (an outdated version of) VBulletin. Could that be changing the setting? I see now that VBulletin's forumdisplay.php has a line error_reporting(E_ALL & ~E_NOTICE); Commenting this out didn't change anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Symfony 2 hidden form field text This is probably really stupid but I am trying to set a hidden form field value in symfony yet when I do a view source, the value doesnt show up. this->postID refers to a value I am passing in through the constructor, but that doesnt matter, even if I set the data value to a string it doesn't show. I must be doing something really stupid.. Here is my form.. public function buildForm(FormBuilder $builder, array $options) { $builder->add('text','text'); $builder->add('IsshPost','hidden', array('data'=>$this->postID)); } any idea whats wrong? A: I figured it out.. thanks! basically you have to detach the field from the entity by passing an extra field "property_path => false" A: In Symfony 2.1, the "data" option is fixed in that regard. The code in question should work out of the box there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Saving a large text chunk in a mysql table I'm building a music site. It has a lot of artists and tracks stored. I'm planning to retrieve artist information from Wikipedia and store it on my server - somehow. Would i want to save this as static files? In the artists table? In a separate table so it wont be loaded everytime i load a track, for example? Selecting only certain columns is too much work at the moment, due to the amount of querys on the site, but i will look into that later. Promise. A: I would store the text as a text object in your db. Since it's an attribute of the artist, store it as such. If you don't need it for some queries, don't select it - I know you say this is too much work - it isn't, it's easy. If you store it in a separate table, you will be making a join when you query and that is probably unnecessary. If it was a video file, I would suggest storing it outside the db, but relatively speaking a large text object is nothing. A: you should store it in another table, keep your tables small. you wont need any join statement to get to the data when you want it, you can do it like this: SELECT wiki FROM bios as b, artists as a WHERE a.ID=b.ID
{ "language": "en", "url": "https://stackoverflow.com/questions/7622364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery and ajax async post back Hi I am using jquery to have the sliding effect, kwicks effect, slideup and fancybox in a single page. everyhting works perfectly until the ajax postback but after that none of the jquery functions seems to work. any ideas will be great A: It looks as though your UpdatePanel is breaking your javascript. The key is to remember when it does a postback these are not the same elements that your javascript was originally tied to. Rebinding after the postback will fix your problem; all this requires is tying some javascript calls to a Microsoft provided call back function: function BindEvents() { //Here your jQuery function calls go } var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(BindEvents); The PageRequestManager will call the BindEvents function after each post back. This can go any where on the page as long as it is there prior to the postback.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Ruby: Extracting Words From String I'm trying to parse words out of a string and put them into an array. I've tried the following thing: @string1 = "oriented design, decomposition, encapsulation, and testing. Uses " puts @string1.scan(/\s([^\,\.\s]*)/) It seems to do the trick, but it's a bit shaky (I should include more special characters for example). Is there a better way to do so in ruby? Optional: I have a cs course description. I intend to extract all the words out of it and place them in a string array, remove the most common word in the English language from the array produced, and then use the rest of the words as tags that users can use to search for cs courses. A: The split command. words = @string1.split(/\W+/) will split the string into an array based on a regular expression. \W means any "non-word" character and the "+" means to combine multiple delimiters. A: For me the best to spliting sentences is: line.split(/[^[[:word:]]]+/) Even with multilingual words and punctuation marks work perfectly: line = 'English words, Polski Żurek!!! crème fraîche...' line.split(/[^[[:word:]]]+/) => ["English", "words", "Polski", "Żurek", "crème", "fraîche"] A: Well, you could split the string on spaces if that's your delimiter of interest @string1.split(' ') Or split on word boundaries \W # Any non-word character \b # Any word boundary character Or on non-words \s # Any whitespace character Hint: try testing each of these on http://rubular.com And note that ruby 1.9 has some differences from 1.8 A: For Rails you can use something like this: @string1.split(/\s/).delete_if(&:blank?) A: I would write something like this: @string .split(/,+|\s+/) # any ',' or any whitespace characters(space, tab, newline) .reject(&:empty?) .map { |w| w.gsub(/\W+$|^\W+^*/, '') } # \W+$ => any trailing punctuation; ^\W+^* => any leading punctuation irb(main):047:0> @string1 = "oriented design, 'with', !!qwe, and testing. can't rubyisgood#)(*#%)(*, and,rails,is,good" => "oriented design, 'with', !!qwe, and testing. can't rubyisgood#)(*#%)(*, and,rails,is,good" irb(main):048:0> @string1.split(/,+|\s+/).reject(&:empty?).map { |w| w.gsub(/\W+$|^\W+^*/, '')} => ["oriented", "design", "with", "qwe", "and", "testing", "can't", "rubyisgood", "and", "rails", "is", "good"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7622369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: getrusage vs. clock_gettime() I am trying to obtain the CPU time consumed by a process on Ubuntu. As far as I know, there are two functions can do this job: getrusage() and clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp). In my code, calling getrusage() immediately after clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp), always gives different results. Can anyone please help me understand which function gives higher resolution, and what advantages/disadvantages of these functions have? Thanks. A: getrusage(...) * *Splits CPU time into system and user components in ru_utime and ru_stime respectively. *Roughly microsecond resolution: struct timeval has the field tv_usec, but this resolution is usually limited to about 4ms/250Hz (source) *Available on SVr4, 4.3BSD, POSIX.1-2001: this means it is available on both Linux and OS X See the man page clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) * *Combined total of system and user time with no way to separate it into system/user time components. *Nanosecond resolution: struct timespec is a clone of struct timeval but with tv_nsec instead of tv_usec. Exact resolution depends on how the timer is implemented on given system, and can be queried with clock_getres. *Requires you to link to librt *Clock may not be available. In this case, clock_gettime will return -1 and set errno to EINVAL, so it's a good idea to provide a getrusage fallback. (source) *Available on SUSv2 and POSIX.1-2001: this means it is available on Linux, but not OS X. See the man page
{ "language": "en", "url": "https://stackoverflow.com/questions/7622371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Random circles being detected I'm trying to detect circles but I am detecting circles that aren't even there. My code is below. Anyone know how to modify the DetectCircle() method to make the detection more accurate , please and thanks void detectCircle( IplImage * img ) { int edge_thresh = 1; IplImage *gray = cvCreateImage( cvSize(img->width,img->height), 8, 1); IplImage *edge = cvCreateImage( cvSize(img->width,img->height), 8, 1); cvCvtColor(img, gray, CV_BGR2GRAY); gray->origin = 1; // color threshold cvThreshold(gray,gray,100,255,CV_THRESH_BINARY); // smooths out image cvSmooth(gray, gray, CV_GAUSSIAN, 11, 11); // get edges cvCanny(gray, edge, (float)edge_thresh, (float)edge_thresh*3, 5); // detects circle CvSeq* circle = cvHoughCircles(edge, cstorage, CV_HOUGH_GRADIENT, 1, edge->height/50, 5, 35); // draws circle and its centerpoint float* p = (float*)cvGetSeqElem( circle, 0 ); if( p==null ){ return;} cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 3, CV_RGB(255,0,0), -1, 8, 0 ); cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(200,0,0), 1, 8, 0 ); cvShowImage ("Snooker", img ); } A: cvHoughCircles detects circles that arent obvious to us. If you know the pixel size of snooker balls you can filter them based on their radius. Try setting the min_radius and max_radius parameters in your cvHoughCircles function. On a side note, once you get the circles, you can filter them based on color. If the circle is mostly one color, it has a good chance of being a ball, if it doenst its probably a false positive. edit: by "circle's color" i mean the pixels inside the circle boundary
{ "language": "en", "url": "https://stackoverflow.com/questions/7622374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fatal error starting debugging kernel every other deployment on Mac I'm writing a FireMonkey HD application on my Windows 32 bits machine, and deploying (remote debugging) it on my MacBook running Snow Leopard. I'm running the Delphi XE2 Trial. Everything is working fine, except for one thing: every other run I hit the following error when I press F9: Fatal error starting debugging kernel: "Invalid debugger request". Please save your work and restart Delphi XE2. Restarting XE2 and running again cures this problem... for exactly one run, then I hit the same error again. Whether I stop the debugging run through CTRL-F2, or gracefully close the application on the Mac, makes no difference. It happens on every project (including new, empty ones with only a single FireMonkey form).The PAServer terminal has no information, it's still on "listen". Anyone has any tips on how to avoid this issue? A: Installing the full version of Delphi XE2 (including update 1) seems to have fully solved my problem. I've checked the Bug Fix list for any references, but no such luck. Oh well, problem is gone anyway. [EDIT] And now, the very next day, the problem re-appears. A: Delphi 10 gives a similar adventure (Win32 --> Win32 target). It's "business as usual" for the remote debugger.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Session data not persisting in GAE (Java) I am struggling while handling sessions in GAE. I am trying to store a two classes and a string in session. Although on DEV environment it runs fine, on production a class and a string are not being persisted in session. The class that is not getting saved as a session attribute is as follows: @PersistenceCapable(detachable="true") public class Agent implements Serializable{ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String name; //Name of the Agency @Element(dependent = "true") private List<Contact> contacts = new ArrayList<Contact>(); @Element(dependent = "true") private List<Agency> agencies = new ArrayList<Agency>(); @Persistent private List<Long> subAgents = new ArrayList<Long>(); @Persistent private Date createdOn = new Date(); } I would like to mention again that it works fine on DEV Environment but on production I get values as null. As you can see I have made the class implement Serializable. But I think it is not the problem because I am setting one more attribute as a simple string and that also is failing (I get the attribute value as null). Session however is created as I can see it at the backend and also there is one more class which is persisted in session. Anybody have suggestions? Thanks in advance. A: Your problem is probably related to either: * *GAE often serializes sessions almost immediately, dev environment doesn't. So all objects in your graph must implement Serializable. *BUT EVEN MORE LIKELY is that after you modify a session variable, you must do something like req.getSession().setAttribute(myKey,myObj) - it WILL NOT see changes in your object and automatically write them back to the session... so the session attributes will have the value of whatever they had when they were last set. Problem #2 above cost me countless time and pain until I tripped over (via a lengthy process of elimination). A: Have you enabled sessions in your configuration file? http://code.google.com/intl/en/appengine/docs/java/config/appconfig.html#Enabling_Sessions A: Making classes Agency and Contact Serializable solves the problem. That mean each and every object (be it nested or otherwise) which is present inside a session attribute should be serializable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nodejs modules and duplication? If an app uses two modules that require a common module, does node optimize to prevent loading the same code twice? Apologies if this is a dumb question, but if I create 2 modules that both require('http') and my main application that requires both modules, or requires modules that in turn require both modules, while also requiring 'http' for its own purposes, do I end up with three instances of the http module, each locked within the scope of a different closure, or does node rewrite things to avoid this? In other words, do I end up with an app that has: // main app creates a closure containing a local instance of http, an instance of proxy1 // and an instance of proxy2, both of which are functions returned from closures that have instances of http in scope var http = require('http'), httpProxy1 = require('./proxy1'), httpProxy2 = require('./proxy2'); /* ... do stuff with http, using proxy1 or proxy2 where appropriate ... */ // proxy1 creates a closure containing a local instance of http and exposes a single public method var http = require('http'); module.exports = function (foo) { /* ... do stuff with http ... */ } // proxy2 creates a closure containing a local instance of http and exposes a single public method var http = require('http'); module.exports = function (foo) { /* ... do stuff with http that has nothing to do with the stuff proxy1 does ... */ } If I also want to use proxy1 independently, it makes sense to have it as a module, but on even a small project, this could lead to many modules that all require core modules repeatedly, especially http and fs A: Read up on how Node.js' module loading caches modules. In your example, the 'http' instance will be the same across all your modules. But be aware that modules are cached based on resolved filename. When requiring a built-in module like 'http' you can be reasonably sure you're getting the same module object across all your code. But 3rd party packages don't necessarily behave this way. For example, if you require 'express' and 'mime', the 'mime' module object you get will, I believe, be different from the one that's used inside of express. The reason being that express ships with it's own set of module files in it's node_modules subdirectory, while you will have installed and loaded your own copy, probably in your your_project/node_modules somewhere
{ "language": "en", "url": "https://stackoverflow.com/questions/7622385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Directed graph connectivity Given a directed graph G, what is the best way to go about finding a vertex v such that there is a path from v to every other vertex in G? This algorithm should run in linear time. Is there an existing algorithm that solves this? If not, I'd appreciate some insight into how this can be solved in linear time (I can only think of solutions that would certainly not take linear time). A: Make a list L of all vertices. Choose one; call it V. From V, walk the graph, removing points from the list as you go, and keeping a stack of unvisited edges. When you find a loop (some vertex you visit is not on the list), pop one of the edges from the stack and proceed. If the stack is empty, and L is not empty, then choose a new vertex from L, call it V, and proceed as before. When L is finally empty, the V you last chose is an answer. A: This can be done in linear time in the number of edges. * *Find the strongly connected components. *Condense each of the components into a single node. *Do a topological sort on the condensed graph, The node with the highest rank will have a path to each of the other nodes (if the graph is connected at all). A: I think I've got a correct answer. * *Get the SCC. *Condense each of the components into a single node. *Check whether every pair of adjacent nodes is reachable. This is a sufficient and necessary condition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Do the contextual rules for 'type' selectors also apply for 'class' & 'id' selectors in CSS? I am new to CSS and facing an issue related to contextual selectors as following: Q1) What is the effect of creating selectors in the following way: .test1 .test2{ background:red; } Here test1 and test2 are the class selectors. I understand that when we use such structure with 'type' selectors then that leads to styling of descendants. Is this the same thing for the class selectors? Q2) If yes, then will all the contextual rules (+, >) etc.. for the 'type' selector will also apply for class selectors? Q3) And will all these rules also be then applicable to the 'id' selectors? I have seen the use of such structure in the css files of js libraries like ExtJS .x-border-box .x-reset *{box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;-webkit-box-sizing:border-box} But I have not been able to locate the exact implication of this structure. Could any guide at this. Thanks for any help in advance. A: Yes, they work the same. They're all simple selectors. A: * *Yes, it is the same thing for class selectors. *Yes, the contextual rules that apply to type selectors will also apply to class selectors. *Yes, they will also be applicable to id selectors. I have seen the use of such structure in the css files of js libraries like ExtJS .x-border-box .x-reset *{box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;-webkit-box-sizing:border-box} But I have not been able to locate the exact implication of this structure. It means, apply that rule to all child elements of the element with the class x-reset, whose immediate or any further parent has the class x-border-box. A: Q1) What is the effect of creating selectors in the following way: .test1 .test2{ background:red; } This will change the background-color of an element with the class of test2 that is nested within the class of test1. So yes. Q2) If yes, then will all the contextual rules (+, >) etc.. for the 'type' selector will also apply for class selectors? Yes, they apply. But there are slight differences. For instance, the above rule is close to the same as .test1 > .test2. This targets the direct child of .test1, whereas the first rule (with just the classes) would target any .test2 descendent of a .test1, no matter who nested. Q3) And will all these rules also be then applicable to the 'id' selectors? Yes, id and class work the same way, expect that id targets a specific, unique element and class can be applied to multiple elements. A: You can just mix and match. So something like this: #header h1.main a Means; any a-element, that is a descendant of a h1 element with a classname that is 'main', that again is a descendant of any element with a ID 'header'. Note that you could just replace #header with *#header (although I would not do that)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java ObjectInputStream hanging I am feeling really stupid right now guys.... basically I am connecting over TCP on a local machine... and when I try to make the In/out streams at the client it wont get passed creating the object input stream. What gives? This stops after printing 2... no exceptions or anything... This isn't the first time I've used this class which is partialy why I am puzzled. try { System.out.println("1"); mySocket = new Socket("localhost", 11311); System.out.println("12"); oos = new ObjectOutputStream(mySocket.getOutputStream()); System.out.println("2"); ois = new ObjectInputStream(mySocket.getInputStream()); System.out.println("13"); } catch (Exception e) { e.printStackTrace(); } A: From the specification of ObjectInputStream: This constructor will block until the corresponding ObjectOutputStream has written and flushed the header. A: (For future readers:) I had the same problem because i made a silly change in server program and didn't test it for a long time then i was confused about why program is locked. ServerSocket accepts the connection (responderSocket = serverSock.accept();) then suddenly for a inapropriate if (The silly change i mentioned!) program jumps out of the thread and because i didn't add a finally block to close streams and sockets the socket was left abandoned w/o sending or recieving anything (even stream headers). So in client side program there was no stream header (When i debbugged The code i saw that the last function executed before lock was: public ObjectInputStream(InputStream in) throws IOException { verifySubclass(); bin = new BlockDataInputStream(in); handles = new HandleTable(10); vlist = new ValidationList(); enableOverride = false; readStreamHeader(); //// <== This function bin.setBlockDataMode(true); } readStreamHeader();) So be careful about what happens in server side, maybe problem isn't where you expecting it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Java JPanel Paint Scaling Following code work for visualizing a molecule on a JPanel except it does not rescale when I change the size of JPanel at runtime. The Chemistry Development Kit is used for generating rendered Image. A molecule is passed to MoleculeViewer for visualizing. What am I doing wrong?? A: What am I doing wrong?? * *why you needed to setSize(new java.awt.Dimension(400, 400)); *put your image = new BufferedImage(this.WIDTH, this.HEIGHT, BufferedImage.TYPE_INT_RGB); as Icon to the JLabel, then you can remove anything about paintComponent() *then you can return JLabel instead of JPanel, but JLabel is translucent by default, or put JLabel to the JPanel by using proper LayoutManager in this case BorderLayout.CENTER *you have to check how way you added MoleculeViewer, what LayoutManager is there used???, because only usage of LayoutManager can this job correctly to resize (or not resize) Container's childs with Top-Level Container, *MoleculeViewer must retuns PreferredSize for its parent A: Adding following resolved the not redrawing upon scaling problem renderer.paint(molecule_, new AWTDrawVisitor(g2), new Rectangle2D.Double(0, 0, w, h), false); g2.dispose(); } else
{ "language": "en", "url": "https://stackoverflow.com/questions/7622402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: use base64 image with Carrierwave I want to perform the similar thing as from base64 photo and paperclip -Rails, but with Carrierwave. Could anybody explain me using of base64 images in Carrierwave? A: class ImageUploader < CarrierWave::Uploader::Base class FilelessIO < StringIO attr_accessor :original_filename attr_accessor :content_type end before :cache, :convert_base64 def convert_base64(file) if file.respond_to?(:original_filename) && file.original_filename.match(/^base64:/) fname = file.original_filename.gsub(/^base64:/, '') ctype = file.content_type decoded = Base64.decode64(file.read) file.file.tempfile.close! decoded = FilelessIO.new(decoded) decoded.original_filename = fname decoded.content_type = ctype file.__send__ :file=, decoded end file end A: The accepted answer did not worked for me (v0.9). It seems to be a check that fails before the cache callback. This implementation works: class ImageUploader < CarrierWave::Uploader::Base # Mimick an UploadedFile. class FilelessIO < StringIO attr_accessor :original_filename attr_accessor :content_type end # Param must be a hash with to 'base64_contents' and 'filename'. def cache!(file) if file.respond_to?(:has_key?) && file.has_key?(:base64_contents) && file.has_key?(:filename) local_file = FilelessIO.new(Base64.decode64(file[:base64_contents])) local_file.original_filename = file[:filename] extension = File.extname(file[:filename])[1..-1] local_file.content_type = Mime::Type.lookup_by_extension(extension).to_s super(local_file) else super(file) end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7622404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Spawned zip process doesn't seem to add file to archive I am trying to add a text file to a zip archive through a Java program on Linux. The program spawns a process (using java.lang.Process) to execute the commandline "zip -j .zip .txt", reads the output and error streams of the spawned process and waits for the process to complete using waitFor(). Though the program seems to run fine (spawned process exits with exit code 0, indicating that the zip commandline was executed successfully) and the output read from output and error streams do not indicate any errors, at the end of the program the zip archive doesn't always contain the file supposed to have been added. This problem doesn't happen consistently though (even with the same existing-archive and file-to-add) - once in a while (perhaps once in 4 attempts) the zip is found to have been updated correctly. Strangely, the problem doesn't occur at all when the program is run through Eclipse debugger mode. Any pointers on why this problem occurs and how it can be addressed would be helpful. Thanks! Below is the code snippet. The program calls addFileToZip(File, File, String): public static void addFileToZip(final File zipFile, final File fileToBeAdded, final String fileNameToBeAddedAs) throws Exception { File tempDir = createTempDir(); File fileToBeAddedAs = new File(tempDir, fileNameToBeAddedAs); try { FileUtils.copyFile(fileToBeAdded, fileToBeAddedAs); addFileToZip(zipFile, fileToBeAddedAs); } finally { deleteFile(fileToBeAddedAs); deleteFile(tempDir); } } public static void addFileToZip(final File zipFile, final File fileToBeAdded) throws Exception { final String[] command = {"zip", "-j", zipFile.getAbsolutePath(), fileToBeAdded.getAbsolutePath()}; ProcessBuilder procBuilder = new ProcessBuilder(command); Process proc = procBuilder.start(); int exitCode = proc.waitFor(); /* * Code to read output/error streams of proc and log/print them */ if (exitCode != 0) { throw new Exception("Unable to add file, error: " + errMsg); } } A: Make sure no other process has the zip file locked for write, or the file being added locked for read. If you're generating the file to be added, make sure the stream is flushed and closed before spawning the zip utility. A: I am trying to add a text file to a zip archive through a Java program on Linux. Use the java.util.zip API, which: Provides classes for reading and writing the standard ZIP and GZIP file formats. If you intend to stick with using a Process to do this, be sure to implement all the suggestions of When Runtime.exec() won't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Protect Jar file source code with exe file (Java) How would I make a .JAR file open up when I make another file as .EXE? I have tried many things, but they don't work. I want this for another way to protect my source code. Kind of like what Minecraft does. You open a .EXE, and somehow the .EXE opens up the .JAR file. Anyone have any ideas? A: To convert to exe, I use JAR2EXE. However obfuscating your code can deter people who want to access your code. But a determined person would still access it. You can use proguard to obfuscate your code.\ ProGuard A: You want something like this: -> http://en.wikipedia.org/wiki/Obfuscated_code You can access the MineCraft.jar but the code is obfuscated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Referential Integrity does not work in N:N relation This is ms create table script: It is a N:M relation between the SchoolclassCode and the Pupil table CREATE TABLE Schoolclasscode ( schoolclassId integer PRIMARY KEY AUTOINCREMENT NOT NULL ); CREATE TABLE SchoolclasscodePupil ( pupilId_FK integer NOT NULL, schoolclassId_FK integer NOT NULL, /* Foreign keys */ FOREIGN KEY (schoolclassId_FK) REFERENCES Schoolclasscode(schoolclassId) ON DELETE CASCADE ON UPDATE NO ACTION, FOREIGN KEY (pupilId_FK) REFERENCES pupil(pupilId) ON DELETE CASCADE ON UPDATE NO ACTION ); CREATE TABLE pupil ( pupilId integer PRIMARY KEY AUTOINCREMENT NOT NULL ); When I delete a SchoolclassCode object in my code: public void DeleteSchoolclass(int schoolclassCodeID, SQLiteConnection con) { using (SQLiteCommand com = new SQLiteCommand(con)) { com.CommandText = "DELETE FROM schoolclasscode WHERE SchoolclassId = @SchoolclassId"; com.Parameters.Add(new SQLiteParameter("@SchoolclassId", schoolclassCodeID)); com.ExecuteNonQuery(); } } The entry in the schoolclasscode table is deleted. But nothing more. I can even additionally delete the schoolclasscodeId_FK in the SchoolclasscodePupil but no pupils were deleted by a cascade delete constraint. What do I wrong? A: In an N:M relation, either N or M may be zero. Referential integrity has not been violated. Deleting a class will deregister all pupils from that class. Similarly deleting a pupil will unroll them from all classes. But deleting a pupil can never cause a cascade to cancel a class, nor can deleting a class expel a pupil. Even if it's the last class the pupil was taking, you're left with a pupil who has zero classes, which is valid under the referential integrity rules.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RML paragraph vertical align? I am working with RML and would like to align my text in the vertical middle of a paragraph. How might I be able to do this? A: Can you use a table ? Like this ? <?xml version="1.0"?> <!DOCTYPE document SYSTEM "rml.dtd" > <document filename="example_08.pdf"> <template showBoundary="0"> <pageTemplate id="main"> <pageGraphics/> <frame id="first" x1="100" y1="400" width="350" height="200" /> </pageTemplate> </template> <stylesheet> <blockTableStyle id="blocktablestyle1"> <blockValign value="MIDDLE" start="0,0" stop="-1,0"/> </blockTableStyle> </stylesheet> <story> <blockTable style="blocktablestyle1" colWidths="6cm,2cm"> <tr> <td> <para> This is your paragraph. It's inside the &lt;para&gt; tags so the long string of text is wrapped! You can set the horizontal space with colWidths attribute on the blockTable. </para> </td> <td>The text valigned on the middle</td> </tr> </blockTable> </story> </document> A: or else you can define like this for eg:: <paraStyle name="terp_header" fontName="Helvetica-Bold" fontSize="15.0" leading="19" alignment="CENTRE" spaceBefore="12.0" spaceAfter="6.0"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7622423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print a voucher with Java and a EPSON TM-T88III I just bought an EPSON TM-T88III. Now I want to write a small application in java that prints a voucher with some plain text, so nothing special. I was wondering how I could do this. So far I figured out that I can print simple documents using the Windows Drivers and Notepad. Do you recommend me to use the JavaPoS? It would be great to get some hints to point me in the right direction. A: I know this is so late, but I'm having a similar issue. I recommend using an existing ESC/POS (the communication protocol) library. This was enough to get me started, I simply did a port for my project (using a TM-T20) https://code.google.com/p/escprinter/source/browse/trunk/net/drayah/matrixprinter/ESCPrinter.java?r=2
{ "language": "en", "url": "https://stackoverflow.com/questions/7622424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Zend_Form submit stops working, when displayed with Display Groups My Zend_Form has only two elements, text and submit. When I render the Form as whole, everything works fine. echo $this->form; When I render the Form part by part, it gets rendered, but the submit button triggers nothing. echo $this->form->range; echo $this->form->submit; Rendering wiht display groups also leaves the submit button dead. Any ideas? Thanks in advance! A: When you echo form object its magic function __toString() gets called which outputs the html generated by default registered decorators . Which includes "" html tag . Which wraps up all the elements added to the zend from . So if you are echoing individual elements you need to manually wrap elements inside html form tag .
{ "language": "en", "url": "https://stackoverflow.com/questions/7622433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting String[] in Java I have String[] inputMsg declared outside a loop and inside a loop I have inputMsg = new String[someSize]; Since the loop can loop lots of times, I find it out that creating new String[someSize] everytime realy wasteful so in the of each iteration of the loop I would like to remove that memory allocation or to delete it's content so the inputMsg will be null. How can it be done in Java? A: Why declare it outside a loop? for (...) { String[] inputMsg = new String[someSize]; ...more code... } The GC will take care of freeing the memory. If the GC turns out to be a bottleneck, and you have the numbers to prove it, then we can talk some more. But, it turns out most GCs are fairly efficient at reclaiming short-lived objects. A: You don't delete objects in Java, you remove the references to them and wait for the garbage collector to collect them. If you have a String[] (ie, an array of String) you can attempt to reuse it (especially if the old and new arrays are the same size), but that the best you're going to do. If you want to be able to add things to an array (change its size) over time you shouldn't use a regular [] type array but should use a Vector or one of the other collection objects. A: You can't delete anything in java by hand. This is automatically done by the garbage collector. It runs from time to time or if more memory is needed. You can't influence it. A: You should be able to force a garbage collect with System.gc() or Runtime.gc(). However, I strongly advise against it. Why do you want the memory freed quickly? Is there a specific reason? A: Have you considered using a LinkedList instead of a String[]?
{ "language": "en", "url": "https://stackoverflow.com/questions/7622434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails button_to to trigger an action in Model directly I would like to allow user to cancel his Event by clicking a button on show page. I have a method cancel in Event model, but don't want to create a method cancel in Controller if I don't have to. My questions are: * *Is it a good idea to invoke a method in the model directly from view in this case? *If it is OK, then how should I do it using button_to? Thank you. A: No, trying to invoke a model method directly isn't a good idea. The Rails routing system routes to controllers so it simply won't work (unless you want to do a lot more work than simply writing a tiny controller). If you call a model method from the view then that method will be executed while the view is being built and that happens before the user sees anything or has a chance to click a button. So you don't want to call your model's cancel method from your view, you want something to call your cancel method when the user performs an action, user actions are routed to controllers and controllers tell models what to do. You probably want a little bit of access control as well and that's generally handled at the controller level. A: * *No, it's not a good idea. *Irrelevant, since it's not a good idea. You can hook the button_to to the update action in the EventsController if the Event model has states or to the destroy action if cancelling the event means removing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a simple way to get li:gt(-1) in jquery? Is there a simple way to get li:gt(-1) in jQuery? Or greater than or equal to zero using jQuery's :gt filter? When the I use the following code, it is not taking li:gt(-1): $('#Input li:gt(-1)').each(function() A: Change your code to start at 0 instead of -1, and do a "greater-than-or-equal-to" selector: $('.someClass:eq('+i+'), .someClass:gt('+i+')') Or, with a little less duplication: $('.someClass').filter(':eq('+i+'), :gt('+i+')') A: What about .slice? Passing one index means anything from that index and up, so add 1 to get gt rather than gte. $('#Input li').slice(1 - l) A: If you want to get all elements at index "greater than or equal to zero" then you just want all the elements, and you don't need the :gt pseudo-selector: $('#Input li').each(function() { //Do whatever }); Update (based on comments) I'm still not exactly sure what you're aiming for, but if you want to know the index of the element referred to by the current iteration, you can use the first argument of each: $('#Input li').each(function(index, elem) { //index is the index of the current element }); A: If I understand the question, I think you just need: $('#Input li').each(function() It will return a jQuery object that is indexed from 0. Therefore every match will be 0 or greater.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: android ddms screen capture vertical size seems fixed at 1024 I can successfully run the DDMS screen capture either via the DDMS.bat file or via eclipse however the screen size in the vertical direction seems fixed at about 1024 pixels. My laptop is a bit small with a screen size of 1366x768. If I attach a VGA monitor running at 1280x1024 then this portrait view just barely fits. I can rotate the view and display within my 1366 landscape view but was hoping there was a way to change the view size. The problem is that I need to make a demo of this with my laptop connected to a projector. The projector will be behind me thus I prefer to duplicate my (smaller) main screen (the 1366x768) onto the projector. A: From within Eclipse: 1.Go to Window -> Android SDK and AVD Manager -> Virtual Devices 2.Select the AVD you want to launch and click Start 3.Check the "Scale display to real size" button 4.Enter how big you want it to appear in inches and press Launch. usually, 8 works great
{ "language": "en", "url": "https://stackoverflow.com/questions/7622441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Prototype object can be changed from instance Could someone explain this to me in a sensible way: function One() {} One.prototype.obj = { key: 'value' }; One.prototype.str = 'string'; var inst1 = new One(), inst2 = new One(); // now let’s change some things in our second instance inst2.obj.key = 'buh!'; inst2.str = 'buh!'; // ok, so what happens to our other instance? console.log( inst1.str ); // Yields 'string' (unaffected, expected) console.log( inst1.obj.key ); // Yields 'buh!' (!!) console.log( One.prototype.obj.key ); // is also 'buh!' It seems that if a prototype contains an object, the instance you create using the new keyword has that object, but if you change it, you also change the prototype object, thus affecting all instances, like a sibling-inheritance-pattern... Is this the way it’s suppose to work? A: Actually, Javascript doesn't copy anything from the prototype. Everything you define on the prototype exists only once (on the prototype itself) and gets reused because the same prototype instance is passed to all objects. When you access a property on an object, the object checks to see if it is defined on itself. If it is, it will return the value associated with that property. If it's not, it will delegate the call to its prototype, who will from now on be responsible for what happens. That's why "inheritance" (code reuse) in Javascript is better called delegation. Things are a bit different for write access. If you set a property on the object, it will "shadow" the value locally. That's the reason why the str property is unaffected, it has actually been defined on the inst2 object. But if you delete inst2.str and do another console.log( inst2.str ) you will notice that it will return the old value. PS: If you want a way to prevent that from happening have a look at this tutorial: http://kevlindev.com/tutorials/javascript/inheritance/index.htm I recommend reading the entire thing, but if you just want the meat see the KevLinDev.extend function in the "Creating a subclass" section. A: In short, yes. Javascript does not implicitly copy objects for you, so when you create the object literal at obj, all instances of the One class simply refer to it via reference. Instead, you need to dynamically create the obj object in the constructor: function One(){ this.obj = {key:'value'}; } See also: javascript multidimensional object
{ "language": "en", "url": "https://stackoverflow.com/questions/7622450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Debug Maven to find out the war file name that has been created I am getting this exception in Maven2 when i run mvn deploy Please see the error [INFO] An Ant BuildException has occured: Warning: Could not find file D:\bayer\service\target\${file.name}.war to copy. I have this below line under my POM.xml file Please tell me is it possible to see the file.name that is forming at runtime ?? I have this line under my POM.xml file <copy file="${project.build.directory}/${file.name}.${project.packaging}" tofile="${deploy.home}/${webapps.dir}/${file.name}.${project.packaging}" /> How can we debug this ?? A: By default maven generated wars will have the following name: ${artifactId}-${version}.war In you antrun plugin you can reference maven properties ( see http://maven.apache.org/plugins/maven-antrun-plugin/usage.html ). So if you replace file.name property by a direct maven reference it will just work: ${project.build.directory}/${artifactId}-${version}.${project.packaging} ( above assumes that your ant script is inside the pom.xml and not externalized ) You also can override that in the build section of your pom.xml: <build> <finalName>MySuperCoolApplication</finalName> ... </build> For general debug output from mvn just use the -X flag
{ "language": "en", "url": "https://stackoverflow.com/questions/7622452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get interests from public user pages? I try to get public interests from user pages by link https://graph.facebook.com/{user_id}/interests?access_key=... But I always receive empty 'data' array, when I request data from non-friend user. What's wrong? A: You can not get data from users besides their name, id, gender, and picture that you are not friends with via the Graph API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access violation in DirectX OMSetRenderTargets I receive the following error (Unhandled exception at 0x527DAE81 (d3d11_1sdklayers.dll) in Lesson2.Triangles.exe: 0xC0000005: Access violation reading location 0x00000000) when running the Triangle sample application for DirectX 11 in D3D_FEATURE_LEVEL_9_1. This error occurs at the OMSetRenderTargets function, as shown below, and does not happen if I remove that function from the program (but then, the screen is blue, and does not render the triangle) //// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include #include #include "DirectXSample.h" #include "BasicMath.h" #include "BasicReaderWriter.h" using namespace Microsoft::WRL; using namespace Windows::UI::Core; using namespace Windows::Foundation; using namespace Windows::ApplicationModel::Core; using namespace Windows::ApplicationModel::Infrastructure; // This class defines the application as a whole. ref class Direct3DTutorialViewProvider : public IViewProvider { private: CoreWindow^ m_window; ComPtr m_swapChain; ComPtr m_d3dDevice; ComPtr m_d3dDeviceContext; ComPtr m_renderTargetView; public: // This method is called on application launch. void Initialize( _In_ CoreWindow^ window, _In_ CoreApplicationView^ applicationView ) { m_window = window; } // This method is called after Initialize. void Load(_In_ Platform::String^ entryPoint) { } // This method is called after Load. void Run() { // First, create the Direct3D device. // This flag is required in order to enable compatibility with Direct2D. UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined(_DEBUG) // If the project is in a debug build, enable debugging via SDK Layers with this flag. creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif // This array defines the ordering of feature levels that D3D should attempt to create. D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_1 }; ComPtr d3dDevice; ComPtr d3dDeviceContext; DX::ThrowIfFailed( D3D11CreateDevice( nullptr, // specify nullptr to use the default adapter D3D_DRIVER_TYPE_HARDWARE, nullptr, // leave as nullptr if hardware is used creationFlags, // optionally set debug and Direct2D compatibility flags featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, // always set this to D3D11_SDK_VERSION &d3dDevice, nullptr, &d3dDeviceContext ) ); // Retrieve the Direct3D 11.1 interfaces. DX::ThrowIfFailed( d3dDevice.As(&m_d3dDevice) ); DX::ThrowIfFailed( d3dDeviceContext.As(&m_d3dDeviceContext) ); // After the D3D device is created, create additional application resources. CreateWindowSizeDependentResources(); // Create a Basic Reader-Writer class to load data from disk. This class is examined // in the Resource Loading sample. BasicReaderWriter^ reader = ref new BasicReaderWriter(); // Load the raw vertex shader bytecode from disk and create a vertex shader with it. auto vertexShaderBytecode = reader->ReadData("SimpleVertexShader.cso"); ComPtr vertexShader; DX::ThrowIfFailed( m_d3dDevice->CreateVertexShader( vertexShaderBytecode->Data, vertexShaderBytecode->Length, nullptr, &vertexShader ) ); // Create an input layout that matches the layout defined in the vertex shader code. // For this lesson, this is simply a float2 vector defining the vertex position. const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; ComPtr inputLayout; DX::ThrowIfFailed( m_d3dDevice->CreateInputLayout( basicVertexLayoutDesc, ARRAYSIZE(basicVertexLayoutDesc), vertexShaderBytecode->Data, vertexShaderBytecode->Length, &inputLayout ) ); // Load the raw pixel shader bytecode from disk and create a pixel shader with it. auto pixelShaderBytecode = reader->ReadData("SimplePixelShader.cso"); ComPtr pixelShader; DX::ThrowIfFailed( m_d3dDevice->CreatePixelShader( pixelShaderBytecode->Data, pixelShaderBytecode->Length, nullptr, &pixelShader ) ); // Create vertex and index buffers that define a simple triangle. float3 triangleVertices[] = { float3(-0.5f, -0.5f,13.5f), float3( 0.0f, 0.5f,0), float3( 0.5f, -0.5f,0), }; D3D11_BUFFER_DESC vertexBufferDesc = {0}; vertexBufferDesc.ByteWidth = sizeof(float3) * ARRAYSIZE(triangleVertices); vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA vertexBufferData; vertexBufferData.pSysMem = triangleVertices; vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemSlicePitch = 0; ComPtr vertexBuffer; DX::ThrowIfFailed( m_d3dDevice->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &vertexBuffer ) ); // Once all D3D resources are created, configure the application window. // Allow the application to respond when the window size changes. m_window->SizeChanged += ref new TypedEventHandler( this, &Direct3DTutorialViewProvider::OnWindowSizeChanged ); // Specify the cursor type as the standard arrow cursor. m_window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); // Activate the application window, making it visible and enabling it to receive events. m_window->Activate(); // Enter the render loop. Note that tailored applications should never exit. while (true) { // Process events incoming to the window. m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); // Specify the render target we created as the output target. ID3D11RenderTargetView* targets[1] = {m_renderTargetView.Get()}; m_d3dDeviceContext->OMSetRenderTargets( 1, targets, NULL // use no depth stencil ); // Clear the render target to a solid color. const float clearColor[4] = { 0.071f, 0.04f, 0.561f, 1.0f }; //Code fails here m_d3dDeviceContext->ClearRenderTargetView( m_renderTargetView.Get(), clearColor ); m_d3dDeviceContext->IASetInputLayout(inputLayout.Get()); // Set the vertex and index buffers, and specify the way they define geometry. UINT stride = sizeof(float3); UINT offset = 0; m_d3dDeviceContext->IASetVertexBuffers( 0, 1, vertexBuffer.GetAddressOf(), &stride, &offset ); m_d3dDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Set the vertex and pixel shader stage state. m_d3dDeviceContext->VSSetShader( vertexShader.Get(), nullptr, 0 ); m_d3dDeviceContext->PSSetShader( pixelShader.Get(), nullptr, 0 ); // Draw the cube. m_d3dDeviceContext->Draw(3,0); // Present the rendered image to the window. Because the maximum frame latency is set to 1, // the render loop will generally be throttled to the screen refresh rate, typically around // 60Hz, by sleeping the application on Present until the screen is refreshed. DX::ThrowIfFailed( m_swapChain->Present(1, 0) ); } } // This method is called before the application exits. void Uninitialize() { } private: // This method is called whenever the application window size changes. void OnWindowSizeChanged( _In_ CoreWindow^ sender, _In_ WindowSizeChangedEventArgs^ args ) { m_renderTargetView = nullptr; CreateWindowSizeDependentResources(); } // This method creates all application resources that depend on // the application window size. It is called at app initialization, // and whenever the application window size changes. void CreateWindowSizeDependentResources() { if (m_swapChain != nullptr) { // If the swap chain already exists, resize it. DX::ThrowIfFailed( m_swapChain->ResizeBuffers( 2, 0, 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0 ) ); } else { // If the swap chain does not exist, create it. DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0}; swapChainDesc.Stereo = false; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.Scaling = DXGI_SCALING_NONE; swapChainDesc.Flags = 0; // Use automatic sizing. swapChainDesc.Width = 0; swapChainDesc.Height = 0; // This is the most common swap chain format. swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // Don't use multi-sampling. swapChainDesc.SampleDesc.Count = 1; swapChainDesc.SampleDesc.Quality = 0; // Use two buffers to enable flip effect. swapChainDesc.BufferCount = 2; // We recommend using this swap effect for all applications. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // Once the swap chain description is configured, it must be // created on the same adapter as the existing D3D Device. // First, retrieve the underlying DXGI Device from the D3D Device. ComPtr dxgiDevice; DX::ThrowIfFailed( m_d3dDevice.As(&dxgiDevice) ); // Ensure that DXGI does not queue more than one frame at a time. This both reduces // latency and ensures that the application will only render after each VSync, minimizing // power consumption. DX::ThrowIfFailed( dxgiDevice->SetMaximumFrameLatency(1) ); // Next, get the parent factory from the DXGI Device. ComPtr dxgiAdapter; DX::ThrowIfFailed( dxgiDevice->GetAdapter(&dxgiAdapter) ); ComPtr dxgiFactory; DX::ThrowIfFailed( dxgiAdapter->GetParent( __uuidof(IDXGIFactory2), &dxgiFactory ) ); // Finally, create the swap chain. DX::ThrowIfFailed( dxgiFactory->CreateSwapChainForImmersiveWindow( m_d3dDevice.Get(), DX::GetIUnknown(m_window), &swapChainDesc, nullptr, // allow on all displays &m_swapChain ) ); } // Once the swap chain is created, create a render target view. This will // allow Direct3D to render graphics to the window. ComPtr backBuffer; DX::ThrowIfFailed( m_swapChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), &backBuffer ) ); DX::ThrowIfFailed( m_d3dDevice->CreateRenderTargetView( backBuffer.Get(), nullptr, &m_renderTargetView ) ); // After the render target view is created, specify that the viewport, // which describes what portion of the window to draw to, should cover // the entire window. D3D11_TEXTURE2D_DESC backBufferDesc = {0}; backBuffer->GetDesc(&backBufferDesc); D3D11_VIEWPORT viewport; viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; viewport.Width = static_cast(backBufferDesc.Width); viewport.Height = static_cast(backBufferDesc.Height); viewport.MinDepth = D3D11_MIN_DEPTH; viewport.MaxDepth = D3D11_MAX_DEPTH; m_d3dDeviceContext->RSSetViewports(1, &viewport); } }; // This class defines how to create the custom View Provider defined above. ref class Direct3DTutorialViewProviderFactory : IViewProviderFactory { public: IViewProvider^ CreateViewProvider() { return ref new Direct3DTutorialViewProvider(); } }; [Platform::MTAThread] int main(array^) { auto viewProviderFactory = ref new Direct3DTutorialViewProviderFactory(); Windows::ApplicationModel::Core::CoreApplication::Run(viewProviderFactory); return 0; } A: I have marked this as the answer for the time being. Feel free to post a different answer, and I will investigate it, and choose that answer instead. Sometimes the best answer is "Microsoft Magic". Microsoft seems to be doing something internally that it isn't exposing to its 3rd party developers. Not much can be said at this stage in development, so it is currently best to simple use the WARP rasterizer on older devices..... A: It looks to me as if you're trying to use some resource that has already been released. Perhaps you should debug output the result from Release(), as it will tell you the number of existing references.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python - Interactive mode vs. normal invocation of the interpreter Is there a difference between the two modes in terms of resources, especially memory? I'm referring to Python in the title but if there is a common explanation to many interpreted languages (Octave, etc...) that would be very helpful. Thanks A: It looks like an interactive process does use somewhat more memory: compare malkovich@malkovich:/etc$ malkovich@malkovich:/etc$ python -c 'import time; time.sleep(20000)' & [1] 3559 malkovich@malkovich:/etc$ pidstat -r -p $! Linux 2.6... (malkovich) 11-10-01 _x86_64_ (4 CPU) 08:11:41 PM PID minflt/s majflt/s VSZ RSS %MEM Command 08:11:41 PM 3559 0.00 0.00 27872 4412 0.12 python malkovich@malkovich:/etc$ kill %1 malkovich@malkovich:/etc$ [1]+ Terminated python -c 'import time; time.sleep(20000)' with malkovich@malkovich:/etc$ python Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.sleep(20000) ^Z [1]+ Stopped python malkovich@malkovich:/etc$ jobs -p 3881 malkovich@malkovich:/etc$ pidstat -r -p 3881 Linux 2.6... (malkovich) 11-10-01 _x86_64_ (4 CPU) 08:16:10 PM PID minflt/s majflt/s VSZ RSS %MEM Command 08:16:10 PM 3881 0.00 0.00 34856 5072 0.14 python The RSS (resident memory usage) value is the one that's interesting: about 650 kB more for the interactive process. I would expect this value (the difference) to increase somewhat, but not significantly, with use, only because of the command history and other niceties provided in an interactive session. I don't think it would ever be a significant difference, but you may want to run similar tests for your particular situation. To background the running interpretive session, you literally press ^Z (CTRL-Z). But overall, I don't think that the difference will be significant unless you are running on an embedded system with only a few MB of RAM. Note that if you write your code as a module and then import it, it will be compiled to bytecode and saved. This will I believe reduce memory consumption and also decrease startup time on subsequent invocations. You might want to run some tests to get an idea of the difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ static-only class I have a bunch of functions that I want to put in either a separate namespace or a class. Out of the two, which would be better? If it's the latter, how should I go about it? I mean, I don't have any instance members, so should I specify the constructor as private? Or delete it? Either way, it will look something like this to give you an idea: myproject::foo::f() A: C++ namespaces and class can both contain functions and other types, but there are some key differences in behavior. You'll have to decide which is best for your particular circumstance. * *Classes can be templated, namespaces can't. This provides a way to pass a set of template arguments to a whole group of functions and other types. Combined with typedef, this can be very powerful. *You can use using namespace xyz; to bring a whole group of namespace members into any scope. Classes can be inherited to bring them into scope (has not much effect if there are no instance members, due to the empty base optimization, but static members can then be used without qualification), but this only works inside other classes. Free functions would have to explicitly qualify all access to members of the class. *Namespaces participate in argument-dependent lookup, members of a parent class don't. If you want to use the trick of inheriting a class to supply template arguments and gain unqualified access to its static members, then you should leave the constructor and destructor as defaulted and trivial, instead of deleting or making them inaccessible. In C++11, you can mark the constructor both protected and defaulted. A: If you use the class it is best to declare the default constructor, copy constructor, assignment operator, and destructor private / unimplemented (plus maybe some more for C++11). If you don't you'll have a class that can be used to make useless objects. If you use a namespace you don't have to do any of that. Classes are made for objects. Using them as containers of static functions, no member data, is more abuse than use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Visual C++ project type to be used for interop I am trying to learn Interop from C# and C++/CLI. I am starting with creating a C++/CLI project. Most of the examples I found talks about interop with COM however when I am creating a C++/CLI project in Visual studio 2010, under the project templates for Visual C++ project, I don't see any type for COM. Any ideas? Also can I create just a Visual C++ Class Library project to use for this purpose? A: You are mixing it up. There are three distinct ways to interop with native code from a managed program, you don't use them all at the same time: * *pinvoke through the [DllImport] attribute. Good for C style native APIs *interop through COM. Very well supported by the CLR as long as it is the Automation subset and you have a type library. Just works out of the box, no work needed. Adding COM to existing native code that isn't COM enabled is not productive unless you already have good COM programming skills (know ATL) *wrapper classes created in the C++/CLI language. When the above options are not enough. Required for interop with native C++ classes. Learning enough C++/CLI to get the job done requires about 3 weeks, truly learning the language is a multi-month effort. Things to focus on when you just use it for writing wrappers is #pragma managed, the proper use of the hat and the difference between the destructor and the finalizer. It is possibly worth your time to learn more about it, the syntax heavily resembles the syntax of C++/CX, the language extensions added to the MSVC++ compiler that support writing Metro apps for Windows 8. Knowing C++/CLI is 95% of knowing C++/CX. Sample quick-start wrapper class in C++/CLI in this answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get function given a list of values Is there a way that I can give python a list of values like [ 1, 3, 4.5, 1] and obtain a function that relates to those values? like y = 3x+4 or something like that? I don't want to plot it or anything, I just want to substitute values in that function and see what the result would be. edit: is there a way that python can calculate how the data is related? like if I give it the list containing thousands of values and it returns me the function that was adjusted to those values. A: Based on your comments to David Heffernan's answer, I want is to know what the relation between the values is, I have thousands of values stored in a list and I want to know if python can tell me how they are related.. it seems like you are trying do a regression analysis (probably a linear regression) and fit the values. You can use NumPy for linear regression analysis in Python. Here a sample from the NumPy cookbook. A: Yes, the function is called map(). def y(x): return 3*x+4 map(y, [1,3,4.5,1]) The map() function applies the function to every item and returns a list of the results. A: I assume you want to find out if the sequences [1, 2, 3, 4] and [ 1, 3, 4.5, 1] (or else the pairs [(1, 1), (2, 3), (3, 4.5), (4, 1)] are related with a (linear) function or not. Try to plot these and see if they form somethign that looks like a (straight) line or not. You can also look for correlation techniques. Check this site with basic statistic stuff (look down on correlation: Basic Statistics A: Based on your revised question, I'm going to go ahead and add an answer. No, there is no such function. I imagine you're unlikely to find a function that comes close in any programming language. Your definitions aren't tight enough for anything to be reasonable yet. If we take a simple case with only two input integers you can have all sorts of relationships: [10, 1] possible relationships: def x(y): return y ** 0 def x(y): return y / 10 def x(y) return y % 10 + 1 ... ... repeat. Admittedly, some of those are arbitrary, but they are valid relationships between the first and second values in the array you passed in. The possibilities for "solutions" become even more absurd as you ask for a relationship between 10, 15, or 35 numbers. A: What you're looking for is called "statistical regression". There are many methods by which you might do this; here's a site that might help: Least Squares Regression but ultimately, this is a field to which many books have been devoted. There's polynomial regressions, trig regressions, logarithmic...you'll have to know something about your data before you decide which model you apply; if you don't have any knowledge of what the dataset will look like before you process it, I'd suggest comparing the residuals of whatever you get and choosing the one with the lowest sum. Short answer: No, no function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cross validation in SAS I have split my data into 5 folds in SAS. So I have s1,s2,s3,s4,s5 I was wondering what's the best way to iterate through each of the folds to perform cross validation. For example, the first iteration I want to use s1 as my test set and s2,3,4,5 as the training sets, the second iteration use s2 as the test and s1,3,4,5 as training etc. what kind of loop in SAS would accomplish this goal? Thanks! A: Probably best to call upon a macro to make it a bit easier to call upon. %Macro Validate(cur,i) ; %Do j = 1 %to 5 ; %If &j <> &i %THEN %DO; Data &Cur._&j. ; Set &cur S&j. ; <validation steps> Run; %END; %End; %mend Validate ; Data _null_ ; Do i = 1 to 5 ; Call Execute("%Validate(s"||strip(i)||","||strip(i)||");"); End; Run; A: Proc gmlselect performs k-folds cross validation with multiple methods to choose best models. It is experimental in 9.1 but released in production for 9.2+ Further info here Hope this help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fancybox opening when I don't want it to I'm a Jeopardy game and I'm using the FancyBox lightbox plugin to show all the questions in. I'm trying to create a bonus question. This question is supposed to pop up once all of the 25 spots are gone. I'm currently using a large if statement: if($('#html5_100').is(':hidden') &&$('#html5_200').is(':hidden') &&$('#html5_300').is(':hidden') &&$('#html5_400').is(':hidden') &&$('#html5_500').is(':hidden') &&$('#attr_100').is(':hidden') &&$('#attr_200').is(':hidden') &&$('#attr_300').is(':hidden') &&$('#attr_400').is(':hidden') &&$('#attr_500').is(':hidden') &&$('#tf_100').is(':hidden') &&$('#tf_200').is(':hidden') &&$('#tf_300').is(':hidden') &&$('#tf_400').is(':hidden') &&$('#tf_500').is(':hidden') &&$('#dtag_100').is(':hidden') &&$('#dtag_200').is(':hidden') &&$('#dtag_300').is(':hidden') &&$('#dtag_400').is(':hidden') &&$('#dtag_500').is(':hidden') &&$('#tag_100').is(':hidden') &&$('#tag_200').is(':hidden') &&$('#tag_300').is(':hidden') &&$('#tag_400').is(':hidden') &&$('#tag_500').is(':hidden')){ $('#bonus').fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'hideOnOverlayClick':false, 'hideOnContentClick':false, 'showCloseButton' : false, 'overlayOpacity' : 1 }).click(); } And I'm trying to use $('#ID').is(':hidden'); I put 25 of these ifs in each Click function for each button. The problem is that once I click submit it opens this fancybox. Is there a way to stop this? If you need more help understanding I could upload my game and just give you a link to it. A: It seems like your code is working, as least for me so maybe the id's don't exist on the page? Also, maybe a better method to check all if all of those divs are hidden would be to just loop through all of them. This method also makes it easier to add additional questions with minimal effort (demo): var checkDivs = function() { var i, j, divs = 'html5 attr tf dtag tag'.split(' '); // loop through div names for (i = 0; i < divs.length; i++) { j = 1; // loop through all numbered div names (adding 100 each time) while ($('#' + divs[i] + '_' + (j * 100)).length) { // check if hidden if (!$('#' + divs[i] + '_' + (j * 100)).is(':hidden')) { return false; } j++; } } return true; }; A: does &&$('#html5_200').is(':hidden') is like that in your code? you need to change all those "&&$" it to && $('#html5_200').is(':hidden') (add space between && and $() ), edit: whay did you added the .click() after the call to $('#bonus').fancybox{ ... }? try to remove this from your code because i thik the call to the .click() function trigger this. if it doesn't help either, i will have to see the rest of your code to figure it out
{ "language": "en", "url": "https://stackoverflow.com/questions/7622479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best Way of Checking a String has one of Many Values in Perl? I'm just in the middle of some Perl code and I found myself writing the monstrosity of a line of code shown below. Perl being so full of great little shortcuts, there just has to be a better way than this right? So - is there a better way to do this: unless($config->{'case_transform'} eq 'NONE' || $config->{'case_transform'} eq 'UPPER' || $config->{'case_transform'} eq 'LOWER' || $config->{'case_transform'} eq 'CAPITAL' || $config->{'case_transform'} eq 'RANDOM') { $config->{'case_transform'} = 'NONE'; } A: my %good_value = map { $_ => 1 } qw( NONE UPPER LOWER CAPITAL RANDOM ); unless $good_value{$config->{case_transform}) { $config->{case_transform} = 'NONE'; } A: Also available is the "Smart Match" operator ~~. use 5.010; $config->{'case_transform'} = 'NONE' unless $config->{'case_transform'} ~~ ( 'NONE', 'UPPER', 'LOWER', 'CAPITAL', 'RANDOM' ); A: unless ($config->{'case_transform'} =~ /^(NONE|UPPER|LOWER|CAPITAL|RANDOM)$/) { ... } A: $config->{'case_transform'} = 'NONE' unless $config->{'case_transform'} =~ /^(?:UPPER|LOWER|CAPITAL|RANDOM)$/;
{ "language": "en", "url": "https://stackoverflow.com/questions/7622480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C: how to store integers by reading line by line with a random layout? I need to read a file and store each number (int) in a variable, when it sees \n or a "-" (the minus sign means that it should store the numbers from 1 to 5 (1-5)) it needs to store it into the next variable. How should I proceed? I was thinking of using fgets() but I can't find a way to do what I want. The input looks like this: 0 0 5 10 4 2 4 5-10 2 3 4 6 7-9 4 3 These are x y positions. A: I'd use fscanf to read one int at a time, and when it's negative, it is obviously the second part of a range. Or is -4--2 a valid input?
{ "language": "en", "url": "https://stackoverflow.com/questions/7622483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting up a model in magento 1.5.x I can successfully do getModel(module/licenses) but then when I load($id) things break. My database table is setup fine called licenses. my config file has in the global -> modules tag <modulename> <class>NameSpace_Module_Model></class> <resourceModel>module_mysql4</resourceModel> </modulename> <modulename_mysql4> <class>NameSpace_Module_Model_Mysql4</class> <entities> <licenses> <table>licenses</table> </licenses> </entities> </modulename_mysql4> I then have a file located at my module at Model/Licenses.php which has the class NameSpace_Module_Model_Licenses extends Mage_Core_Model_Abstract and includes a construc function which does $this->_init('module/licenses') I also have a file in my module at Model/Mysql4/Licenses.php with the class NameSpace_Module_Model_Mysql4_Model_Licenses extends Mage_Core_Model_Mysql4_Abstract with a constructor which does $this->_init('module/licenses', 'primary key here') This class never seems to be instantiated because I've added a var_dump exit that never seems to run So I can get my model and dump it onto the screen but if I do a load($id) things die without warning in any log files. If I run it in a try catch i still get nothing. If I run a ->getResource() instead in a try catch and dump out the exception it gives a message that Mage registry key "_resource_singleton/module/licenses" already exists. So how does one properly setup a model for a table? A: Yes, Mage registry key "_resource_singleton/module/licenses" already exists is always an indication is that you've duped a resourceModel config node.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a Magento "Backend" model? After building some frontend stuff, I'm now exploring the internals of the admin side of Magento. I read Alan Storm's article on creating a simple model (as opposed to an EAV model, something which I am not yet ready for). My main goal is to create a module that enables the user to upload and manage media to the Magento installation, so that it can be used in some templates I defined in the frontend. So I would create a model to keep track of the relations between certain media (pictures) and certain categories, pages, you name it. Just for the record: I don't like EAV models, they scare me, so unless it's absolutely necessary, don't push the conversation that way. Thank you :) I've also skimmed through this article. It's about backend models, and my question is about that: What IS a backend model? Is it a model that's used only in the backend (admin)? I wouldn't know what that would be good for. If someone could tell me something about it, or give me a hint on what to read to know more about it, it'd be great. The reason I'm telling what goal I want to reach is so that someone can tell me if these "backend models" are significant to what I want. Thanks! A: Don't worry about EAV, don't worry about "backend models". You'll need some in the trenches programming experience before you can fully understand their significance. You can get a lot done with the plain-jane Magento model classes and SQL queries. The light version: Backend models have nothing to do with the frontend-cart/backend-admin application split. A "backend model" handles loading, storing, and persisting information into a datastore (the database). A "frontend model" is PHP code that handles rendering a user interface element to display the attribute in the web browser. The terms are used in several different systems in Magento, including EAV and the System Configuration section. The article you linked to is talking abou EAV backend models. Again, the light version: Each data property of an EAV model is, itself, an object. For example, in a simpler system you'd store the product's name as the string 'Bicycle'. In Magento you assign a product attribute object to the parent EAV model for name. This way, the code for saving "name" to the database can be kept separate from the other saving code. Long story short, It's overkill for what you're after. A: In Magento backend attribute models is used to prepare data before placing it in the database. This preparation is done by beforeSave method. A good exampe is Mage_Eav_Model_Entity_Attribute_Backend_Datetime
{ "language": "en", "url": "https://stackoverflow.com/questions/7622488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get an element from a node in XDocument where two other elements are known I'm stumped (again) with an misunderstanding of XDocument/Linq. For the XML below, I have nameEn and provinceCode as variables in my code. I'm trying to identify the code (e.g., s0000002) and nameFr given I have the other two elements. The provinceCode and NameEn combined are unique in the XML (no duplication). <siteList> <site code="s0000001"> <nameEn>Edmonton</nameEn> <nameFr>Edmonton</nameFr> <provinceCode>AB</provinceCode> </site> <site code="s0000002"> <nameEn>Algonquin Park</nameEn> <nameFr>Parc Algonquin</nameFr> <provinceCode>ON</provinceCode> </site> ... </siteList> Here's the code I'm trying (my XML is in the "loaded" XDocument: selectedProvince = "ON"; selectedCity = "Algonquin Park"; strSiteCode = loaded.Descendants("site") .Where(x => x.Element("provinceCode").Value == selectedProvince) .Where(x => x.Element("nameEn").Value == selectedCity) .Select(x => x.Element("code").Value) .ToString(); strNameFR = loaded.Descendants("site") .Where(x => x.Element("provinceCode").Value == selectedProvince) .Where (x => x.Element("nameEn").Value == selectedCity) .Select(x => x.Element("nameFr").Value) .ToString(); The string strSiteCode returns: System.Linq.Enumerable+WhereSelectEnumerableIterator2[System.Xml.Linq.XElement,System.String]andstrNameFRreturns""`. I can't figure out what the working code should look like. Thanks for any help. Doug A: Try var result = loaded.Descendants("site") .Where(x => (x.Element("provinceCode").Value == selectedProvince) && (x.Element("nameEn").Value == selectedCity) ) .Select(x => x.Element("code").Value) .SingleOrDefault(); if (result != null) { strSiteCode = result.ToString(); } The Select() call returns a collection (which, in your case happens to have just one element). So you'll have to call SingleOrDefault() (or Single() ) to get the one item. Also, I removed the second Where() and included the condition to the first Where(). A: Keep in mind that it's possible that the "x.Element(...)" method will return null, whereby accessing "Value" on it will cause a null ref. This is assuming that your xml may not always have the provinceCode or nameEn. If it does, you won't have a problem, but you wouldn't want to put that possible null ref ex in release code, anyways. The following solves the null ref problem. var site = loaded .Descendants("site") .FirstOrDefault(x => (string)x.Element("provinceCode") == selectedProvince && x => (string)x.Element("nameEn") == selectedCity); if (site == null) { return } var siteCode = (string)site.Attribute("code"); var nameFr = (string)site.Element("nameFr"); A: I would probably rewrite it like this: * *get the list of matching <site> nodes once *iterate over all matches (typically only one) *get the code attribute and nameFr element from those matching items Code would look like this: // determine the matching list of <site> nodes ... var selectedSites = loaded .Descendants("site") .Where(x => x.Element("provinceCode").Value == selectedProvince) .Where(x => x.Element("nameEn").Value == selectedCity); // iterate over all matching <site> nodes foreach (var site in selectedSites) { // grab the code attribute and nameFr element from <site> node var siteCode = site.Attribute("code").Value; var nameFR = site.Element("nameFr").Value; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Operation must use an updateable query when updating excel sheet I am getting this error when trying to update excel sheet : Server Error in '/ReadExcelData_Csharp' Application. Operation must use an updateable query. and here is the code that i am using : querys = "UPDATE [Sheet1$] "+"SET [Number]=" +s.Trim()+ " WHERE [Number]=" + s2.Trim() ; objcmc = new OleDbCommand(querys, conn); objcmc.ExecuteNonQuery(); any help will be appreciated . and here is the connection i used : if (strFileType.Trim() == ".xls") { connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; } else if (strFileType.Trim() == ".xlsx") { connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; } A: Remove the IMEX=2 (or IMEX=1) from the connection string and it will work. I have tested this crazy solution several times and removing the IMEX for some strange reason seems to do the trick (at least for xlsx files). The following code works: static void Main(string[] args) { string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "d:\\temp\\customers.xlsx" + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\""; string selectString = "INSERT INTO [Customers$](Id,Company) VALUES('12345', 'Acme Inc')"; OleDbConnection con = new OleDbConnection(connectionString); OleDbCommand cmd = new OleDbCommand(selectString, con); try { con.Open(); cmd.ExecuteNonQuery(); Console.WriteLine("Success"); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { con.Dispose(); } Console.ReadLine(); } } Thanks to RobertNet from social.msdn.microsoft.com A: I used the solution provided above and removed the IMEX=2 or IMEX=1 string from the connection string. But this was not enough. In my case, the solution needed an additional work around. But in my data base I actually needed the IMEX - because my column had mixed data types, some double values some string values. When I remove IMEX =1, I get the a runtime exception "Unable to cast object of type" because it automatically selects the column data type based on the most popular value in the column and then fails to cast the values which are not of the selected type. I worked around this issue by changing my double and int values to string values (added a ' in the beginning of the cell value manually in excel) and removed the IMEX from the connection string. and then this solved the issue. A: In my case,I changed ConnectionString and then this solved the issue. I removed ReadOnly=False;HDR=Yes; parametes in connectionString string _connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;\";", pathToExcelFile);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: PC Toast Message with Java I have a Java Desktop Application which runs in the background and has a System Tray icon. When I want to tell the user something or when they interact with the icon I want to use "Toast" which is the only name I know for it. Toast is a box without a frame that pops up on the bottom right of the screen. Google Talk has exactly what I am talking about (I think Google started it). I tried searching for some example code but all I found was Toast for the Android. So, how can I make Toast with Java? A: How about trying Twinkle? It looks very similar to the Google Talk/Chrome desktop notifications. It has it's own API and the source code is free to view (license needed for commercial though).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.Net MVC 3 big file uploader with progress I've spent several hours of googling. Can anybody point me to an example of big file uploader with progress with backend on ASP.Net MVC3. I found many different solutions, but most of them use PHP as backend, and it's a bit hard for me to convert. Also I think there have to be some examples for ASP.Net MVC3. PS I don't consider paid components, please don't suggest them. A: Uploadify - there you have it :) Set maxRequestLength in the web.config http://midnightprogrammer.net/post/Upload-Files-In-RAZOR-With-jQuery-Uploadify-Plugin.aspx A: You could try out Telerik Upload not sure what the file size limit is though. This is a free and opensource component from Telerik. A: I spent a good amount of time getting the right plugin too. I use this : http://valums.com/ajax-upload/ Uploadify uses flash to send files, which was bad for me as i needed upload from authenticated users ONLY. And flash would not send the cookies and so your application will treat the upload request as anonymous. If that is not an issue, uploadify works fine too. Here is how i implemented it in mvc3 - Create a controller / action to receive the opload file. Change the 'action' property of the plugin to point to it - // url of the server-side upload script, should be on the same domain action: '/controller/action' Make sure that action returns JSON object with a property in it with 'success' = 'true'/'false'
{ "language": "en", "url": "https://stackoverflow.com/questions/7622499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Like and Share information not showing properly I made my website My SMS Buddy and i have included one facebook like button to sharing my website on facebook. But, whenever i clicked on the like button, it is only showing my website url,but it is not showing thumbnail,title,description, although i have written the code for all the information inside the main page. This is the sample code of the main page <head> <meta property="og:title" content="My SMS Buddy" /> <meta property="og:type" content="activity" /> <meta property="og:url" content="http://www.eravikant.com" /> <meta property="og:image" content="http://www.eravikant.com/images/image.jpg" /> <meta property="og:site_name" content="My SMS Buddy" /> <meta property="fb:admins" content="100002723853376" /> <meta property="og:description" content="Share and Send Free Sms Anywhere In India Which Support Upto 160 Characters Long Sms Without Any Advertisements Attached with the Sms To Any Mobile In India With Easy Group Messaging" /> </head> <body> <iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.eravikant.com&amp;send=false&amp;layout=box_count&amp;width=60&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font=segoe+ui&amp;height=90" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:60px; height:90px;" allowTransparency="true"></iframe> </body> Need suggestion, what am doing wrong here... Suggestion will be appreciated ... A: There are some really odd things in your page's HTML. You have duplicates of your opening and closing HEAD, BODY and wrapping HTML tags. This is invalid HTML and doesn't parse at all. This also won't show your page properly in web browsers since it won't know which part of the HTML to render. This is what is confusing Facebook. Remove the first HTML opening and closing (plus its contents) and Facebook should get your OG Metadata fine. It's in the second HTML HEAD metadata and that looks fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Name parameter ignored in Facebook feed dialog I try opening a simple dialog from my iOS app to post something on a user's wall. However it seems the "name" parameter is completely ignored. Here is the code, I use the Facebook SDK from Github, pulled the version yesterday. NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"This is the name",@"name",nil]; [facebook dialog:@"feed" andParams:params andDelegate:self]; The dialog shown only shows: "Post to your wall" "Write something..." the text box "via MyApp" When actually posting the post is completely empty. Why is the "name" parameter completely ignored? A: Seems I've found the solution. It works if you do not pass a description, but pass a caption argument instead. Then the name appears, the caption text below, and the parsed link text below that A: For some background, the name parameter is attached to a link you attach to the post, see the properties description section https://developers.facebook.com/docs/reference/dialogs/feed/. So add a link parameter alongside the name. As mentioned in a comment, even though the name parameter is not visible in the preview dialog it will be posted and show up on Facebook, providing you also provide a link parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create media - Magento API (Soap) I have a little problem with my PHP script. This one use the Magento API and try to create a media for a product. $imageData = array( 'file' => array( 'name' => 'myimage.jpg', 'content' => base64_encode(file_get_contents($product_image_url)), 'mime' => 'image/jpeg' ), 'label' => 'Product Image #4', 'position' => 1, 'types' => array('small_image','image','thumbnail'), //'types' => array('image'), 'exclude' => 0 ); $image_create = $client->call($sessID, 'product_media.create', array($product_id, $imageData)); $client->call($sessID, 'product_media.update', array($product_id, $image_create)); When I run this script with a little image (about 10ko, 100x100 pixels), everything works fine, but when I try with a large image (140k, 500x500 pixels) soap return this error : SoapFault exception: [HTTP] Internal Server Error in /var/www/vhosts/domain.com/httpdocs/test_update.php:46 Stack trace: #0 [internal function]: SoapClient->__doRequest('__call('call', Array) #2 /var/www/vhosts/domain.com/httpdocs/test_update.php(46): SoapClient->call('068bd88e8f56261...', 'product_media.c...', Array) #3 {main} My idea is that the length, when it's a large image, of base64_encode(file_get_contents($product_image_url)) is too big and then Soap fail. Maybe Apache or PHP conf file? Santerref. A: Yes, it's very likely that PHP or Apache is causing this error. Check your Apache error_log for any clues. Some possible PHP configuration options: * *max_execution_time *memory_limit *post_max_size *upload_max_filesize
{ "language": "en", "url": "https://stackoverflow.com/questions/7622516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: while loops and fileStreams i have the code below: while (FileOne.hasNextLine()){ String check = FileOne.nextLine(); Reader r = new FileReader("something"); mass1: try{ Scanner FileTwo = new Scanner(r); mass1: while (FileTwo.hasNextLine()) { String toCheck= FileTwo.nextLine().toString(); index1 = check.indexOf(toCheck); if(index1 != -1){ index2++; break mass1; }//if(index1 != -1) }//(it.hasNext()) }//try finally { r.close(); }//finally }//while (FileOne.hasNextLine()) And i want to ask: When the second while aka while (FileTwo.hasNextLine) ends (with or without the break command), the next time that the parser will go to that command, the file will start from the beggining or from the possition it was last time? If it doesnt starts from the beggining then how will i make it to start from it (the beggining)? A: It should start from the beginning because you create a new scanner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to install windows service using Inno Setup? In VS2010 I have solution with windows service project and some other 'helper' projects. So in my debug folder there is an windows service application and couple of dlls. I can install windows service by running application with parameter, so in Inno Setup I just do: Filename: {app}\MyService.exe; Parameters: "--install"; WorkingDir: {app}; Flags: skipifdoesntexist; StatusMsg: "MyService is being installed. Please wait..." My question in: It is necessary to pack all files from Release folder to my Setup file? I mean, in my Release folder are: DLLs from my other projects in app solution, Program Debug Database (.pdb) files, and XML Configuration file.. What files should be packed in my Setup.exe file? A: You just need the *.exe files. *.pbd and other are not needed there. Only DLLs if nedded by your main project (service).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need to write a RESTful JSON service in Java Here is my requirement: * *I have a simple table in mysql(Consider any table with a few fields) *I need to write a simple RESTFUL JSON webservice in Java that performs CRUD operations on this table. I tried searching on the net for some comprehensive example for this but could not find any. Can anyone help? A: Jersey is a JAX-RS implementation for building RESTful webservices. Start with their tutorial. It's pretty easy. http://jersey.java.net/nonav/documentation/latest/getting-started.html Edit: Also, there's a great O'Riley book on the subject (shocking, I know); RESTful Java with JAX-RS A: I would take a look at what Spring has to offer. There are RestTemplate's, and Spring MVC, Both of which should be able to help you out. Another thing which will be helpful is some sort of JSON-Mapping library. I will recommend Jackson Object Mapper. Take a look at their tutorials for an idea of how it will work. A: I will outline the essential parts of my blog post Building a RESTful Web Service in Java, which shows the steps you can take to connect to the database and create a RESTful Web Service using the following. * *IDE: Eclipse IDE for Jave EE Developers (Kepler), comes with Maven built in *Database: MySQL (also makes use of MySQL Workbench) *Application Server: GlassFish 4.0 *Java EE 7 (JAX-RS, JPA, JAXB, etc) *Any REST Client for testing: (eg Postman) The following description assumes you have already installed the technology listed above. The service is for a database table 'item' that stores items with the fields id, itemName, itemDescription, itemPrice. The Persistence Layer * *Create a MySQL database schema using MySQL Workbench's ‘create a new schema in connected server‘ icon. In this example the schema is called 'smallbiz'. *Connect Eclipse to MySQL * *Download the MySQL JDBC driver and save in a convenient location. *In Eclipse, create a new Database Connection in the Data Source Explorer tab. During this process you will need to browse to the MySQL JDBC driver. *Create a MySQL JDBC Connection Pool and Resource in GlassFish (this is required for the application to be able to connect the database once deployed on the server). * *Copy the MySQL JDBC driver to the ext directory in GlassFish i.e. $glassfish_install_folder\glassfish\lib\ext. Then restart GlassFish. *Loggin into the GlassFish admin area using a browser (located at http://localhost:4848 by default). *Under Resources > JDBC > Connection Pools, create a new connection pool with a 'Resource Type' of java.sql.Driver. *On the 'New JDBC Connection Pool (Step 1 of 2)' screen. * *Enter a 'Pool Name' (eg SmallBizPool). *Select the 'Resource Type' (java.sql.Driver). *Select the 'Database Driver Vendor' (MySQL). *Next. *On the bottom section of the following screen in Additional Properties. * *URL: jdbc:mysql://localhost:3306/smallbiz *user: yourUser (root in my set-up) *password: yourPassword *Finish *Ping on the following screen to test the connection. *Create a JDBC Resource from the connection pool at Resources > JDBC > JDBC Resources: * *Enter a 'JNDI Name' (eg jdbc/SmallBiz). We use this in the persistence.xml file so the application knows how to connect to the database. *Select the connection pool previously created from the 'Pool Name' drop down list. *For more Information on JDBC Connection Pool and Resource * *This answer has some screen shots that may help. Note it uses a 'Resource Type' of javax.sql.DataSource *Making datasource in Glassfish *Some confusion surrounding JDBC Resources and JDBC Connection pools Glassfish *Connect Eclipse to GlassFish. * *Add GlassFish Tools to Eclipse by searching Help > Eclipse Marketplace. *Connect GlassFish to Eclipse by creating a new server using the Servers tab. * *Select GlassFish 4.0 on the Define a New Server screen. *Ensure 'jdk7' i selected and the JDK in the New GlasssFish 4.0 Runtime screen. *On the screen that follows, ensure the correct domain directory is selected (the default is domain1, eg. $glassfish_install_folder\glassfish\domains\domain1), then enter the admin credential for GlassFish. *You can now interact with GlassFish (start, stop, restart, run on, etc) from in Eclipse. *Create a new Maven Project in Eclipse and add dependencies using m2e (which is built in) for: * *EclipseLink (for JPA) “org.eclipse.persistence eclipselink” To map to the database, a JPA Entity is used. A JPA Entity is simple a POJO (Plain Old Java Object) annotated with JPA annotations. If the database already exists, Eclipse can generate the JPA Entity from the database. * *Create a database table using the SQL scrapbook in Eclipse with the following SQL CREATE TABLE item ( id VARCHAR(36) NOT NULL, itemName TEXT NOT NULL, itemDescription TEXT, itemPrice DOUBLE, PRIMARY KEY (id) ) *Create a JPA entity from the database table by right clicking a package created in Eclipse and selecting New > JPA Entities from Table. *Annotate the JPA entity with JAXB annotation in order to be able to marshal it to and from xml or json. Since this example uses UUID's for the primary key, there are also annotations (@UuidGenerator and @GeneratedValue) that are specific to EclipseLink to take care of creating them. It is not necessary to use UUID's as the primary keys but one of the reasons I use it is so that I can create a model on the client complete with a UUID and then PUT that new model to the server (eg in offline mode, new models created and stored locally are PUT to the server when cell signal returns). If the server created the UUID then new model is sent to the server without an id using POST. package com.zangolie.smallbiz.entities; import java.io.Serializable; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import org.eclipse.persistence.annotations.UuidGenerator; /** * The persistent class for the item database table. * */ @UuidGenerator(name="UUID") @XmlRootElement @Entity @NamedQuery(name="Item.findAll", query="SELECT i FROM Item i") public class Item implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator="UUID") @Column(length=36) private String id; private String itemDescription; @Lob private String itemName; private double itemPrice; public Item() { } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getItemDescription() { return this.itemDescription; } public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; } public String getItemName() { return this.itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public double getItemPrice() { return this.itemPrice; } public void setItemPrice(double itemPrice) { this.itemPrice = itemPrice; } } * *Create folder src\main\webapp\WEB-INF\classes\META-INF and create a persistence.xml file. <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="testPU" transaction-type="JTA"> <jta-data-source>jdbc/SmallBiz</jta-data-source> </persistence-unit> </persistence> * *See Understanding Persistence.xml in JPA for more information. The RESTful Service Layer * *Set the Maven Compiler to 1.7 * *Right click the pom.xml file and select Open With > Maven POM Editor. Add the following just before the closing tag. xml snippet <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> * *Add dependencies using m2e for: * *Servlet 3.1 (JAX-RS 2.0 requires this) "javax.servlet javax.servlet.api" *Jersey (for JAX-RS) "org.glassfish.jersey.core jersey-sever" *EJB (required to use the @Stateless annotation) "javax.ejb javax.ejb.api" *Create a POJO (plain old java object) and annotate it with JAX-RS annotations to create an endpoint. * *@Path("/your-app-api-uri"): To indicate the path, relative to your server base uri, that a resource is located *@Produces ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}): The representation produced can be json or xml. *@Consumes ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}): The representation consumed can be json or xml *@Stateless: There server does not store state between interactions (this is one of the principles of the RESTful architecture). *Annotate methods that map to CRUD operations * *@POST: Create *@GET: Read *@PUT: Update *@DELETE: Delete The JAX-RS Service package com.zangolie.smallbiz.services.rest; import java.net.URI; import java.util.Collection; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.ws.rs.BadRequestException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.zangolie.smallbiz.entities.Item; @Path("/item") @Produces ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Consumes ({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Stateless public class ItemRestService { //the PersistenceContext annotation is a shortcut that hides the fact //that, an entity manager is always obtained from an EntityManagerFactory. //The peristitence.xml file defines persistence units which is supplied by name //to the EntityManagerFactory, thus dictating settings and classes used by the //entity manager @PersistenceContext(unitName = "testPU") private EntityManager em; //Inject UriInfo to build the uri used in the POST response @Context private UriInfo uriInfo; @POST public Response createItem(Item item){ if(item == null){ throw new BadRequestException(); } em.persist(item); //Build a uri with the Item id appended to the absolute path //This is so the client gets the Item id and also has the path to the resource created URI itemUri = uriInfo.getAbsolutePathBuilder().path(item.getId()).build(); //The created response will not have a body. The itemUri will be in the Header return Response.created(itemUri).build(); } @GET @Path("{id}") public Response getItem(@PathParam("id") String id){ Item item = em.find(Item.class, id); if(item == null){ throw new NotFoundException(); } return Response.ok(item).build(); } //Response.ok() does not accept collections //But we return a collection and JAX-RS will generate header 200 OK and //will handle converting the collection to xml or json as the body @GET public Collection<Item> getItems(){ TypedQuery<Item> query = em.createNamedQuery("Item.findAll", Item.class); return query.getResultList(); } @PUT @Path("{id}") public Response updateItem(Item item, @PathParam("id") String id){ if(id == null){ throw new BadRequestException(); } //Ideally we should check the id is a valid UUID. Not implementing for now item.setId(id); em.merge(item); return Response.ok().build(); } @DELETE @Path("{id}") public Response deleteItem(@PathParam("id") String id){ Item item = em.find(Item.class, id); if(item == null){ throw new NotFoundException(); } em.remove(item); return Response.noContent().build(); } } * *Create an Application Class that defines the base uri. eg for http://localhost:8080/smallbiz/rest package com.zangolie.smallbiz.services.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("rest") public class ApplicationConfig extends Application { } *Deploying to GlassFish from within Eclipse. * *Right click the project Run As > Run on Server *Select the connected GlassFish server. *Test with any HTTP client (such as Postman which works in chrome). Though the example uses GlassFish, any Java EE 7 compliant container will work. If you do use a different container (and assuming you use the same EclipseLink for JPA and Jersey for JAX-RS implementations), you will have to: * *Sort out how to connect to it from Eclipse. *Change the Maven dependencies for Jersey and EclipseLink from provided to compile (since those are the implementations in GlassFish and may be different in other containers). Hope it is helpful. A: this might be doing exactly what you are looking for: http://restsql.org/doc/Overview.html DISCLAIMER: I have never used it - just remembered seeing it recently in a news post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Custom URL Scheme for CommandLine Application Is it possible for a Xcode "CommandLine application" (written in C++) to be launched with a custom URL scheme? I know you can do this with a Cocoa application, but would it be possible with C++? A: It doesn't matter what language you use; it is not possible to bind a URL scheme to a command-line tool. The opening of URLs happens by an Apple Event to the application, not directly running the program with the URL (particularly since it may already be running, but this is true whether it is or not). You could try embedding an Info.plist in the executable to give it a bundle identifier and declare its support for the URL scheme, which may enable you to bind the URL scheme to the executable. I would still be surprised if opening such URLs worked, but it's worth a shot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is it possible to understand at Code behind whether page is being called inside iframe or not I need to understand that whether page is being called inside iframe or not at code behind. Is this possible? I need to determine it in master page code behind. asp.net 4.0, C# A: In general, no. Of course you can emit client script that detects iframe and reloads the page with e.g. a querystring. A: It's not possible. However there's a workaround this. You can use querystring and check on page load if that querystring contains value, for example: <iframe src="Default.aspx?iframe=true" /> In your Default.aspx.cs file: protected void Page_Load(object sender, EventArgs e) { if(!string.IsNullOrEmpty(Request.QueryString["iframe"])) { if(Convert.ToBoolean(Request.QueryString["iframe"]) { // this page is loaded in an iframe } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery Simple SlideToggle in sections I am creating a simple page with questions and answers. This is how it looks: SECTION > Question > Answer And this keeps on repeating with different sections, Each section has multiple questions and each question has an answer. By default everything is set to display:none. Now when someone clicks on any of the section, the related set of questions should showup, and when someone clicks on the question, it;s answer should show up. Only one section should be open at a time. I kind of figured it would require parent(), child(), each() functions but I don't know how and where to use them :( I have previously used javascript and used to do it via ID basis, but since I'm using jQuery, I thought I'd rewrite the page using classes as .section, .question and .answer Here is a the simple fiddle page where I have created li elements : http://jsfiddle.net/DKMJH/2/ A: Here it is: $('.question, .answer').css("display","none"); $('.section').click(function (){ $(this).next('.question').slideToggle(500); }); $('.question').click(function (){ $(this).next('.answer').slideToggle(500); }); A: Your HTML is invalid, <li> elements don't nest like that so the browser will probably try to fix it up and what sort of selector you want for the next question or answer depends on how the browser decides to mangle your HTML. You probably want this HTML: <ul> <li class="section">Section One</li> <li class="question">This is a question</li> <li class="answer">This is an answer</li> <li class="section">Section Two</li> <li class="question">This is another question</li> <li class="answer">This is another answer</li> </ul> Now that we have valid HTML, we'll know what the final structure really is and you can use next to find the appropriate single element to open: $('.section').click(function() { $(this).next('.question').slideToggle(500); }); $('.question').click(function() { $(this).next('.answer').slideToggle(500); }); You also spelled cursor wrong in your CSS but that won't have any effect on your jQuery. Fix fiddle: http://jsfiddle.net/ambiguous/jcnMa/ ryudice was in first and got to the heart of the matter, I just needed more space than a comment to deal with the broken HTML issue. Using next only works because the browser is restructuring your HTML into a single unordered list. If you only want one question open at a time, then close the other ones: $('.section').click(function() { var $others = $('.question:visible').not(this); $others.next('.answer').hide(); $others.slideToggle(500); $(this).next('.question').slideToggle(500); }); Demo: http://jsfiddle.net/ambiguous/jcnMa/1/ A: I think this neater for what you want:- $('.question, .answer').css("display", "none"); $('.section').click(function() { $(this).nextUntil('.section', '.question, .answer:visible').slideToggle(500); }); $('.question').click(function() { $(this).next('.answer').slideToggle(500); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7622530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Need application/json from RESTful Roo application I've created a basic RESTful Roo application using the following Roo-script (Roo 1.1.5). project --topLevelPackage com.roorest persistence setup --provider HIBERNATE --database HYPERSONIC_IN_MEMORY entity --class ~.domain.MyClass field string --fieldName String1 web mvc setup web mvc all --package ~.web json all When I access the RESTful WS asking for application/json the WS spits out a valid json body, however the content type is set to application/text (which makes perfect sense if one looks at the generated (aj) controller code ticking in the background). Unfortunately, I need to have the WS return a content type of application/json. I've tried to push in the necessary methods from the json-controllers, however this seems 1) cumbersome, 2) not really working (I'm getting a LOT of errors with the pushed in source). Can one force the WS return application/json on a general basis? For instance, is it possible to combine ContentNegotiatingViewResolver with the roo generated aj controllers? (And why does the roo generated code explicitly set application/text as it's content type in the first place? Is hacking the roo JSON addon a viable solution?) I guess what I'm really asking is this: what do you think is the best way to make a roo scaffolded application return domain objects as application/json through a WS? A: Did you solve the problem, because I just having the same one...? Okay, I do have one solution: Add the methods to your controller and do not let the AOP Framework add them: @RequestMapping(headers = "Accept=application/json") @ResponseBody public ResponseEntity<String> listJson() { HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json; charset=utf-8"); //was app/text return new ResponseEntity<String>(Customer.toJsonArray(Customer .findAllCustomers()), headers, HttpStatus.OK); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to build FParsec for .NET Compact Framework? I’m writing a small application based on FParsec. Today, I’m looking for an opportunity to make a version for Compact Framework. Apparently, it is not that simple to build FParsec sources for .NET CF. The FParsecCS library has unsafe code and some references to the types that are not available in CF. Namely, System.Collections.Generic.HashSet, System.Text.DecoderFallbackException, and more. I’m wondering if there’s any way to make it built. Obviously, I’m trying not to alter the code as it would be hard to update when further versions of FParsec released. I don’t really care about performance. If there is a generic CharStream that can be used instead of high-performance one you have, that would be quite sufficient. Thank you for your help. A: I don’t have any experience with .NET CF and never tried to make FParsec run on it. However, there’s a Silverlight version of FParsec, which might be a good starting point for a port to .NET CF. The Silverlight version builds on the LOW_TRUST version of FParsec, which doesn’t use any "unsafe" code. Hopefully, the stream size limitation of the LOW_TRUST version won’t be an issue for your application. The easiest way to deal with the HashSet dependency probably is to implement you own simple HashSet type (based on a Dictionary) that implements the few methods that FParsec actually uses for its error handling. If the DecoderFallbackException is not supported, you can just comment out the respective exception handlers. If you track your changes with HG, it shouldn’t be difficult to merge in updates to FParsec. Depending on how extensive the changes for .NET CF are, I could also include them in the main source tree for another conditional compiler symbol.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# MVC Access to path denied when trying to write file I have an MVC application in which users are able to upload files. Before I write the uploaded file, I create a directory according to date time. I start off with C:\ApplicationName and end up with C:\ApplicationName\20111001\Filename.ext when the upload is completed (in theory). My problem on my local Windows 7 machine is that I can not write the file. I get an "access denied" exception no matter which user I give full access to the directory. The strange thing is that the date directory gets created just fine. I have given the following users full access: * *[Current logged in user] *NETWORK SERVICE *IUSR *IIS_IUSRS *Guests *Everyone Without any success. I really don't understand what is going on here. When I give Everyone full access, I should be able to create a file right? PS: I use Visual Studio 2010 and ASP.NET Development Server straight out of the box. A: Check the permissions of the parent folder and make sure they are inheritable, you can check this on the advance options window. A: This might help a bit... probably application pool permission is the culprit here: IIS AppPoolIdentity and file system write access permissions A: I am not running IIS, I am running the watered down version "ASP.NET Development Server". So I am quite limited The problem is that in order for you to write to the file directory from the application you will need to run Visual Studio as Administrator. Windows 7 is preventing the process from going outside of its sandbox because it is running with limited privileges. This is true even if your account is the administrator. A: Just had the same problem myself. By default IIS7 AppPools use AppPoolIdentity. Just open up your AppPools in IIS Management Console, select the one you are having problems with, choose Advanced Settings and under Process Model change Indentity to Built-in Acoount > NetworkService. Since you have already granted NETWORK SERVICE acces to your folder everything should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Better performance in lower light conditions (OpenCV)? I am trying to detect hands, and my algorithm works perfectly during day, but during the night it completely fails- it shows no signs of working at all. I have come to the conclusion this is because of lower light conditions. Could someone please give me tips for better performance in lower light conditions? My algorithm just uses cvInRangeS to find the skin-coloured pixels in an HSV image. Any tip would do, regardless of how little it would help. Thanks A: Have you normalized your input first? What's the average V value by day and by night? That said, your sensor will be RGB, and the transformation from RGB to HSV loses quite a bit of precision in the H and S components when R,G and B are low. In extrema: {0,1,0} is quite close to {1,0,0} but the hue is entirely different. A: cv::equalizeHist is probably what you want for normalization/equalization. As for the colour matching - you are dropping the V component of your image to do the colour matching right? You could also try YCbCr, which has been shown to be even better than HSV in terms of lightness variance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I detect when to show a keyboard on a touch device? I'm trying to make a program the will run on a touchpad device like this: http://sethsandler.com/multitouch/mtbiggie/ I'm trying to make a keyboard that will pop up when you need it. I'm working in C++ and Windows or Java and Ubuntu (haven't decided yet). I was hoping people might be able to answer the question: How can I detect when the user needs a keyboard to enter text when I'm * *using C++ on Windows *using Java on Windows *using Java on Ubuntu A: Presumably you will have some sort of GUI facilities, with several control types available for you to use. Each control must expose if it is interested in keyboard. For example, a TextField control will report that it wants keyboard input, while a Button will not. Also your GUI engine will have to track which control has focus, based on what the user taps. Once you have implemented the above, you know that you need to pop the keyboard when the focus moves to a control that reports itself as wanting keyboard input. Inversely, you will hide the keyboard when the focus goes to a control that does not want keyboard input.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does this do whatever it does? #include <stdio.h> void littledot(){}//must use C, not C++ int main() { littledot(568,76,105,84,116,76,101,68,111,84); printf("%c%c%c%c%c%c%c%c%c\n"); getchar(); return 0; } The above code yields the result "LiTtLeDoT". Why does it do that? Why is 568 crucial? A: This differs per platform and is UB (the implementation can do anything it wants*), but probably the arguments to littledot() are still on the stack after littledot() returns and printf prints those arguments from the stack. NEVER RELY ON THIS! *really anything. Afaik an ancient version of GCC started a videogame when it encountered something that would behave in an undefined way. A: You were lucky. This is undefined behaviour, specifically the call to printf. The program could do anything. Your implementation happens to write "LiTtLeDoT". The really is the nature of undefined behaviour. The compiler can do anything it wants. If you really want to know why it does what it does then you will need to look at the emitted object code. Looking at the C code will yield nothing because of the aforementioned undefined behaviour. A: http://codepad.org/tfRLaCB5 I'm sorry, what you claim the program to print is not what happens on my box and not what happens on codepad's box. And the reason is, the program has undefined behavior. printf expects one additional argument (an int) for every %c you have in the format string. You don't give it those arguments, hence anything can happen. You are in a situation where with certain implementations of printf, compiler options, certain compilers and certain ABIs, you end up with that output. But you should not think that this output is required by any specification. A: This is what's working reliably for me with Open Watcom 1.9 on Windows: //must use C, not C++ #include <stdio.h> #include <stdlib.h> void __stdcall // callee cleans up littledot() { } int main(void) { littledot(/*568,*/'L','i','T','t','L','e','D','o','T'); printf("%c%c%c%c%c%c%c%c%c\n"); getchar(); exit(0); return 0; } littledot() is called with a number of parameters that are passed on the stack. If the calling convention for littledot() is __stdcall (or __fastcall), it will have to remove its parameters from the stack. If it's __cdecl, then main() will have to remove them, but this won't work for us. However, littledot() doesn't and can't do anything about the parameters because they're not specified, which is something you can do in C, but not C++. So, what happens is that not only littledot()'s parameters remain on the stack after the call to it, but also the stack pointer is not restored (because neither littledot() nor main() remove the parameters, which is typically done by adjusting the stack pointer) and the stack pointer points to 'L'. Then there's the call to printf() that first places on the stack the address of the format string "%c%c%c%c%c%c%c%c%c\n" thus forming all expected parameters for the function on the stack. printf() happily prints the text and returns. After that the stack isn't correctly balanced and doing return in main() is risky as the app may crash. Returning by means of exit(0) fixes that. As all others have said, none of this is guaranteed to work. It may only work with specific compilers for specific OSes and then only sometimes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can Basemap draw a detailed coastline at the city level? I'm trying to draw a detailed coastline of the NYC area using Basemap in Python. Using the full resolution dataset, Manhattan looks like rectangle, and the Hudson doesn't show up at all about midtown. Here's the code I'm using. Any suggestions? from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np m = Basemap(projection='merc',llcrnrlat=40.55,urcrnrlat=40.82,\ llcrnrlon=-74.1, urcrnrlon=-73.82, lat_ts=40.5,resolution='f') m.drawcoastlines() m.drawrivers() m.fillcontinents(color='coral',lake_color='aqua') m.drawmapboundary(fill_color='aqua') plt.show() EDIT On further exploration, it looks like my issue is with the rivers, specifically. I can get the detailed boundaries of the oceanic coastline, but there is still no Hudson river and no Harlem river. Current code: m = Basemap(projection='merc',llcrnrlat=40.55,urcrnrlat=40.82,\ llcrnrlon=-74.1, urcrnrlon=-73.82, lat_ts=40.5,resolution='f') m.drawmapboundary(fill_color='#85A6D9') m.drawcoastlines(color='#6D5F47', linewidth=.4) m.drawrivers(color='#6D5F47', linewidth=.4) m.fillcontinents(color='white',lake_color='#85A6D9') plt.show() A: The data shipped with basemap is quite low resolution (high resolution data takes up quite a lot of space). You can load shapefiles to display with basemap. I've borrowed code from this tutorial to do that before. The tutorial also links to GADM, where you can download high resolution shapefiles for any country. A: You should try to put the area threshold to 0.1, e.g: m = Basemap(projection='merc', # ... area_thresh = 0.1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to use easy_install to install Python modules I am trying to use easy_install to install a module called requests by doing easy_install requests This worked fine a week ago when I was using Python 2.6.5 but today I installed Python 2.7.2 and then tried to import requests in one of my scripts but it failed. I then tried reinstalling requests with easy_install requests but got this error install_dir /usr/local/lib/python2.6/dist-packages/ error: can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/usr/local/lib/python2.6/dist-packages/test-easy-install-15207.pth' The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /usr/local/lib/python2.6/dist-packages/ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: http://packages.python.org/distribute/easy_install.html Please make the appropriate changes for your system and try again. So I was told to go reinstall easy_install and I went to http://pypi.python.org/pypi/setuptools and learned I had to delete all setuptools*.egg and setuptools.pth files from your system's site-packages directory (and any other sys.path directories) FIRST. So I did this. I then reinstalled setuptools from the setuptools-0.6c11-py2.7.egg. It seemed successful but when I ran easy_install requests I got basically the same error except the directory python2.6/dist-packages is now python2.7/site-packages siddhion@siddhion-laptop:~$ easy_install requests error: can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/test-easy-install-16253.write-test' The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /usr/local/lib/python2.7/site-packages/ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: http://peak.telecommunity.com/EasyInstall.html Please make the appropriate changes for your system and try again. Also, when I do easy_install and press tab I get these options easy_install easy_install-2.6 easy_install-2.7 How come easy_install-2.6 is there? and How do I get easy-install working again? A: You should use virtualenv on package-based Linux distributions so Python scripts don't interfere with other packages or conflict with the OS's package-manager. http://workaround.org/easy-install-debian A: The following worked for me with Ubuntu 12.10 installing easy_install then pip: sudo apt-get install python-virtualenv curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py sudo python get-pip.py A: Have you tried adding your new python.framework to path? On mountain lion I added /Library/Frameworks/Python.framework/Versions/3.3/bin/ to /etc/paths and then I was able to use easy_install-3.3 and pip-3.3 A: Using Sudo before easy_install may solve your problem Sudo easy_install requests thanks A: Did you try using sudo like this? sudo easy_install requests Or specify the install directory to a directory that you have write privileges. easy_install --install-dir=/home/foo/bar But you should really use PIP instead of easy_install. It is much better and has a lot more features. A: It might be a simple case of you missing "sudo" in the front. Can you try it with sudo easy-install requests putting the "sudo" will add the required permissions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Simulating computer cluster on simple desktop to test parallel algorithms I want to try and learn MPI as well as parallel programming. Can a sandbox be created on my desktop PC? How can this be done? Linux and windows solutions are welcome. A: If you want to learn MPI, you can definitely do it on a single PC (Most modern MPIs have shared memory based communication for local communication so you don't need additional configuration). So install a popular MPI (MPICH / OpenMPI) on a linux box and get going! If your programs are going to be CPU bound, I'd suggest only running job sizes that equal the number of processor cores on your machine. Edit: Since you tagged it as a virtualization question, I wanted to add that you could also run MPI on multiple VMs (on VMPlayer or VirtualBox for example) and run your tests. This would need inter-vm networking to be configured (differs based on your virtualization software). Whatever you choose (single PC vs VMs) it won't change the way you write your MPI programs. Since this is for learning MPI, I'd suggest going with the first approach (run multiple MPI programs on a single PC). A: You don't need to have VMs running to launch multiple copies of your application that communicate using MPI . MPI can help you a virtual cluster on a given single node by launching multiple copies of your applications. One benifit though, of having it run in a VM is that (as you already mentioned) it provides sand boxing .Thus any issues if your application creates will remain limited to that VM which is running the app copy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Vim auto indent private keyword I'm learning Vim (I'm using gVim) I need to do the following: Suppose I typed this: class MyClass { private } After typing the : after private, result should be: class MyClass { private: } How can I do automate that behaviour? I tried with :imap private: <Home><Delete> But I feel it's not an elegant solution at all. I already installed c.vim by Fritz Mehner. A: set cindent set cinoptions=g-1 Reference: http://vimdoc.sourceforge.net/htmldoc/indent.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7622564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What mechanisms are available for sharing session state in ASP.NET applications? So we're scaling out our application to have two Web servers, and will most likely need four or five in the next year or so if all goes well. I'm aware of sharing session state between servers with SQL Server and the ASP.NET state server. However, I'm a little concerned about the single-point-of-failure with the ASP.NET state server, and as we don't use SQL Server for anything else I'd rather avoid that provider, too. What are my alternatives? What custom state servers are out there that are light-weight, can support fail-over between multiple machines, and don't require the licensing overhead of SQL Server? A: Take a look at either: Memcached: http://memcachedproviders.codeplex.com/ or, AppFabric: http://msdn.microsoft.com/en-us/library/ee790859.aspx Both are free. There's also scale out state server, but you have to pay for it: http://www.scaleoutsoftware.com/products/scaleout-sessionserver/
{ "language": "en", "url": "https://stackoverflow.com/questions/7622576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assign variable to multiple vectors in Clojure The clojure.contrib.sql module has a create-table function that takes the table name and a list of specifications, like this: (sql/create-table :services [:id :serial "PRIMARY KEY"] [:service_name :varchar "NOT NULL"] [:pass_hash :varchar "NOT NULL"] [:token :varchar "NOT NULL"]) If I'm reusing the same columns again and again, is there a way to define something like this? (def same-columns [:id :serial "PRIMARY KEY"] [:service_name :varchar "NOT NULL"] [:pass_hash :varchar "NOT NULL"] [:token :varchar "NOT NULL"]) When I tried running that in the REPL I got an error, because it passes too many arguments to def. A: You could probably use apply for this: (def same-columns [[:id :serial "PRIMARY KEY"] [:service_name :varchar "NOT NULL"] [:pass_hash :varchar "NOT NULL"] [:token :varchar "NOT NULL"]]) (apply sql/create-table :services same-columns) If you have other columns you can add those as well: (apply sql/create-table :services [:some-column :varchar "NOT NULL"] same-columns)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Given list of countries draw map with those countries a different color Looking to the do what the title says - produce a world map image that colors particular countries. I'm open to platform - Processing or Python/Basemap preferable. Web based service ok if it has an API. Anyone have direction on this? A: have you looked at GIS? There are a number of open source and free clients that allow you to work with various maps (probably .dwg) with various corresponding data in xml format to produce geographical visualizations through queries and you can export a number of formats. I think this would give you either the visualization that you want or the data to plug into processing or whatever to create it. A: Get the map data in shapefile format, look at python bindings to OGR and GDAL, or maybe try Fiona: http://sgillies.net/blog/1095/fiona/ or SciPy, or just download Qgis www.qgis.org and learn some GIS skills. Country-level shapefiles for the world are fairly widely available www.gadm.org maybe. A: Google Geomap did the trick here. It's part of their chart visualizations tools. A javascript call that returns an SVG map colored according to data that you provide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: XCode 4.2 on OSX 10.7.1 (Lion) Crashing/Locking Up all the time. Anyone Know how to fix? This should not create any Issues with the NDA as I am not asking anyone to reveal any functionality of the application, I have asked on the Developer Forums, but They dont have the user base or the response speed of StackOverflow. I have been working with XCode for a while now. And other then these issues, I REALLY LIKE the new xcode. I will (when these issues are resolved) recommend this application to all iOS/OSX developers. Anyhow. I am currently developing iOS applications. And am Running this setup on Mac OSX 10.7.1 (Lion) Issue 1: If I use the Interface builder it will first of all stay open even after I navigate away from it and it is no longer visible or to my knowledge "running". After a while it will consume more then 4 gigs of active memory. I will have the activity monitor open and Will eventually have less than 20megs left of free memory. I upgraded my MacMini to 8 Gigs of memory and at this point it will get down to about 200 Megs of memory left and will eventually release the memory that IB had held onto. If I do not open IB in XCode 4 it tends to use a lot less memory. (adding 8 gigs of memory makes this memory leak a lot less of a problem) Issue 2: (MOST ANNOYING, HOPING FOR A FIX TO THIS ONE MOST) This one only currently happens on one of the Three machines I code on. And what happens is while programming if I [Run] the app it will work for a while. Then at some point through the process it will begin to Lock Up when I press Run or Command-R. If I save the code file and run. It will not lock up. However if I forget to save, It will not only lock up. But will force me to terminate the XCode app, and Subsequently Recode everything that I had edited since the last save and the Application Run. This is by far the most annoying bug I have encountered this far. Issue 3: This bug happens more and more often the longer the application and operating system has been running. Running into the iPad will give me a number of Errors including "Unable to Connect to Debugger" or "Finished Successfully" among others. But the important part of this issue is that the application will never get sent to the iOS device. It will compile and say it finished. But there will be a error in the output pane. I hope others have encountered these errors and Hopefully there is a quick fix with config files or something that will make development a lot more convenient. Thanks to anyone for resolution to any of these issues..... EDIT I finally received an email from apple support. I have emailed them off a Capture from XCode 4 and will hopefully hear something from them. Or maybe they will just release a new beta. Either way I hope to get this resolved asap. A: For issue #2 you might want to try auto-saving your code before runs. See XCODE auto save code when build and run? instructions. Not sure if these instructions will work for 4.2 but you get the idea. A: I had issues with my Xcode 4.2 install crashing initially. Re-running the installer over the already installed Xcode 4.2 fixed them. Obviously I don't know what the underlying issue with the install was, but although the first install reported installation was successful, obviously it wasn't. Perhaps worth trying. When a newer version of Xcode 4.2 becomes available to you (cough), you might want to see whether installing that one fixes the problem. Perhaps given the issues, you should try uninstalling the previous version first rather than installing over the top? A: Do you use multiple windows? They are anathema to Xcode 4. If you persist in your heresy, it may corrupt some files, and slow itself down. You will see a lot of beachballing, and it will be in some sort of GC. You can work around this by deleting a workspace-specific file hidden inside your project. (I will have to look up which one, if this describes your case.) A: With the new Beta GM Release they have seemingly fixed the issue with the Hanging. Thanks for the Answers. Ill +1 anyone who helped but ultimately it was apple that fixed the issue.... For now
{ "language": "en", "url": "https://stackoverflow.com/questions/7622581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Php array to formatted Text Key : Value I have this array: Array ( [location] => Array ( [country] => India [country_code] => IN [region] => [region_code] => [city] => [zip] => [latitude] => 13.044468 [longitude] => 77.575665 [ip_address] => 123.236.219.154 [timestamp] => 1317496122 [route] => 3rd Cross Rd [neighborhood] => Basaveshwara Layout [sublocality] => BCITS PVT LTD [locality] => Bengaluru [administrative_area_level_2] => Bengaluru Rural [administrative_area_level_1] => Karnataka ) ) I wonder if there is a way that I can format it some what like this: country: India country_code:In That is like Key : Value, Key : Value, Key : Value A: Something like that? foreach( $array as $key => $value ) { echo $key." : ".$value.","; } You have to check the last value and remove the "," then.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display a custom string in mvc3 dropdownlist but keep id field mapped to item selected? Q: How can I display firstname + lastname (or any string literal) in a mvc3 dropdown list but keep mapped/bound associated id when item is selected? -- Model public class UserT { public int UserTId { get; set; } public string Username { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } -- Controller // This is what I have to display as username but want to display as FirstName + LastName // .: How to I change "Username" to FirstName + LastName but bind it to the selected UserTId ??? ViewBag.ContactUserId = new SelectList(db.UserTs, "UserTId", "Username"); -- View @Html.DropDownList("ContactUserId", "--Select a contact--") A: One possibility would be to add a new, read-only property to your UserT class which returns the first and last names and then bind to that property: public class UserT { public int UserTId { get; set; } public string Username { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get { return string.Format("{0} {1}", this.FirstName, this.LastName); } } } ViewBag.ContactUserId = new SelectList(db.UserTs, "UserTId", "FullName");
{ "language": "en", "url": "https://stackoverflow.com/questions/7622590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby searching through multidimensional array Learning the beauty of Ruby code and I was wondering if there is a simple/straightforward to search within a multidimensional array. I have an multi array with 4 indices that contain assorted number. I want to search though each index matching the contents agains another array...seudo codez multi_array = [ [1,3,7], [3,1,4], [1,3,4], [0,9,2]] numbers_looking_to_match = [1,5,9] multi_array.each do | elmt | elmt.each_with_index do |elmt, idx| if elmt == numbers_looking_to_match.each { |e| puts "match" } end end I want this to return a new multi array with all non matching characters removed for original multi array. A: Using Array#& for intersection, multi_array.map {|a| a & numbers_looking_to_match } A: multi_array.each { |elem| numbers_looking_to_match.each { |x| elem.delete(x) if elem.include?(x)} } A: To scrub each element of unwanted characters: require 'set' multi_array=[ [1,3,7], [3,1,4], [1,3,4], [0,9,2]] numbers_looking_to_match=Set.new([1,5,9]) scrubbed=multi_array.collect{ |el| numbers_looking_to_match.intersection(el).to_a } puts scrubbed.inspect # prints [[1], [1], [1], [9]]
{ "language": "en", "url": "https://stackoverflow.com/questions/7622591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use Google Libraries API (jQuery) with Google App Engine? I am trying to add this jQuery Hover effect to my site. Instead of downloading jQuery I decided to use Google Libraries API for jQuery. I got a key and copied the code that goes to the header then I copied the jQuery for the hover effect but nothing is happenning. What am I doing wrong? This is where my test page is and below is the complete code and the handler: class JQueryTest(webapp.RequestHandler): def get(self): self.response.out.write("""<html>""") self.response.out.write("""<head>""") self.response.out.write("""<script type="text/javascript" src="https://www.google.com/jsapi?key=GOOGLE LIBRARIES API KEY"></script>""") self.response.out.write("""<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> $("ul.thumb li").hover(function() { $(this).css({'z-index' : '10'}); /*Add a higher z-index value so this image stays on top*/ $(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/ .animate({ marginTop: '-110px', /* The next 4 lines will vertically align this image */ marginLeft: '-110px', top: '50%', left: '50%', width: '174px', /* Set new width */ height: '174px', /* Set new height */ padding: '20px' }, 200); /* this value of "200" is the speed of how fast/slow this hover animates */ } , function() { $(this).css({'z-index' : '0'}); /* Set z-index back to 0 */ $(this).find('img').removeClass("hover").stop() /* Remove the "hover" class , then stop animation queue buildup*/ .animate({ marginTop: '0', /* Set alignment back to default */ marginLeft: '0', top: '0', left: '0', width: '100px', /* Set width back to default */ height: '100px', /* Set height back to default */ padding: '5px' }, 400); }); </script>""") self.response.out.write("""<link type="text/css" rel="stylesheet" href="/stylesheets/jquery.css" /> """) self.response.out.write("""<title>JQuery Test</title>""") self.response.out.write("</head>") self.response.out.write("""<body>""") self.response.out.write("""<div class="content">""") self.response.out.write(""" <ul class="thumb"> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGIfcCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGIyGCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGIm1Cww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGM-dCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGM6dCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGIuGCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGLrzCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGLWlCww" alt="" /></a></li> <li><a href="#"><img src="http://ting-1.appspot.com/image?img_id=agZ0aW5nLTFyEAsSCEhvbWVQYWdlGLWlCww" alt="" /></a></li> </ul>""") self.response.out.write("""</div>""") self.response.out.write("</body></html>") A: You're not wrapping your jQuery code in $(document).ready(), so the DOM doesn't exist yet at the time you're trying to attach the handlers. In general, any time you need to reference DOM elements in the page (as opposed to just defining functions to be called later), you have to wrap it all in a .ready() callback so that it won't run until the DOM is completely loaded. Try this: $(function() { $("ul.thumb li").hover(function() { // ... }, function() { // ... }); }); That should work - it does here: http://jsfiddle.net/nrabinowitz/gdsxH/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7622592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Isotope plugin .element resizing and positioning is there any other jQuery Isotope plugin implementor that knows, if it is possible to automatically shrink a currently enlarged .element when a new .element is clicked, and if it is possible to have that currently enlarged .element always displayed top left in the #container div (the other elements can Isotope themselves around as usual after reLayout)? Thanks! A: With support from the plug-in creator, it can be done rather smoothly via using Isotope's sort function - classing the clicked element while declassing the previously clicked one. I post the website I'm working on, once I have understood it myself ;) It's really amazing how one can customize the workings of this plug-in; worth paying for. A: You may be able to leverage this: http://isotope.metafizzy.co/tests/masonry-corner-stamp.html for stamping the elarged element to the side. If you can't get this to work you might want to look into the "shuffle" functionality and set that elements shuffle property to a value where it always puts it at the top left. As for the other issue of toggling the enlarged elements you can just remove the class which enlarges the element from the currently enlarged element and put it on the new one using jquery's "removeClass" method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Intellij Idea shows compatible="no" for android emulator Intellij Idea shows compatible="no" for every android emulator. I tried emulators with different api levels. At the same time compatible="true" for my NexusOne. Does anyone know how it checks device/emulator for compatibility? I have next settings in manifest: <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="4"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.WRITE_APN_SETTINGS"/> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:anyDensity="true" /> A: It could happen because of a known bug when you install SDK while IntelliJ IDEA is running. Restarting IntelliJ IDEA should fix the problem. A: Try removing android:targetSdkVersion="4" A: I've had this problem before. For me it was because I did not have some of the Android tools in my $PATH. The emulator may work regardless, but it is better to play it safe. Try adding these lines somewhere in your /home/username/.bashrc file and restart the terminal to make sure all of these tools are included. export PATH=${PATH}:.../android-studio/bin export PATH=${PATH}:.../android-studio/sdk export PATH=${PATH}:.../android-studio/sdk/platforms export PATH=${PATH}:.../android-studio/sdk/platform-tools To test if they are included properly, just check the output of a simple command like, $adb
{ "language": "en", "url": "https://stackoverflow.com/questions/7622595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: what is recommended for a wpf app, sql database or xml I want to build a wpf app (with mvvm dp) and I need to manage a list of customers (200 customers maximum) What is the recommended way to handle this? sql (mySql, sqlServer) or other way (xml, excel, access)? I can see advantage in xml because its not required addition installation A: If you've got multiple users on different machines, and those machines have a persistent, shared network connection (they're on the same network, for instance), then you should prefer to use a central database, like (as you mention) SQL Server or MySQL. The latter is free, and the former is available in a free edition (Express) for light workloads. If you don't need to share data between the different users of your application (you don't mind if their customer data get out of sync), then look at lightweight, embedded databases, like SQLite or SQL Server Compact Edition. Very simple and easy to set up and maintain, but the data stays present on a single machine. You could build an infrastructure around manual synchronization between the different machines, sort of like how iTunes synchronizes data between your computer and iPhone whenever you plug the latter in, but trust me, that's a lot of work that's best avoided if possible. Databases have a lot of built-in multiple-users-doing-stuff-at-the-same-time logic that you want to leverage if at all possible. A: If the only thing you need to persist is a list of 200the items and you don't see there as being any other persistent data requirements in the future, I would say that a flat file is plenty. However, this also depends on how often that small data will be retrieved. I am a huge proponent of SQL Server, and Express is free. But you don't want to overengineer the problem. Unless I misunderstood your question, that is my evaluation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php resize blob image I am echoing the data received from a blob column from mysql like this: <?php $con = mysql_connect("localhost","username","pass"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mydb", $con); if(isset($_GET['imageid'])){ $img=$_GET['imageid']; $sql="SELECT image FROM vrzgallery WHERE id=$img"; $que=mysql_query($sql); $ar=mysql_fetch_assoc($que); echo $ar['image']; header('Content-type: image/jpeg'); } ?> QUESTION: How can i reduce my image to say like 500px X 500px A: It is really the bad idea to store images in DB, because they are too big, harder to maintain, harder to work with and so on. You should store only path to it or file name. To resize image you may use PHP's GD library. Create it using imagecreatefromstring() and manipulate using imagecopyresized() or imagecopyresampled(). Example from manual: // File and new size $filename = 'test.jpg'; $percent = 0.5; // Content type header('Content-Type: image/jpeg'); // Get new sizes list($width, $height) = getimagesize($filename); $newwidth = $width * $percent; $newheight = $height * $percent; // Load $thumb = imagecreatetruecolor($newwidth, $newheight); $source = imagecreatefromjpeg($filename); // Resize imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // Output imagejpeg($thumb);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: libsqlite in simulator and iOS compiling I'm having some issues when compiling my app to iOS. I'm using sqlite3 and imported as #import <sqlite3.h> Well, I only found a file named libsqlite3.0.dylib in my Mac and I copied it to my project. When I compile it for iOS Simulator, it works just fine. However, when I try to compile the app for iOS Device, it throws an error (Apple Match-O Linker Error) in every call I do in my implementation to sqlite's function (such as _sqlite3_open, etc.) How can I compile it to iOS Device? Thank you! A: Instead of simply copying the library, do it like this: * *in Xcode Navigator, click on your target (the upmost entry) *go to Build Phases, then Link Binary With Libraries *add the libsqlite3.dylib from it's location at /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOSxx.sdk/usr/lib/ A: Just in case someone faced that same problem as me. If you are unit testing your code, add the lib file also to your test target. A: Did you try to import sqlite3 library like: #import "sqlite3.h" instead of: #import <sqlite3.h> A: The best way that I have found to use SQLite in your IOS application is to build your own copy of the SQLit library and include it in your project. libsqlite3.0.dylib is a very old copy of SQLite. You can easily download the SQLite Amalgamation source code and build it for IOS. this gives you the latest SQLite source code that has all the latest bug fixes and improvements. If you can open Xcode and create a new static library project, then you are 75% of the way there. Once you have the static library project, include the SQLite sources that you downloaded from the SQLite Amalgamation and set a few Preprocessor options and your off and running with the latest code. For complete details and sample source code you can visit my blog conedogers
{ "language": "en", "url": "https://stackoverflow.com/questions/7622610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do I stop this video from autoplay on my blog? I've tried everything < object id="flashobject" type="application/x-shockwave-flash" allowScriptAccess="always" allowFullScreen="true" allowNetworking="all" height="442" width="720" data="http://www.thedoctorstv.com/UMInterface_Tremor.swf?at=01823b09-1298-4bc6-a9fe-b70810b73213"> <param name="quality" value="high" /> <param name="allowScriptAccess" value="always" /> <param name="allowFullScreen" value="true" /> <param name="allowNetworking" value="all" /> <param name="movie" value="http://www.thedoctorstv.com/UMInterface_Tremor.swf?at=01823b09-1298-4bc6-a9fe-b70810b73213" /> <param name="flashvars" value="programID=4ded41f8b81bc&config=http://r.unicornmedia.com/embed/01823b09-1298-4bc6-a9fe-b70810b73213?view=item%26view_id=4d91c6ec-dcaf-4861-939d-2c57052d1ab5" /></object> A: As far as I know, flash movie will need to have a stop(); action in the first frame of the first scene in order to not play right away, regardless of what the parameters say in the <object> tag. Additionally, a button hotspot would need to be added over the entire flash movie that initates the play(); command when the viewer clicks on it. I'm not sure that you can do anything about it without owning the original .fla file. on (release){ play(); } A possible work around would be to try and screenshot the first frame of the flash movie and make a static image out of it. Then try to find a script that "swaps" content on a click. Put the static image on your page and have it "swap" to the flash content when the viewer clicks. Source: http://www.dynamicdrive.com/forums/showthread.php?t=15583
{ "language": "en", "url": "https://stackoverflow.com/questions/7622615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: executing a git pull from a different directory I'm configuring calimoucho (a little play continuos integration server), and for it to work I need to run a command to pull a cloned git hub repository from outside it. to be more precise, I'll explain it with an example. I have the following repository cd /home/sas mkdir apps cd apps mkdir myApp cd myApp git init echo "my file" > file git add . git commit -m "initial commit" Just a silly test repository where my app is supossed to be Now I need to clone that repository to a checkout folder. cd /home/sas mkdir calimoucho cd calimoucho mkdir checkout cd checkout git clone /home/sas/apps/myApp/ so I have the following directory structure ~/apps myapp .git file ~/calimoucho checkout myapp .git file The continuos integration server will have to pull new changes from ~/apps/myapp to ~/calimoucho/checkout/myapp, running a command line sentence from ~/calimoucho I try with the following command ~/calimoucho$ git --git-dir=/home/sas/apps/myApp/.git --work-tree=/home/sas/calimoucho/checkout/myApp/ pull and I get the following error fatal: /usr/lib/git-core/git-pull cannot be used without a working tree. if I don't specify the --work-tree option, the pull is issued, but changes are applied to ~/calimoucho folder instead of ~/calimoucho/checkout/myApp any idea how to update the cloned repo from the ~/calimoucho folder? thanks a lot A: This one worked for me: git --git-dir=/home/myuser/awesomeproject/.git --work-tree=/home/myuser/awesomeproject pull I'm using it inside a post-update hook to automatically pull and restart pm2 on my test server. A: In my case, this is only working solution: git --git-dir=/gitbackup/test/.git pull A: git -C ~/Documents/blar/blar/directory/ pull This worked for me after hours of searching. I'm on a Mac in Terminal. A: I had this question, too. I found the answer in the git documentation (https://git-scm.com/docs/git). Run the command git -C <git-working-directory> pull <git remote> The specific command to answer this question is git -C checkout/myApp/ pull Note that it is important -C <git-working-directory> comes before the pull command and any additional pull options can be specified at the end of the command. In the example above, the git clone command would have setup the default remote repository ~/apps/myapp so it is not required to specify the remote repository. A: You should not set the work-tree to a different repository than the git-dir variable. I think they are meant to be used when you don't want the .git folder to be in the same directory as your working tree. Instead try this: ~/calimoucho/$ git pull --work-tree=checkout/myApp/ ../../apps/myapp A: In case your git version doesn't like the git-working-directory option: Unknown option: -C Then use the push-directory command beforehand. For example, this will pull your git project from parent directory (or clone if it doesn't exists): pushd ./project-name && git pull && popd || git clone https://repo-url/project-name
{ "language": "en", "url": "https://stackoverflow.com/questions/7622616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: Simply encrypt a string in C I'm trying to encrypt a query string on a game I'm making when opening a url. It doesn't have to be complicated, in fact since I'm working from a game engine it needs to be as simple as possible. It tends to fuss if I get too low level. I've already created the query string, I just need to take each char of it and subtract 15 from the char to lightly encrypt it. I'm just wanting to make a simple encryption that will deter most users. I wish I could give a code example but I'm not too experienced in C, and I'm not even sure where to begin. The game engine's api usually makes everything simple for me. A: Your "encryption" won't fool anybody. There are good implementatons of well-known and secure encryption algorithms available online. For example: Twofish Edit: Example implementation of XOR: void encrypt(char *array, int array_size) { int i; char secret[8] = { 22, 53, 44, 71, 66, 177, 253, 122 }; for(i = 0; i < array_size; i++) array[i] ^= secret[i]; } Assumes that the array containing the query string is 8 or less bytes long. Increase the length of secret to meet your needs. A: void doTerribleEncryptionMethod(char * arr, int arrSize) { int i; for(i = 0; i < arrSize; i++) { arr[i] -= 15; } } Notice the function name. What you want to do is silly, and pretty worthless. A: You can do it with a very simple function: void encrypt(char *s) { int i, l = strlen(s); for(i = 0; i < l; i++) s[i] -= 15; } There's also a simple encryption algorithm you may be interested in, it's called XOR cipher. A: SonOfRa already proposed the right answer. But if you're intent on using something terrible to obscure a string without actually encrypting it, the GNU C library provides a memfrob(3) that is already-written and easily reversible. A: None of these answers really constitute any form of reasonable encryption. What you actually want to do, is use some form of authenticated encryption, and some form of secure key derivation algorithm. My personal recommendation is libsodium. It provides very good defaults, and an API that is relatively hard to get wrong. There's several different ways to do this: * *Secret key encryption with a random key Authenticated Encryption *Secret key encryption with a key derived from a passphrase Key Derivation *Hybrid encryption with Key Agreement. Public Key Encryption All of these possibilities are integrated into libsodium and implementable with relative ease. The following code examples are taken directly from the libsodium documentation. For 1: #define MESSAGE ((const unsigned char *) "test") #define MESSAGE_LEN 4 #define CIPHERTEXT_LEN (crypto_secretbox_MACBYTES + MESSAGE_LEN) unsigned char nonce[crypto_secretbox_NONCEBYTES]; unsigned char key[crypto_secretbox_KEYBYTES]; unsigned char ciphertext[CIPHERTEXT_LEN]; /* Generate a secure random key and nonce */ randombytes_buf(nonce, sizeof nonce); randombytes_buf(key, sizeof key); /* Encrypt the message with the given nonce and key, putting the result in ciphertext */ crypto_secretbox_easy(ciphertext, MESSAGE, MESSAGE_LEN, nonce, key); unsigned char decrypted[MESSAGE_LEN]; if (crypto_secretbox_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, key) != 0) { /* If we get here, the Message was a forgery. This means someone (or the network) somehow tried to tamper with the message*/ } For 2: (Deriving a key from a password) #define PASSWORD "Correct Horse Battery Staple" #define KEY_LEN crypto_secretbox_KEYBYTES unsigned char salt[crypto_pwhash_SALTBYTES]; unsigned char key[KEY_LEN]; /* Choose a random salt */ randombytes_buf(salt, sizeof salt); if (crypto_pwhash (key, sizeof key, PASSWORD, strlen(PASSWORD), salt, crypto_pwhash_OPSLIMIT_INTERACTIVE, crypto_pwhash_MEMLIMIT_INTERACTIVE, crypto_pwhash_ALG_DEFAULT) != 0) { /* out of memory */ } Now, the key-array contains a key that is suitable for the use in the code sample above. Instead of randombytes_buf(key, sizeof key) for generating a random key, we generated a key derived from a user-defined password, and use that for encryption. 3 is the "most complicated" of the 3 types. It is what you use if you have two parties communicating. Each of the parties generates a "keypair", which contains a public and a secret key. With those keypairs, they can together agree on a "shared key" that they can use for encrypting (and signing) data for each other: #define MESSAGE (const unsigned char *) "test" #define MESSAGE_LEN 4 #define CIPHERTEXT_LEN (crypto_box_MACBYTES + MESSAGE_LEN) unsigned char alice_publickey[crypto_box_PUBLICKEYBYTES]; unsigned char alice_secretkey[crypto_box_SECRETKEYBYTES]; crypto_box_keypair(alice_publickey, alice_secretkey); unsigned char bob_publickey[crypto_box_PUBLICKEYBYTES]; unsigned char bob_secretkey[crypto_box_SECRETKEYBYTES]; crypto_box_keypair(bob_publickey, bob_secretkey); unsigned char nonce[crypto_box_NONCEBYTES]; unsigned char ciphertext[CIPHERTEXT_LEN]; randombytes_buf(nonce, sizeof nonce); if (crypto_box_easy(ciphertext, MESSAGE, MESSAGE_LEN, nonce, bob_publickey, alice_secretkey) != 0) { /* error */ } unsigned char decrypted[MESSAGE_LEN]; if (crypto_box_open_easy(decrypted, ciphertext, CIPHERTEXT_LEN, nonce, alice_publickey, bob_secretkey) != 0) { /* message for Bob pretending to be from Alice has been forged! */ } This code first generates both keypairs (typically, this would happen on bob's and alice's machine separately, and they would send each other their public key, while keeping their secret key, well, secret). Then, a random nonce is generated, and the call to crypto_box_easy(...) encrypts a message from alice to bob (using bob's public key to encrypt, and alice's secret key to make a signature). Then (after potentially sending the message over the network), the call to crypto_box_open_easy(...) is used by bob to decrypt the message (using his own secret key to decrypt, and alice's public key to verify the signature). If the verification of the message failed for some reason (someone tried to tamper with it), this is indicated by the non-zero return code. A: if you want to, you can just xor the bytes by iterating through the array and using ^= this decrypts and encrypts #include <string.h> char* xorit(char* str, int key){ // any number for key except for(int i=0; i<strlen(str);i++){ str[i] ^= key; } return str; } A: You can use a variant of base64 with a custom alphabet, or just a shuffled alphabet. It's not really secure, but in your case it is probably sufficient. The algorithm is widely used, so it will be easy for you to find an implementation where you can provide a custom alphabet. The bonus point is, that whatever you put into the query string, the encoded form will consist of valid URL characters, if you choose the alphabet appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Performance Bottleneck with python mapping data structure I am facing a little performance problem with one of my data structures used for a bigger project in python. Basically, I am importing a tabular delimited file. Using the normal python open(...) file iterator I am splitting the lines with line.split("\t"). Now I want the actual value of a column be inserted in some sort of dictionary returning an ID for the value. And there it is getting slow: In general - the dictionary class looks like this: class Dictionary(list): def getBitLength(self): if(len(self) == 0): return 0 else: return math.log(len(self), 2) def insertValue(self, value): self.append(value) return len(self) - 1 def getValueForValueId(self, valueId): return self[valueId] def getValueIdForValue(self, value): if(value in self): return self.index(value) else: return self.insertValue(value) The basic idea was, that the valueId is the index of the value in the dictionary list. Profiling the program tells me that more than 50% are spend on getValueIdForValue(...). 1566562 function calls in 23.218 seconds Ordered by: cumulative time List reduced from 93 to 10 due to restriction <10> 240000 13.341 0.000 16.953 0.000 Dictionary.py:22(getValueIdForValue) 206997 3.196 0.000 3.196 0.000 :0(index) The problem is, that this is just a small test. In real application environment this function would be called several million times which would increase the runtime for this to a large extend. Of course I could inherit from python dict, but than the performance problem is quite similar since I need to get key of a given value (in case that the value already has been inserted to the dictionary). Since I am not the Python Pro until now, can you guys give me any tips how to make this a bit more efficient? Best & thanks for the help, n3otec === Thanks guys! Performance of bidict is much better: 240000 2.458 0.000 8.546 0.000 Dictionary.py:34(getValueIdForValue) 230990 1.678 0.000 5.134 0.000 Dictionary.py:27(insertValue) Best, n3otec A: If keys and values are unique, you can use a bidirectional dictionary. There is one python package here
{ "language": "en", "url": "https://stackoverflow.com/questions/7622618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: logo on left and menu on right in same row I want to have in the same raw, in the left a logo, and in the right a menu like Contact Us. If I make 3 divs for this and I allign the first left, and the 3rd right, it doesn't work. How can you have this? A: Float would be a clean, simple way to do it. Try floating your logo div left, and your menu div right, like so: HTML: <div id="navbar"> <div id="logo">Logo</div> <div id="navmenu">Nav menu</div> </div> CSS: div#logo { float: left; } div#navmenu { float: right; } A: Without any actual markup to look at, the following is a very simple three-column setup. This is not meant as a three-column page layout, only three columns stretching across the top. Note the use of float to send the DIV's to the same row, left to right*. * You could set the last right. Also, you will have to clear as well for any content following the #menu-row DIV (this is the overflow: auto part). CSS #menu-row { overflow: auto; } #menu-logo { width: 10%; float: left; } #menu-logo img { width: 100%; } #menu-content { width: 80%; background: #ddd; float: left; } #menu-right { width: 10%; height: 1.3em; background: #dfd; float: left; } #menu-content li { display: inline; list-style-type: none; height: 128px; } #page-content { background: #ddf; } HTML <div id="menu-row"> <div id="menu-logo"> <img src="http://www.gravatar.com/avatar/e1122386990776c6c39a08e9f5fe5648?s=128&d=identicon&r=PG"/> </div> <div id="menu-content"> <ul> <li>Home</li> <li>About</li> <li>Stuff</li> </ul> </div> <div id="menu-right"></div> </div> <div id="page-content"> <p>This is stuff.</p> </div> http://jsfiddle.net/LYJUB/1/ A: I dont fully understand your question, but you might be able to fix it by positioning the divs absolute. in the HTML: <div id="leftdiv"></div> in the CSS: #leftdiv{ width:10%; height:100%; position:absolute; left:0%; top:0%; } #rightdiv{ width:10%; height:100%; position:absolute; right:0%; top:0%; } #centerdiv{ width:80%; height:100%; position:absolute; left:10%; top:0%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala 2.9 can't run "hello world" sample on Windows XP I'm trying to run HelloWorld sample with scala 2.9.1 final on Windows XP: object HelloWorld extends App { println("Hello, World!") } File is saved as Hello.scala. When I run scalac Hello.scala, it's ok. When I run scala Hello, it writes: "Exception in thread "main" java.lang.RuntimeException: Cannot figure out how to run target" It's ridiculous, my echo %PATH% contains: C:\Program Files\Java\jdk1.6.0_25\bin; C:\Program Files\Java\jdk1.6.0_25\jre\lib; C:\Program Files\Java\jdk1.6.0_25\lib; C:\Program Files\scala\bin so everything seems to be in classpath. Running scala -classpath "%PATH%;." Hello doesn't help either. Please help. A: Shouldn't it be scala HelloWorld? I can repro your problem on Mac too: $ scalac hello.scala $ scala HelloWorld Hello, World! $ scala Hello Exception in thread "main" java.lang.RuntimeException: Cannot figure out how to run target: Hello at scala.sys.package$.error(package.scala:27) at scala.tools.nsc.GenericRunnerCommand.scala$tools$nsc$GenericRunnerCommand$$guessHowToRun(GenericRunnerCommand.scala:38) at scala.tools.nsc.GenericRunnerCommand$$anonfun$2.apply(GenericRunnerCommand.scala:48) at scala.tools.nsc.GenericRunnerCommand$$anonfun$2.apply(GenericRunnerCommand.scala:48) at scala.Option.getOrElse(Option.scala:109) at scala.tools.nsc.GenericRunnerCommand.<init>(GenericRunnerCommand.scala:48) at scala.tools.nsc.GenericRunnerCommand.<init>(GenericRunnerCommand.scala:17) at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:33) at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:89) at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala) scala expects either a class name or a source name. scala Hello doesn't resolve to either of them. A: I think it´s a CLASSPATH issue. You could try this: $ scala -classpath . Hello
{ "language": "en", "url": "https://stackoverflow.com/questions/7622626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Installing cancan 2.0 gem in Rails 3.1 I'm having trouble installing the cancan 2.0 gem in Windows XP. I am using Rails 3.1 and in my gemfile y have gem "cancan", :git => "git://github.com/ryanb/cancan.git", :branch => "2.0" but it keeps saying No such file or directory - git clone "git://github.com/ryanb/cancan.git" My teammates are not having this problem, but the are working in Unix systems. A: It sounds like your git is not working properly. Are you using any other git references in your Gemfile? I copied and pasted the exact same thing in my gemfile and it worked just fine. A: gem 'cancan', github: 'ryanb/cancan', branch: '2.0'
{ "language": "en", "url": "https://stackoverflow.com/questions/7622630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Examining XML in a stream If I have a large XML document, which I don't want to load entirely into memory, and some configurable value like an XPath statement or othe format that identifies a path to an element in the xml, is it possible to read the xml from a stream node by node until I find the location I am looking for? We need to build facilities to pull out a value from xml without knowing the schema. All we have is the xml document and an xpath statement. We could probably revise to use something other than xpath, but we really want to avoid loading up the whole document because we need to process in realtime, and the xml could be fairly large, and the volume could get high. A: LibXML2 provides a streaming API (where you can parse a document a chunk at a time) and also XPath. Mixing the two isn't as straightforward as with the standard DOM parser, but it's possible to do on a per-element basis. See here for more info: http://xmlsoft.org/xmlreader.html#Mixing A: You can do this with Saxon-EE. The simplest approach is probably using XQuery document projection: see here http://www.saxonica.com/documentation/sourcedocs/projection.xml A: try http://code.google.com/p/jlibs/wiki/XMLDog XMLDog can evaluate xpaths using SAX (i,e without loading whole document into memory)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Destroying a Postgres DB on Heroku I want to destroy the database but I'm not sure what the command would be. Does anyone know how to do this? A: To answer Siamii's question above: DATABASE in heroku pg:reset DATABASE is by default postgres A: Simply follow the steps below. Run heroku pg:reset DATABASE to recreate the database with nothing in it, then run heroku run rake db:migrate to initialize the database with the correct schema & data. Look at the new heroku documentation it helps ;) A: None of the answers above actually describe how to destroy a Heroku database, which was the original question (and what led me here seeking an answer). From their docs, either of these will work: * *heroku addons:destroy heroku-postgresql:tier (where tier is the database tier, like hobby-dev) *heroku addons:destroy HEROKU_POSTGRESQL_<COLOR> (if you have more than one database of that tier) Note that because this is a destructive action it will prompt you to confirm the action. If you want to use this in a script you can skip the prompt with something like this: heroku addons:destroy HEROKU_POSTGRESQL_<COLOR> --confirm <appname> Hope that's helpful! A: You shouldn't use a postgres command to fully delete your database, as you will not have permissions to create a new one. Instead you should use the heroku command to clear out your database: heroku pg:reset DATABASE_URL
{ "language": "en", "url": "https://stackoverflow.com/questions/7622633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: Winforms: Closing a program to system tray 'This is the event that is fired as the application is closing, whether it 'be from a close button in the application or from the user 'clicking the X in the upper right hand corner Private Sub Form1_FormClosing(sender as Object, e as FormClosingEventArgs) Handles Form1.FormClosing 'What we will do here is trap the closing of the application and send the application 'to the system tray (or so it will appear, we will just make it invisible, re-showing 'it will be up to you and your notify icon) 'First minimize the form Me.WindowState = FormWindowState.Minimized 'Now make it invisible (make it look like it went into the system tray) Me.Visible = False End Sub Hello again Stackoverflow! Im trying to make an application that when you press X, the program gets put in system tray. But i have like no idea how i'm suppost to do that, so did a search on google and found this code. Only VB2010 (what i use) doesn't like the fourth line. Can anybody give me a quick tutorial on this, and make this work in VB 2010? By the way, i will most likely use VB only tonight, just to make one application. So im not thinking of learing the whole language. A: It looks like you found code over here Dream.In.Code: Minimize To System Tray Did you "keep" reading the rest of the messages? You need to add: e.Cancel = True to your FormClosing event or else the program just ends. Also, you need to add the NotifyIcon component and a ContextMenuStrip.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: read audio file information php How do I read information as bitrate, length, etc. Different file formats, mp3, wmw etc etc. from a sound file. I guess there is some library/class out there, perhaps I could try out. Any suggestions? A: getID3() is a PHP script that extracts useful information from MP3s & other multimedia file formats. Last updated Aug. O8 Sourceforge Directory http://sourceforge.net/projects/getid3/files/getID3%28%29%201.x/ Another good one at PHP Audio Formats Manipulation Edit : getID3 works amazingly well. Test Shot
{ "language": "en", "url": "https://stackoverflow.com/questions/7622638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Libusb interrupt transfer callback I'am working on a real-time control system that calculates the control signals in a buffered fashion (a user-mode program) and outputs to the usb device the array through isochronous transfers. The usb device them reports the execution progress through interrupt transfer, so that pc software can then calculate and push the next control array. The software runs based on raw win32 api, C based. (C++ used only on not time sensitive parts of the program, such as interface, 3D models...). I would like to know if there is a way to register a callback function in response to a interrupt transfer? A: From what I understand, although we are talking about interrupt transfers, the USB device still has to be polled using libusb_interrupt_transfer: Interrupt transfers are typically non-periodic, small device "initiated" communication requiring bounded latency. An Interrupt request is queued by the device until the host polls the USB device asking for data. Excerpt from https://www.beyondlogic.org/usbnutshell/usb4.shtml#Interrupt
{ "language": "en", "url": "https://stackoverflow.com/questions/7622647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert SHA256 hash string to SHA256 hash object in Python I have a string which is a SHA256 hash, and I want to pass it to a Python script which will convert it to a SHA256 object. If I do this: my_hashed_string = // my hashed string here m = hashlib.SHA256() m.update( my_hashed_string ) it will just hash my hash. I don't want to hash twice...it's already been hashed. I just want python to parse my original hashed string as a hash object. How do I do this? A: Unfortunately the hash alone isn't enough info to reconstruct the hash object. The hash algorithm itself is temporal, depending on both internal structures and further input in order to generate hashes for subsequent input; the hash itself is only a small piece of the cross section of the algorithm's data, and cannot alone be used to generate hashes of additional data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get cell to the right of current month in Excel I'm pretty new to Excel, that question is probably easy, but I dont know what to do :-(. So this is what I have: Date Numbers 01.09.11 10 01.10.11 20 01.11.11 30 01.12.11 40 Now what I want is in another cell: Get the number of the date, where the date's month is the current month. How do I do this? A: Assuming all your dates are strings of the form "dd.mm.yy", you can use the following array formula: =INDEX(B1:B4,MATCH(9,VALUE(MID(A1:A4,4,2)),0)) where the 9 is the month number you want to look up. Enter this as an array formula by pressing Ctrl+Shift+Enter. EDIT: As pointed out in the comments, you want to match the current month, so incorporating @JMax's suggestion works: =INDEX(B1:B4,MATCH(MONTH(TODAY()),VALUE(MID(A1:A4,4,2)),0)) To clear up any confusion, MID() returns a string, which by itself will not return a match for the number value returned by MONTH(TODAY()). However, if you stick the MID() function inside a VALUE() function, the string returned by MID() will be converted into a number value. E.g., "09" becomes the number 9, "10" becomes the number 10. This allows you to match the number value returned by MONTH(TODAY()). However, if your dates are entered as dates with format dd.mm.yy in your sheet instead of as strings, then you can use the same strategy but with a different matching term: =INDEX(B1:B4,MATCH(MONTH(TODAY()),MONTH(A1:A4),0)) Enter this as an array formula.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSN Validation in MVC2 I have a business requirement where in i need to display SSN Field into three separate text boxes and if any one of the textbox is blank and user clicks save, I need to display a common error message on top of the SSN Field saying- "SSN is required field". I have added required field attribute on the view model on all these fields so i am getting three edit messages saying SSN is required. how to present only one edit in this case ? I am using ASP.NET MVC 2 My view model is like this [Required] SSN_FirstThreeDigits [Required] SSN_SecondTwoDigits [Required] SSN_ThirdFourDigits Any suggestions Thanks Subu A: SSNValidator.com now has an API for validating social security numbers. Data elements include whether or not the number was issued, approximate date of issuance, state of issuance and if it was used in a death claim. Go to the site and click the API/Batch Processing links for details. A: The Mvc.ValidationTookit Alpha Release: Conditional Validation with MVC 3 can do this. A: You may need a custom model binder. Please have a look at this article and see how he validates date of birth
{ "language": "en", "url": "https://stackoverflow.com/questions/7622652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: query on test files, branching and folder structure in in team foundation server recently i was embarking on new project. it is giving me this time try to make my tfs structure more solid put some betterment on my recent version. so here it s branch release trunk bin docs src sln.file project1 project2 tests sln.file project1.test project2.test since test projects will not be branched this make sense. however I was contemplating is it better to keep test projects within same sln. though it s my preference how can than I refer to them withing working dev solution. A: http://tfsbranchingguideiii.codeplex.com/ Also, I don't know what you call the "test projects", but if they change when your main code changes, then they should be branched with your main code. Here's a brief description of how I set up a small application recently. I have not yet moved larger larger applications, so haven't yet dealt with things like libraries of common code. $/TeamProject /Development (folder) /Development (branch) /Lib /Src etc. /Main (branch) /Lib [third party binaries and other artifacts] /Src /Solution1 Solution1.sln WebApplication WebApplication.csproj etc. WcfServices WcfServices.csproj etc. DAL DAL.csproj UnitTests UnitTests.csproj /Solution2 (same pattern as Solution1) /Release (folder) /Release (branch) /Lib /Src etc. * *I have a CI build set up for the Development branch, building the "Dev" configuration. We deploy it to our Integration environment. *I have the nightly build set up for our Main branch, building the "Test" configuration. When QA wants to test a new build, they deploy the latest of these to the QA environment. *I have a manual build set up for the Release branch, building the "Prod" configuration. When we're ready to migrate to production, QA first tests the deployment process in their environment (will be a staging environment once we get one), and then Operations deploys this to the Production environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I make a webpage display what platform and browser its being viewed in? I need a webpage to display if its being viewed on a PC/Mac, iphone, etc and also what browser its being run on. Anyone know how I would go about doing that? A: You typically get this information through the User-agent: HTTP header sent by your browser. If you were using PHP, you'd get this by reading $_SERVER['HTTP_USER_AGENT']. PHP also has a higher level [get_browser][1] API to read this data. If you're using another scripting language in your web app, you'll need to look up the equivalent. A: The easiest way is to use Javascript, and the easiest way to use Javascript is to use a library like jQuery. jQuery has .browser detection flags that'll give you what you're looking for. jQuery.support: browser-specific CAPABILITIES (preferred) jQuery.browser: browser identity (deprecated) NOTES: * *You can try to determine "browser type" on either the client (web browser) or the server (e.g. IIS or Apache; in .Net or PHP). *Simply reading "browser type" (e.g. from an http return variable) is quite often inaccurate. A better strategy is to "probe" for browser type, using different heuristics. jQuery simplifies this for you. *A better strategy still is to determine browser CAPABILITIES, rather than "browser type". jQuery simplifies this, too. 'Hope that helps! A: You can do it using server-side code if the page is dynamically generated. For example, if you're using PHP you can use the get_browser() function. Other language should have similar capabilities, via the User-Agent header sent by the browser. You can also do it client-side in Javascript. Some details on this process can be found here: http://www.quirksmode.org/js/detect.html A: I think this is what you need! http://plugins.jquery.com/plugin-tags/useragent http://jasonlau.biz/userinfo/test1.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7622656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generics & Types I am using generics in a certain data structure. I have to store int x, int y, and Value value, where value is the generic type. I am trying to group all those in one object called NodeData and then in another class, create an ArrayList of NodeData's, (so each element in the array list will include hold an x, y and value. My NodeData is as follows: public class NodeData<Value> { private int x; private int y; private Value value; In another class, the array list instantiated as follows: ArrayList<NodeData> items = new ArrayList<NodeData>();. I am getting an error for the array list which says: NodeData is a raw type. References to NodeData<Value> should be parametrized. Why is that? NodeData is already parametrized as NodeData<Value>. Thanks A: Not in your array declaration. Try it like this: List<NodeData<Foo>> list = new ArrayList<NodeData<Foo>>(); where Foo is the Value type you want for that instance. A: In the other class, You'll have to specify the type you intend to use in place of the generic type Value eg. ArrayList<NodeData<String>> items = new ArrayList<NodeData<String>>();.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What can my models bind to when a collection is reset? Are there any events my models can bind to, to know their collection has been reset? When I call: collection.reset() I want those removed models to be destroyed and in turn any views to know they are gone. What should I bind to here? A: From the fine manual: reset collection.reset(models, [options]) [...] triggering a single "reset" event at the end. So bind to the collection's reset event and hope that no one uses the {silent: true} option to do things behind your back. A: @mu's answer is correct, but you might also need to know that a model that is added to a collection has the .collection property, which points to the parent collection. So if you are instantiating your models manually, you can just do this: var myModel = new MyModel(); collection.add(myModel); collection.bind('reset', model.cleanUp(), model); But if you're instantiating your models via the collection, e.g. with collection.fetch(), you need to bind to the collection in the initialize() method of the model: var MyModel = Backbone.Model.extend({ initialize: function() { if (this.collection) { this.collection.bind('reset', this.cleanUp(), this); } } // etc });
{ "language": "en", "url": "https://stackoverflow.com/questions/7622661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate sun-web.xml for a Java Web Application using NetBeans? The title says it all. Is there any plugin for NetBeans 7.0 to generate sun-web.xml in a web project? If yes, please let me know. A: Yo do not need to install any plugin: * *Go to File > New Files > XML > XML Document from menu. *In the first wizard form enter "sun-xml" as file name. *In Document Type wizard form select DTD-Constrained Document radio button *in the DTD Options wizard enter following information: DTD Public ID: -//Sun Microsystems, Inc.//DTD GlassFish Application Server 3.0 Servlet//EN DTD System ID: http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd Document Root: sun-web-app *Finally click on the finish button. You have to know that glassfish-web.xml is the new name for sun-web.xml and for GlassFish server versions older than 3.1, this file is called sun-web.xml. You can create glassfish-web.xml using: File > New Files > GlassFish > GlassFish Descriptor
{ "language": "en", "url": "https://stackoverflow.com/questions/7622663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Network communication between C# server and JAVA client: how to handle that. transition? I have a C# server that cannot be altered. In C#, a byte ranges fom 0 - 255, while in JAVA it ranges from -128 to 127. I have read about the problem with unsigned byte/ints/etc and the only real option as I have found out is to use "more memory" to represent the unsigned thing: http://darksleep.com/player/JavaAndUnsignedTypes.html Is that really true? So when having network communication between the JAVA client and the C# server, the JAVA client receives byte arrays from the server. The server sends them "as unsigned" but when received they will be interpreted as signed bytes, right? Do I then have to typecast each byte into an Int and then add 127 to each of them? I'm not sure here... but how do I interpret it back to the same values (int, strings etc) as I had on the C# server? I find this whole situation extremely messy (not to mention the endianess-problems, but that's for another post). A: A byte is 0-255 in C#, not 0-254. However, you really don't need to worry in most cases - basically in both C# and Java, a byte is 8 bits. If you send a byte array from C#, you'll receive the same bits in Java and vice versa. If you then convert parts of that byte array to 32-bit integers, strings etc, it'll all work fine. The signed-ness of bytes in Java is almost always irrelevant - it's only if you treat them numerically that it's a problem. What's more of a problem is the potential for different endianness when (say) converting a 32-bit integer into 4 bytes in Java and then reading the data in C# or vice versa. You'd have to give more information about what you're trying to do in order for us to help you there. In particular do you already have a protocol that you need to adhere to? If so, that pretty much decides what you need to do - and how hard it will be depends on what the protocol is. If you get to choose the protocol, you may wish to use a platform-independent serialization format such as Protocol Buffers which is available for both .NET and Java. A: Unfortunately, yes ... the answer is to "use more memory", at least on some level. You can store the data as a byte array in java, but when you need to use that data numerically you'll need to move up to an int and add 256 to negative values. A bitwise & will do this for you quickly and efficiently. int foo; if (byte[3] < 0) foo = (byte[3] & 0xFF); else foo = byte[3];
{ "language": "en", "url": "https://stackoverflow.com/questions/7622665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }