text
stringlengths
8
267k
meta
dict
Q: Where can I download Jai and Jai-imageio? I need to get the pixel color of a TIFF image, if you know any alternatives to Jai and Jai-imageio please let me know. A: Here you go: http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-java-client-419417.html Maybe this is interessting, too. I saw they provide some extensions: http://java.net/projects/imageio I know about Sanselan and ImageJ, too, but do not know if and how they give you the ability to read the pixelcolor. But as long as you can get a BufferedImage in Java you should be able to do what is needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "133" }
Q: Loading Local PDF File Into WebView I am attempting to put the following functionality into an iOS app I am writing: * *Ship a set of PDFs in the resources folder of the project in XCode *Copy the PDFs to the app directory *Open the PDF in a webview. As far as I can see, the first two steps work ok (I've used FileManager to check fileExistsAtPath after the copy operation). However, the webview is empty, and is erroring out ("the requested URL does not exist on server"). My code for the file open is as follows: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *localDocumentsDirectory = [paths objectAtIndex:0]; NSString *pdfFileName = @"example.pdf"; NSString *localDocumentsDirectoryPdfFilePath = [localDocumentsDirectory stringByAppendingPathComponent:pdfFileName]; pdfUrl = [NSURL fileURLWithPath:localDocumentsDirectoryPdfFilePath]; [webView loadRequest:[NSURLRequestWithURL:pdfUrl]; This works fine on the simulator, but doesn't work on the device A: Are you sure you don't want to let the UIDocumentInteractionController do the heavy lifting for you? UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:fileURL]; dc.delegate = self; [dc presentPreviewAnimated:YES]; A: As posted by Anna Karenina above, "The device is case-sensitive. Make sure the filename matches exactly" A: As bshirley suggested UIDocumentInteractionController is a great option to present your PDF. Initially I tried using the 3rd party JSQWebViewController but I was getting a blank screen on device while on simulator it was working. UIDocumentInteractionController worked great for me! For Swift you can do: let interactionController = UIDocumentInteractionController(url: fileURL) interactionController.delegate = self interactionController.presentPreview(animated: true) and implement the delegate method: // Mark: UIDocumentInteractionControllerDelegate func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return UIApplication.shared.keyWindow!.rootViewController! }
{ "language": "en", "url": "https://stackoverflow.com/questions/7502189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to keep properties of separate collections in sync? I have a WPF application with a screen containing a tab control with two tabs. On each tab is a datagrid, each one bound to an ObservableCollection of Part objects. The part has a few "quantity" properties, which need to be synchronized between the grids. For example, if the user changes the quantity of partABC on grid1, partABC either needs to be added to grid2 with the same quantity, or if grid2 already contains partABC, then its quantity must be changed to reflect grid1. My problem is that this must work in both directions. If I set a PropertyChanged handler on every part in both grids, I end up with an infinite loop as they constantly update each other's quantities. Up until now, I was handling this during the tab control selection changed event, just iterating through one of the lists and setting quantities one-by-one. This worked well enough until I realized that the users could potentially add thousands of parts to their lists, and at that point this process takes an unacceptable amount of time to complete (around 25 seconds for 4500 part objects). edit The first grid contains every part in the database, serving as sort of a "pick-list" where users simply scroll to the part they are looking for and enter quantities. The second grid contains only parts which have been manually entered by the user, in the event that they prefer to type in the numbers of the parts they want. Grid2 is always a subset of grid1. A: You can accomplish this through databinding. You should not create duplicate Part objects. Instead duplicate the collections that hold the parts. Part sharedPart = new Part(); Part onlyInTabA = new Part(); Part onlyInTabB = new Part(); ObservableCollection<Part> tabAParts = new ObservableCollection<Part>() { sharedPart, onlyinTabA }; ObservableCollection<Part> tabBParts = new ObservableCollection<Part>() { sharedPar, onlyInTabB }; Now use tabAParts to databind to the grid on tab A and tabBParts to databind to the grid on tab B If your Part class implements INotifyPropertyChanged then changing a property of sharedPart will update both grids on both tabs. When you add a new part you can choose to make it shared (add it to both collections) or to keep it tab-specific
{ "language": "en", "url": "https://stackoverflow.com/questions/7502192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Axis2 : When to use Wsdd file with Axis2 Webservices I am using Axis2 for developing webservices . I started from WSDL file , and used WSDL2Java command line and generated all the sever related code (Skeltons) , wrote services.xml file , modified the skelton ( Implemented business logic in it ) and deployed as .aar file inside the Services folder of Axis2.war . Now my question is I have seen some examples using .wsdd file with Axis2 Webservices , i am really confused with this , please tell me do we need .wsdd file ?? A: Axis2 uses services.xml as the descriptor file. A: You do not need to have .wsdd files with Axis2 - its been used in Axis.. A: In Axis 1 we use wsdd file. While in Axis2 we use services.xml or sun-jaxws.xml file. A: You don't want .wsdd file in Axis2 , To understand the migration from Axis 1.x to Axis2 and the improvements in Axis2 in comparison with Axis1 visit Apache Axis article : https://axis.apache.org/axis2/java/core/docs/migration.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7502194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: utf8 filenames and greek chars I'm trying to figure this out but I'm quite puzzled at the mo. I have a directory in my website containing pdf files with greek filenames (ie ΤΙΜΟΚΑΤΑΛΟΓΟΣ.pdf) I want to have links for the files on a web page so that users can open or save the files. So far I can list the files ok but if I click on them I get a 404 error. It's as if the server thinks they're not there although they are. I understand it's problably an encoding issue but beyond that I'm not sure what to look for. The website encoding is utf-8 and in order to display the filenames correctly I had to use mb_convert_encoding($file->filename, 'utf8', 'iso-8859-7'). This is the url: http://www.med4u.gr/timokatalogoi/ This is the directory listing: http://www.med4u.gr/pricelists/ The site is based on Joomla and it's hosted on a linux server. Any ideas? A: ISO-8859-* MUST DIE! (That's not personal!) Do everything in UTF-8. Everything. With good reason, some of us get upset when we see them being used, especially Latin-1 (8859-1) which bites a lot of people. I think you would find it very helpful to just dump them and move on to UTF-8. Things to check: * *Store your files encoded in UTF-8: Usually no difficulties with that. *Make sure your server is sending the files with UTF-8 charset: add header('Content-Type: text/html;charset=UTF-8'); near the top of your PHP. *Just in case someone saves your page, it's helpful in that case to put the same thing in a <meta> tag in the head. *Check it all in your browser: right click, view page info, and make sure the encoding is right. CPanel is very flexible, so that's all doable without much fuss. Feel free to comment if you want more detail. If you have a database, there are a few more hoops to jump through, but it's worth it. With UTF-8 you never have to worry, and it's the definitive, future-proof way of doing things. A: Let's suppose for the sake of argument that the file name on disk is aa.pdf but your conversion displays it as ab.pdf. You need either to revert the conversion so it points back to aa.pdf, or teach the server to remap or redirect requests for ab.pdf to this file. Or if you prefer, rename the file to ab.pdf instead, if your file system can handle this name. A: It's definitely an encoding problem. You'll need to escape the URL, or convert it to whatever character set your server recognises. e.g. 'ΤΙΜΟΚΑΤΑΛΟΓΟΣ LASER.pdf' in iso-8859-7 = 'ÔÉÌÏÊÁÔÁËÏÃÏÓ LASER.pdf' in iso-8859-1
{ "language": "en", "url": "https://stackoverflow.com/questions/7502198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to enable macros once in Excel 2007 I have a excel 2007 macro-enabled file (xlsm) that I want to share with a lot of users, but it requires enabling macros each time the spreadsheet is opened. I know that you can change the macro settings to "enable all macros" and put the spreadsheet in a trusted location. I'm looking for a more user-friendly to do this. I'm trying to to see if there is another option before having to digitally sign the code. Office 2010 looks like it will remember that you enable macros. Most of our users have 2007 though. A: Probably just do what you said, digitally sign, or put in trusted location. You could also create a executable program that opens the workbook that suppresses the macro warning when opening the workbook. Really, there aren't any "friendly" ways of doing this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Core Data Predicate a Many to Many relationship for sectionNameKeyPath reoccurrence I have a Core Data model that looks like this… Event <<-------->> Date The idea being that an Event can have many Dates and a Date can have many Events. I need my tableview to list Events with SectionHeaders displaying the Dates. My issue is that I don't know how to set this up so that an Event can reoccur each time a new date is displayed in the SectionHeader. When I setup my Predicate to collect all the Dates for each Event it does not allow for a duplication of the event when setting the sectionNameKeyPath on the FRC. A: Instead of a many to many relationship, wouldn't it make sense to just have a date property of your event object, and just look up all events for a particular date? I'd imagine this is possible using NSPredicate. The minor downside is you'd have to have an entry for each reoccurring event and modify all of them when one is changed. On the upside this is functionally beneficial as it allows users to modify individual events in series, or cancel / delete an event without effecting the rest in the series. A: Jim, The NSFetchedResultsController is restricted to just a single entity. Hence, many complex queries are not possible or require complex queries using sub-queries. In my experience, unless your data model fits into this narrow design, then you'll have trouble. I retreat to listening for the context did save notification and processing the objects that change or are inserted directly. Andrew
{ "language": "en", "url": "https://stackoverflow.com/questions/7502203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I package a jar with Maven and include some dependencies in WEB-INF/lib? How can I package a jar with Maven and include some dependencies in WEB-INF/lib? I tried with assembly, but cannot be achieved easier? A: Try using the jar-with-dependencies feature of the maven-assembly-plugin: <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2.1</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> This will incorporate all dependencies into your jar. Mark the dependencies that you don't want included in your jar with <scope>provided</scope>, eg: <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.4</version> <scope>provided</scope> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/7502204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Best way to get a files mime typein PHP What is the best way to get the mime type of a file? Before any answers are given, here are a list of a few things to consider. * *Can't rely on upload form for accuracy *Fileinfo has been inaccurate in 5.3 with testing *mime_content_type has been inaccurate with test like FileInfo *This goes beyond just image types so getImageSize() is not a viable option. Could this also be an apache/server/pear thing and not just rely on php functions? A: Sad to say, there is no perfect way to do so in any programming language. The 2 most standard way to get the minetype is * *Determine from the file extension... So something.jpg is a jpeg file and something.doc is a word document. *Determine from the magic string in the file... so if the first 2 bytes of the file is 0xFF 0xD8, it's a jpeg file. and a office document begins with 0xD0 0xCF 0x11 0xE0. Both ways have pros and cons. I can upload a exe file, but have it named with the extension of ".jpg" to defeat the first way or determining mime type. And for both types, I basically need a large database to search from so that i can tell what mimetype the file belongs to. However, if you are only interested in determining the mimetype for a few types of files. (Maybe just jpg, png, gif, etc), then the best way (imho) would be way number 2. Just keep a database or array of all the magic strings, and test the file against that. It is easy to get the magic strings, just Google.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trouble executing JQuery Flot from CGI script I'm currently testing a webservice on my local machine using Apache (on Windows XP). I have a Python CGI script that calls the services and generates html output that can be viewed in a browser. I recently came across Flot, which would enable me to plot my web service results. So, I downloaded all the Flot libraries and dumped them into my Apache directory. Everything seemed fine, because I was able to view the Flot examples successfully. Unfortunately, when I try to generate similar html from my CGI script, the javascript seems to not execute. However, if I take the html created by the CGI script and save it with a *.html extension, then reload it in the browser...it works. Has anybody come across a similar problem? Do my Apache settings/configuration need to be adjust to allows JQuery to execute? A: I figured it out... the problem was that the javascript libraries had to be put in the 'htdocs' folder. Then, the javascript path in the html had to be adjusted such that it is relative to the 'htdocs' directory. e.g. <script language="javascript" type="text/javascript" src="/js/jquery.flot.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7502212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing with id and handle in Rails I'm trying to set up rails to use both the ID and the Handle (which is just an URL safe version of the title) of a blog post in the route. match '/articles/:id/:handle', :to => 'articles#show' resources :articles This works, of course -- but I can't seem to set up the to_param method in the model os the longer URL -- with the handle attached, is the default. This doesn't work (not that I really expected it to): def to_param "#{id}/#{handle}" end I get a No route matches {:action=>"edit", :controller=>"articles", error. I also tried just using the handle, but then Rails generates links to the resource just using the handle and not the ID. I know I can do it with a - in stead of a /, but I prefer the /. Any way to make this work? If I have to add some extra paremeters to my link_to helpers, that's okay. A: Did you try to pass a Hash to link_to? link_to "Link", {:id => @article.id, :handle => @article.handle} Update You have to modify your routes: match '/articles/:id/:handle', :to => 'articles#show', :as => :article_with_handle and use the following helper to generate the link: link_to "Link", article_with_handle_path(:id => @article.id, :handle => @article.handle) You can override the helper to simplify things: def article_with_handle_path(article) super(:id => article.id, :handle => article.handle) end and use it like this: link_to "Link", article_with_handle_path(@article) A: Okay, here's what I did to remove the query string problem from the answer above: Changed the route to this: match '/articles/:id/:handle' => 'articles#show', :as => :handle Removed the to_param method from the model and then generated the link like this: link_to 'Show', handle_path(:handle => article.handle, :id => article.id) %> That works, but could be condensed, obviously, with the helper above. Just change the one line to: args[1] = handle_path(:id => args[1].id, :handle => args[1].handle)
{ "language": "en", "url": "https://stackoverflow.com/questions/7502214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the best way to count MySQL records I have a search engine on a shared host that uses MySQL. This search engine potentially has millions/trillions etc of records. Each time a search is performed I return a count of the records that can then be used for pagination purposes. The count tells you how many results there are in regard to the search performed. MySQL count is I believe considered quite slow. Order of search queries: * *Search executed and results returned *Count query executed I don't perform a PHP count as this will be far slower in larger data sets. Question is, do I need to worry about MySQL "count" and at what stage should I worry about it. How do the big search engines perform this task? A: In almost all cases the answer is indexing. The larger your database gets the more important it is to have a well designed and optimized indexing strategy. The importance of indexing on a large database can not be overstated. You are absolutely right about not looping in code to count DB records. Your RDBMS is optimized for operations like that, your programming language is no. Wherever possible you want to do any sorting, grouping, counting, filtering operations within the SQL language provided by your RDBMS. As for efficiently getting the count on a "paginated" query that uses a LIMIT clause, check out SQL_CALC_FOUND_ROWS. SQL_CALC_FOUND_ROWS tells MySQL to calculate how many rows there would be in the result set, disregarding any LIMIT clause. The number of rows can then be retrieved with SELECT FOUND_ROWS(). See Section 11.13, “Information Functions”. A: If MySQL database reaches several millions of records, that's a sign you'll be forced to stop using monolithic data store - meaning you'll have to split reads, writes and most likely use a different storage engine than the default one. Once that happens, you'll stop using the actual count of the rows and you'll start using the estimate, cache the search results and so on in order to alleviate the work on the database. Even Google uses caching and displays an estimate of number of records. Anyway, for now, you've got 2 options: 1 - Run 2 queries, one to retrieve the data and the other one where you use COUNT() to get the number of rows. 2 - Use SQL_CALC_FOUND_ROWS like @JohnFX suggested. Percona has an article about what's faster, tho it might be outdated now. The biggest problem you're facing is the way MySQL uses LIMIT OFFSET, which means you probably won't like your users using large offset numbers. In case you indeed get millions of records - I don't forsee a bright future for your MySQL monolithic storage on a shared server. However, good luck to you and your project. A: If I understand what you are trying to do properly, you can execute the one query, and perform the mysql_num_rows() function on the result in PHP... that should be pretty zippy. http://php.net/manual/en/function.mysql-num-rows.php A: Since you're using PHP, you could use the mysql_num_rows method to tell you the count after the query is done. See here: http://www.php.net/manual/en/function.mysql-num-rows.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7502216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Delphi map database table as class A friend of mine asked me how he can at runtime to create a class to 'map' a database table. He is using ADO to connect to the database. My answer was that he can fill an ADOQuery with a 'select first row from table_name', set the connection to database, open the query, and after that by using a cycle on the ADOQuery.Fields he can get FieldName and FieldType of all the fields from the table. In this way he can have all the fields from the table and their type as members of the class. There are other solutions to his problem? A: @RBA, one way is to define the properties of the class you want to map as "published", then use RTTI to cycle through properties and assign the dataset rows to each property. Example: TMyClass = class private FName: string; FAge: Integer; published property Name: string read FName write FName; property Age: Integer read FAge write FAge; end; Now, do a query: myQuery.Sql.Text := 'select * from customers'; myQuery.Open; while not myQuery.Eof do begin myInstance := TMyClass.create; for I := 0 to myQuery.Fields.Count - 1 do SetPropValue(myInstance, myQuery.Fields[I].FieldName, myQuery.Fields[I].Value); // now add myInstance to a TObjectList, for example myObjectList.Add(myInstance); Next; end; This simple example only works if all fields returned by the query have an exact match in the class. A more polished example (up to you) should first get a list of properties in the class, then check if the returned field exists in the class. Hope this helps, Leonardo. A: Not a real class, but something quite similar. Sometime ago I blogged about a solution that might fit into your needs here. It uses an invokeable custom variant for the field mapping that lets you access the fields like properties of a class. The Delphi Help can be found here and the two part blog post is here and here. The source code can be found in CodeCentral 25386 A: This is what is called ORM. That is, Object-relational mapping. You have several ORM frameworks available for Delphi. See for instance this SO question. Of course, don't forget to look at our little mORMot for Delphi 6 up to XE2 - it is able to connect to any database using directly OleDB (without the ADO layer) or other providers. There is a lot of documentation available (more than 600 pages), including general design and architecture aspects. For example, with mORMot, a database Baby Table is defined in Delphi code as: /// some enumeration // - will be written as 'Female' or 'Male' in our UI Grid // - will be stored as its ordinal value, i.e. 0 for sFemale, 1 for sMale TSex = (sFemale, sMale); /// table used for the Babies queries TSQLBaby = class(TSQLRecord)   private     fName: RawUTF8;     fAddress: RawUTF8;     fBirthDate: TDateTime;     fSex: TSex;   published     property Name: RawUTF8 read fName write fName;     property Address: RawUTF8 read fAddress write fAddress;     property BirthDate: TDateTime read fBirthDate write fBirthDate;     property Sex: TSex read fSex write fSex; end; By adding this TSQLBaby class to a TSQLModel instance, common for both Client and Server, the corresponding Baby table is created by the Framework in the database engine. Then the objects are available on both client and server side, via a RESTful link (over HTTP, using JSON for transmission). All SQL work ('CREATE TABLE ...') is done by the framework. Just code in Pascal, and all is done for you. Even the needed indexes will be created by the ORM. And you won't miss any ' or ; in your SQL query any more. My advice is not to start writing your own ORM from scratch. If you just want to map some DB tables with objects, you can do it easily. But the more time you'll spend on it, the more complex your solution will become, and you'll definitively reinvent the wheel! So for a small application, this is a good idea. For an application which may grow in the future, consider using an existing (and still maintained) ORM. A: Code generation tools such as those used in O/RM solutions can build the classes for you (these are called many things, but I call them Models). It's not entirely clear what you need (having read your comments as well), but you can use these tools to build whatever it is, not just models. You can build classes that contain lists of field / property associations, or database schema flags, such as "Field X <--> Primary Key Flag", etc. There are some out there already, but if you want to build an entire O/RM yourself, you can (I did). But that is a much bigger question :) It generally involves adding the generation of code which knows how to query, insert, delete and update your models in the database (called CRUD methods). It's not hard to do, but then you take away your ability to integrate with Delphi's data controls and you'll have to work out a solution for that. Although you don't have to generate CRUD methods, the CRUD support is needed to fully eliminate the need for manual changes to adapt to database schema changes later on. One of your comments indicated you want to do some schema querying without using the database connection. Is that right? I do this in my models by decorating them with attributes that I can query at runtime. This requires Delphi 2010 and its new RTTI. For example: [TPrimaryKey] [TField('EmployeeID', TFieldType.Integer)] property EmployeeID: integer read GetEmployeeID write SetEmployeeID; Using RTTI, I can take an instance of a model and ask which field represents the primary key by looking for the one that has the TPrimaryKeyAttribute attribute. Using the TField attribute above provides a link between the property and a database field where they do not have to have the same name. It could even provide a conversion class as a parameter, so that they need not have the same type. There are many possibilities. I use MyGeneration and write my own templates for this. It's easy and opens up a whole world of possibilities for you, even outside of O/RM. MyGeneration (free code generation tool) http://www.mygenerationsoftware.com/ http://sourceforge.net/projects/mygeneration/ MyGeneration tutorial (my blog) http://interactiveasp.net/blogs/spgilmore/archive/2009/12/03/getting-started-with-mygeneration-a-primer-and-tutorial.aspx I've taken about 15 mins to write a MyGeneration script that does what you want it to. You'll have to define your Delphi types for the database you're using in the XML, but this script will do the rest. I haven't tested it, and it will probably want to expand it, but it will give you an idea of what you're up against. <%# reference assembly = "System.Text"%><% public class GeneratedTemplate : DotNetScriptTemplate { public GeneratedTemplate(ZeusContext context) : base(context) {} private string Tab() { return Tab(1); } private string Tab(int tabCount) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int j = 0; j < 1; j++) sb.Append(" "); // Two spaces return sb.ToString(); } //--------------------------------------------------- // Render() is where you want to write your logic //--------------------------------------------------- public override void Render() { IDatabase db = MyMeta.Databases[0]; %>unit ModelsUnit; interface uses SysUtils; type <% foreach (ITable table in db.Tables) { %> <%=Tab()%>T<%=table.Name%>Model = class(TObject) <%=Tab()%>protected <% foreach (IColumn col in table.Columns) { %><%=Tab()%><%=Tab()%>f<%=col.Name%>: <%=col.LanguageType%>; <% }%> <%=Tab()%>public <% foreach (IColumn col in table.Columns) { %><%=Tab()%><%=Tab()%>property <%=col.Name%>: <%=col.LanguageType%> read f<%=col.Name%> write f<%=col.Name%>; <% }%> <%=Tab()%><%=Tab()%> <%=Tab()%>end;<% } %> implementation end. <% } } %> Here is one of the table classes that was generated by the script above: TLOCATIONModel = class(TObject) protected fLOCATIONID: integer; fCITY: string; fPROVINCE: string; public property LOCATIONID: integer read fLOCATIONID write fLOCATIONID; property CITY: string read fCITY write fCITY; property PROVINCE: string read fPROVINCE write fPROVINCE; end; A: Depending on the database, you could query the INFORMATION_SCHEMA tables/views for what you need. I've done this in an architecture I created and still use in DB applications. When first connecting to a database it queries "data dictionary" type information and stores it for use by the application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: DefaultIfEmpty() Causing "System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable'" Scenario: I have a table of User Profiles and a table of Colleagues. The colleagues table has a record for ever other user that a User Profile is following. In this query, I am grabbing all of the people who are following the current logged in user (getting their Record IDs from the Colleagues table and joining the User Profile table to get their details). Then, I am joining the Colleagues table again to see if the logged in user is following that user back. Issue: It is my understanding that the best way to do a LEFT JOIN (in looking for the colleague record where the user is following the colleague back) is to add "DefaultIfEmpty()" to that join. When I add .DefaultIFEmpty() to that join, I get the following error message: System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable' If I remove the ".DefaultIFEmpty()" from that join, it works. However, it runs it as a regular JOIN, leaving out records where the user is not following the colleague back. Code: Here is the code I am using: var results = (from a1 in db.Colleague join b1 in db.UserProfile on new {ColleagueId = a1.ColleagueId} equals new {ColleagueId = b1.RecordId} join d1 in db.UserProfile on new {RecordId = a1.OwnerId} equals new {RecordId = d1.RecordId} join c1 in db.Colleague on new {OwnerId = b1.RecordId, Ignored = false, ColleagueId = a1.OwnerId} equals new {c1.OwnerId, c1.Ignored, c1.ColleagueId} into c1Join from c1 in c1Join.DefaultIfEmpty() // This is the .DefaultIfEmpty() breaking the query where b1.AccountName == userName && a1.Ignored == false orderby b1.LastName select new { RecordId = (System.Int64?) d1.RecordId, d1.AccountName, d1.PreferredName, d1.FirstName, d1.LastName, d1.PictureUrl, d1.PublicUrl, IsFollowing = c1.OwnerId < 1 ? 0 : 1 }); foreach (var result in results) // This is what throws the error { // Do stuff } Any ideas? A: The SQL Provider for Entity Framework in version 3.5 of the .NET framework does not support DefaultIfEmpty(). Sorry, but could not find a better reference than this article: http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/ You might want to try straight LINQ-to-SQL rather than ADO.NET Entity Framework. I believe that it works in LINQ-to-SQL. I've verified in the past that left joins work in 3.5 via LinqPad. A: DefaultIfEmpty is supported only in EFv4+. First version of EF doesn't support DefaultInEmpty. A: It looks like you need to create a default value to pass into DefaultIfEmpty(), since DefaultIsEmpty() takes a parameter. DefaultIfEmpty() on MSDN
{ "language": "en", "url": "https://stackoverflow.com/questions/7502220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OS X Lion Server - Apache Question - index.html.en I've added some additional sites to my apache config today, however the default document root should serve the "It Works" index.html.en apache default page. However I must of altered something by accident as it now displays the directory listing by default instead? If I navigate to index.html.en it successfully loads, but not by default when I enter 127.0.0.1 for example. I'm sure the .en language files are resolved by httpd-languages.conf, I have doubled checked that files dependancies are included in httpd.conf 'mod_mime' & 'mod_negotiation'. The problem shouldn't bother me to much but I would like to discover the cause if possible? A: Specify your DirectoryIndex by putting: DirectoryIndex index.html.en in httpd.conf or .htaccess files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to handle large amounts of static text, images when creating pdf using iText We are going to use iText to create a large report. There will be a lot of static text and images that will be the same for every report. We will then insert dynamic data from a database into the report. The static data and the dynamic data will be mixed together when the report is finished. What is the best way to handle the static data. We are going to use a java servlet in a web application for the creation of the report. We want the report to be sent to the web page immediately, so performance is critical. These are some of the ideas I had. Not sure if any of these are good ideas. 1.) Create a PDF with the static content then insert the dynamic data. If I go this way how would I know where to insert the dynamic data? Is it possible to bookmark place to insert data? 2.) Get the static data from a database. This seems like it would be difficult trying to design a database with static content that would have to consider things like pages, paragraphs, headings, images. I would also think that this would not be great for performance if the website gets hit hard. 3.) Cache the static content in the servlet context. This would seem to help performance but would still have the same design issues as the database. I would love some opinions on the best way to store large amounts of static text when creatig a PDF using iText. Thanks for your help Doug A: I am not sure if the best way to do it, but this worked well for me in a similar situation, I created a template file that I read into code, and in the template I had hash tagged variable holders that I used to find a location and replace with dynamic text from whatever source. For example: Hello #CUSTOMER_NAME#, Thank you for the purchase of #RECENT_PURCHASES# on #RECEIPT_DATE#, for a total value of #RECEIPT_TOTAL#. ... Like I said, it probably isn't ideal, but it really well for my needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding Hours to DateTimePicker in VS2010 How to add 3 hours in DateTimePicker in VS? Dim dateAdd as Date = DateTimePicker1 dateAdd.AddHours(3) MsgBox(dateAdd.Value.ToString) Why does it doesn't add on my system? A: DateTime.AddHours() returns a new DateTime: Dim dateAdd as Date = DateTimePicker1 Dim newDate as Date = dateAdd.AddHours(3) MsgBox(newDate.Value.ToString)
{ "language": "en", "url": "https://stackoverflow.com/questions/7502234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Request["__EVENTTARGET"] call killing page lifecycle This one is absolutely bizzare. Alarm bells are probably ringing as to why I am inspecting this property, and probably indicates to you that I am trying to do something "out of step" or circumventing the ASP.NET Page LifeCycle's prescribed event management. I am using a Wizard in a quite a nested hierarchy and within an update panel. Wizards, if you dont already know, require initialisation/loading of all of the Wizard step controls upfront. I am trying to do something a bit quirky (not exactly super quirky) in that I am trying to dynamically load Wizards based on a user choice. Now this works, but has required a bit of shoe horning. Anyway, the situation arises where retrieving user input to see what wizard they would like to use, means that the wizard are 'inited' "before" i can get at the choice they have made (by way of drop down or button) I look it up earlier than the prescribed framework intends the values to be looked up to do some necessary initialisation in the page init event (as mentioned before, a requirement for using Wizards and the Wizard steps they comprise of). Anyway I have swapped this from just a drop down, to a drop down and a button and need to see which one is clicked. The call to Request["__EVENTTARGET"] makes the rest of the page processing, not work. I suppose I should roll my own DynamicWizard control? A: Is Request["__EVENTTARGET"] equal to null? That may be because regular buttons don't populate the __EVENTTARGET hidden field (they don't have to). You can change that by setting UseSubmitBehavior to false for the button. <asp:Button ID="SelectWizard" runat="server" Text="Select" UseSubmitBehavior="false" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7502235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python, mutable object as default argument, is there any way to solve? class A: def __init__(self, n=[0]): self.data = n a = A() print a.data[0] #print 0 a.data[0] +=1 b = A() print a.data[0] #print 1, desired output is 0 In the case above, is there any way to provide a default argument with the mutable object (such as list or class) in __init__() class A, but b is not affected by the operation a? A: You could try this: class A: def __init__(self, n=None): if n is None: n = [0] self.data = n Which avoids the biggest problem you're facing here, that is, that's the same list for every single object of your type "A." A: One possibility is: class A: def __init__(self, n=None): if n is None: n = [0] self.data = n A: Also: class A: def __init__(self, n=[0]): print id(n) self.data = n[:] print id(self.data) del n a = A() print a.data[0] #prints 0 a.data[0] +=1 print a.data[0] #prints 1 print b = A() print b.data[0] #prints desired output 0 The principle is that it creates another list. If a long list is passed as argument, there will be two long list in memory. So the inconvenience is that it creates another list.... That's why I delete n. Don't think it's better, but it may give you comprehension of what happens
{ "language": "en", "url": "https://stackoverflow.com/questions/7502238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: is there an instance of class in use? I've caused a circular loop between a class and it's parent class. The only way I can think of to fix the problem is to test if there are instances of the child class in use. Is there anyway to test for that? So I took a break and came back the issue. The loop was caused by the __construct method in a class that deals with routing input to the appropriate logic. This class is then inherited by other classes so that if I need to do something automatically that would normally be done by the user I can implement it easily. What I didn't see happening was that each time a child class was called, this constructor was activated to reroute the user to the right code. Since the input was identical, it was sent back to child class, setting up the loop. I have solved the issue by taking out the constructor and calling the methods needed in the site index instead, so that child classes, no longer attempt to call themselves. A: Well, you should adjust your code to avoid the loop. It sounds like a bad thing what you did and it's likely to cause troubles in the future. So my suggestion is to redesign your code so you avoid the loop instead of fixing it. A: You could use instanceof to check if it's an instance of a class. Or is_subclass_of to check if it extends a class. If you post your code maybe someone can suggest a better design, the loop can probably be avoided.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java casting ".class"-operator used on a generic type, e.g. List, to "Class>" and to "Class>" I use the .class-operator to supply information about the contained type to a generic class. For non-generic contained types, e.g. Integer.class, this works without any problems. But with the contained type being a generic, e.g. List<Integer>.class or List.class it results in compile time errors about class casting. There is a way to circumvent the errors, but I'm curious about what is happening here. Can someone explain what is happening?, why things are as they are?, and what the best way to circumvent the problem is? The following lines demonstrate the problem: Note the outer generic type expects Class<T> as parameter, so in this case Class<List<Integer>>. Class<Integer> tInt = Integer.class; // Works as expected. Class<List> tList = List.class; // Works with warning, but is not // what i'm looking for. Class<List<Integer>> tListInt1 = List.class; // Error Class<List<Integer>> tListInt2 = (Class<List<Integer>>) List.class; // Error Class<List<?>> tListGeneric = (Class<List<Integer>>) List.class; // Error The next line works: Class<List<Integer>> tListInt3 = (Class<List<Integer>>) ((Class<Integer>)List.class); Why do the declarations of tListInt2 and tListGeneric give and error? Why does upcast and then downcast with tListInt3 not produce an error? Is there a better way to declare tListInt3? With kind regards, Kasper van den Berg ps. Let me know if you like to see code the outer generic container that needs this type information; i'll post it if needed. A: Class<List<Integer>> tListInt3 = (Class<List<Integer>>) ((Class<Integer>)List.class); that doesn't work. you probably meant Class<List<Integer>> tListInt3 = (Class<List<Integer>>) ((Class)List.class); we can always cast from one type to another by up-cast then down-cast Integer x = (Integer)(Object)"string"; The type of List.class is Class<List>; it is not a subtype/supertype of Class<List<Whatever>> therefore direct cast between the two types is illegal. It can be argued that Class<List<Integer>> doesn't exist - there is only a class for List; there is no such class for List<Integer> (which really is just List at runtime) However, this is a flaw of Java type system; in practice we do need things like Class<List<Integer>>. Our solution - casting and pretending Class<List<Int>> exits - is likewise flawed - but it's not our fault.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Is an SSH Key Required to clone a public github account? Does github require all cloning, of both public and private repositories, to use an SSH public key? Maybe a better question, is can git clone a github repo without a ssh key at all. A: You can use https protocol, as mentioned in "GitHub - Https access". You would then use your GitHub login/password in a ~/.netrc file (which can be a security concern). Note: on Windows, that would be an _netrc file. Since GitHub supports smart http protocol (as detailed here), you can use that for cloning/pulling and for pushing. A: SSH Key is used for more safety communication. Is not necessary, although using SSH Key is usefull because encrypte communication and also does not involve password. A: No. A SSH key is only needed to push to a public repo on github, not to pull from one (although the easiest method to get a clone you can later push to uses the same key to pull as to push, that isn't the only way to work).
{ "language": "en", "url": "https://stackoverflow.com/questions/7502247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to access the one component properties form other component with out binding I would like to bind two components with out binding and which resides in different MXML. for eg: A.mxml has textinput and B.mxml has a combobox when choose one item in B.mxml selected item should be display in A.mxml textinput. A: Listen for the Combobox's change event and in the event handler update the text property of your text input. As you have mentioned that both reside in separate mxml's, you might need to add eventlistener on (common) parent to both. A: "Flex in a week" on day 3 of traing has some good information on extending the event class. http://www.adobe.com/devnet/flex/videotraining.html Extending the event class for the "change" event would be an easy way to handle this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete folder content and remove from version control We have a folder on the SVN tree with a lot of garbage on it. We want to do the following: * *Delete folder content (leave the folder empty on the SVN) *Ignore subsequents commits for the content of this folder. The problem is that every developer working at this proyect, can write garbage into this folder, but it never be commited to the SVN. BUT, currently there is a lot of garbage on the SVN itself. Because the folder is already on the SVN tree, we can't add a 'ignore' property. Note that the content deleting must be done at the SVN tree. Local content of every developer' folder must be left untouched. We work with Eclipse+Subclipse and TortoiseSVN. So, any idea on how do this ? A: As you've said, you can't add the svn:ignore property, and you can't delete the folder without that change being propagated to individual working directories. Ultimately, you're trying to subvert the way Subversion works — instead, just ask your developers to back-up their copies of the directory, and then delete it from the repository in the usual way. A: Tortoise has an option for this. Right click on the folder and click "TortoiseSVN" then select "Delete and add to ignore list." A: I'd faced same issue in similar setup, and I found it really tough. I managed to do this using the svn command line client (could be downloaded from here). cd directory-to-remove svn remove * svn commit -m "message deletion" svn update svn propset svn:ignore * . svn commit -m "message ignoring" After this command sequence directory-to-remove itself will stay on svn but anything inside this directory couldn't be committed to repository.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: function not working on remote server the function is for checking if an url is pointing to a valid image by checking the meta info in the head section of the given file. the echo in the below code gives me the correct wrapper data but on my remote server it echoes "ArrayResource id #11" How this is possible? local:PHP Version 5.3.4 remote server: PHP Version 5.2.9 function isImage($url) { $params = array('http' => array( 'method' => 'HEAD' )); $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) return false; // Problem with url $meta = stream_get_meta_data($fp); if ($meta === false) { fclose($fp); return false; // Problem reading data from url } $wrapper_data = $meta["wrapper_data"]; if(is_array($wrapper_data)){ foreach(array_keys($wrapper_data) as $hh){ echo substr($wrapper_data[$hh], 0, 19);//////////////ECHO//////////////////////// if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19 { fclose($fp); return true; } } } fclose($fp); return false; } EDIT: I adapted the function so it checks if 'Content-Type: image' is somewhere in the header of the file. this works cross server... function isImage($url) { $params = array('http' => array( 'method' => 'HEAD' )); $ctx = stream_context_create($params); $fp = @fopen($url, 'rb', false, $ctx); if (!$fp) return false; // Problem with url $meta = get_headers($url); if ($meta === false) { fclose($fp); return false; // Problem reading data from url } foreach ($meta as $key => $value) { $pos = strpos($value, 'Content-Type: image'); if($pos!==false){ fclose($fp); return true; } } fclose($fp); return false; } A: Refer to this. stream_get_meta_data can return values in several datatypes. On your remote server it is returning an array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the exact difference between Keys.Control/Shift and Keys.ControlKey/ShiftKey? What's the exact difference between Keys.Control and Keys.ControlKey/Keys.Shift and Keys.ShiftKey in System.Windows.Forms? I've googled it but nothing specific came up, and it doesn't seem to be documented on MSDN either. Personally, I always use Keys.Control/Keys.Shift, because it works fine. Edit: After reading KreepN's answer, I thought if you never have to use Control/Shift, why are they in the framework? I mean, they aren't even the physical keys, so I can't see the reason why Microsoft decided to create them. Are there circumstances where it's better to use Control/Shift? A: ControlKey and ShiftKey (and Menu--which you would assume would have been named AltKey) represent the physical keys themselves. In other words, they are "actual" keys and can be found in the KeyCode property of a KeyEventArgs object. Control, Shift, and Alt, on the other hand, will never appear in the KeyCode property, but their values can be found in the KeyData property. It seems you never actually NEED to use these constants, because the framework already pulls them out for you via the Alt, Control, and Shift properties of the KeyEventArgs object, but you CAN use them to test against the KeyData property if you really want to. Source with Examples. Edit for your edit: Look at the values that are returned when the "a" key is pressed: a (unshifted) / 41 / 41 A (Shift+a) / 41 / 10041 Ctrl+a / 41 / 20041 The "KeyCode" in this case is = 41 for all modifiers. You could use this in code if all you cared about was the primary button pressed, in this case "a". If you wanted to have different functionality based on if a modifier was pressed you would need to get more specific and reference the "KeyData" field and look for the # that denoted a certain modifier. In this case "100" for shift and "200" for control at the beginning of the field. That's not to say you couldn't just check for the "41" at the end of the KeyData field, but I've never been one to complain about convenience. It would be safe to say that the "difference" you are looking for between them in your first question is that they reference different property fields. Edit for additional relevance: The key modifier values combined with the key value directly correlate to the Shortcut enumeration members. For example: Shortcut.CtrlF8 ( 0x20077 ) is the same as Keys.Control | Keys.F8 ( 0x20000 | 0x77 ) This can be useful when dealing with the defined Shortcut properties of menu items.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: dns_get_record problems I am setting up a dns lookup form using dns_get_record. I set it up to check the A Record and MX Records and NS records of the domain that is input. However, I would like it to also to get the full TTL of a record? also is it possible to query direct to the named service on port 53 (UDP)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7502270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Understanding how canvas converts an image to black and white I found this script for converting an image to black and white, which works great, but I was hoping to understand the code a little bit better. I put my questions in the code, in the form of comments. Can anyone explain in a little more detail what is happening here: function grayscale(src){ //Creates a canvas element with a grayscale version of the color image var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var imgObj = new Image(); imgObj.src = src; canvas.width = imgObj.width; canvas.height = imgObj.height; ctx.drawImage(imgObj, 0, 0); //Are these CTX functions documented somewhere where I can see what parameters they require / what those parameters mean? var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); for(var y = 0; y < imgPixels.height; y++){ for(var x = 0; x < imgPixels.width; x++){ var i = (y * 4) * imgPixels.width + x * 4; //Why is this multiplied by 4? var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; //Is this getting the average of the values of each channel R G and B, and converting them to BW(?) imgPixels.data[i] = avg; imgPixels.data[i + 1] = avg; imgPixels.data[i + 2] = avg; } } ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); return canvas.toDataURL(); } A: function grayscale(src){ //Creates a canvas element with a grayscale version of the color image //create canvas var canvas = document.createElement('canvas'); //get its context var ctx = canvas.getContext('2d'); //create empty image var imgObj = new Image(); //start to load image from src url imgObj.src = src; //resize canvas up to size image size canvas.width = imgObj.width; canvas.height = imgObj.height; //draw image on canvas, full canvas API is described here http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html ctx.drawImage(imgObj, 0, 0); //get array of image pixels var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height); //run through all the pixels for(var y = 0; y < imgPixels.height; y++){ for(var x = 0; x < imgPixels.width; x++){ //here is x and y are multiplied by 4 because every pixel is four bytes: red, green, blue, alpha var i = (y * 4) * imgPixels.width + x * 4; //Why is this multiplied by 4? //compute average value for colors, this will convert it to bw var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; //set values to array imgPixels.data[i] = avg; imgPixels.data[i + 1] = avg; imgPixels.data[i + 2] = avg; } } //draw pixels according to computed colors ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height); return canvas.toDataURL(); } In this function coefficient equal to 1/3 are used, however the usually used are: 0.3R + 0.59G + 0.11B (http://gimp-savvy.com/BOOK/index.html?node54.html). A: * *The canvas functions are, like most functions, described in an official specification. Also, MDC is helpful for more "informal" articles. E.g. the drawImage function on MDC is here. *The getImageData function returns an object, which contains an array with the byte data of all pixels. Each pixel is described by 4 bytes: r, g, b and a. r, g and b are the color components (red, green and blue) and alpha is the opacity. So each pixel uses 4 bytes, and therefore a pixel's data begins at pixel_index * 4. *Yes, it's averaging the values. Because in the next 3 lines r, g and b are all set to that same value, you'll obtain a gray color for each pixel (because the amount of all 3 components are the same). So basically, for all pixels this will hold: r === g, g === b and thus also r === b. Colors for which this holds are grayscale (0, 0, 0 being black and 255, 255, 255 being white).
{ "language": "en", "url": "https://stackoverflow.com/questions/7502271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sockets over the net I am implementing a Socket program in Java and realized that Socket and ServerSocket classes can only be used in my LocalNetwork.What i need to do,so that a remote PC(different router) can connect to my PC(server)?what API should i use? A: There is nothing about Socket and ServerSocket that limits them to the local network. There may be issues around firewalls and such, but the classes themselves won't place any additional constraints. A: There is no restriction, It can be used over the internet as well, Ideally what you want to do is to make sure your firewall permits you to connect to the port listened by the socket, you can create a port forwarding via your DMZ or NAT to filter and forward requests to the listening machine. A: "Socket and ServerSocket classes can only be used in my LocalNetwork." Where did you get that from? Anyway, the Socket and ServerSocket are not restricted to local network at all. This is not local: Socket s = new Socket("www.java2s.com", 80); However, if your client and server are on different networks, then you have to set up the proper routing (i.e. configure the router's DMZ, etc.).
{ "language": "en", "url": "https://stackoverflow.com/questions/7502275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you make a HTTP PATCH request from Javascript? I am working with an API that requires me to make an HTTP PATCH request as part of the URI, is this possible to do from Javascript, my research is showing that I can only do POST, GET, DELETE, and PUT. Is PATCH allowed? Thank you, A: I'm not sure what you exactly mean by a "PATCH" request, but it seems to be possible (at least in Firefox 6 and Chromium 12). According to the Mozilla source code, there is only a limitation of TRACE and TRACK requests. A quick testcase: <!-- test.html --> <script> var x=new XMLHttpRequest(); x.open("patch", "/"); x.send(null); </script> Any webserver can be used, but I choose for Python's SimpleHTTPServer module. $ ls test.html $ python -m SimpleHTTPServer localhost - - [21/Sep/2011 17:32:11] "GET /test.html HTTP/1.1" 200 - localhost - - [21/Sep/2011 17:32:11] code 501, message Unsupported method ('patch') localhost - - [21/Sep/2011 17:32:11] "patch / HTTP/1.1" 501 - So, as long as the server supports the method, the request get's passed. A: As of some research the PATCH method seems to be new (march 2010 https://www.rfc-editor.org/rfc/rfc5789) so if you try to define PATCH on an XMLHttpRequest it may work, but only on very latest revisions of modern browsers. Don't have a supported browser list found, yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to send selected date of rich:calendar to my bean? I am using richfaces calendar in my JSF 1.1 project. If I select a date, I want to send the selected date to my bean. How can I do it? I write simple code for this but it comes always null. Here is my JSF page: <rich:panel style="width: 15%;"> <rich:calendar cellWidth="24px" cellHeight="22px" value="#{functions.selectedDate}" datePattern="yyyy-MM-dd" style="width:200px;"> </rich:calendar> </rich:panel> Here is my bean: import java.util.Date; public class functions { private Date selectedDate; public Date getSelectedDate() { return selectedDate; } public void setSelectedDate(Date selectedDate) { this.selectedDate = selectedDate; } } A: Put it in a <h:form> and submit it by a command button/link inside the same form. E.g. <rich:panel style="width: 15%;"> <h:form> <rich:calendar cellWidth="24px" cellHeight="22px" value="#{functions.selectedDate}" datePattern="yyyy-MM-dd" style="width:200px;"> </rich:calendar> <h:commandButton value="submit" action="#{functions.submit}" /> </h:form> </rich:panel> with public void submit() { System.out.println("Selected date is: " + selectedDate); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7502280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lync SDK - Making a plugin for Lync First of all, thanks. I want to know if there's some example or documentation about how to make a plugin to modify (specifically add a kind of input text, like text or emoticons) the Lync 2010. I read the Lync SDK and other documentation related, but i can only found ways of make my own application with Lync properties, not how to modify or add funcionalities to the client itself. Thanks in advance A: There really isn't a way to modify the Lync client itself, it doesn't have a plugin model. Basically, you've got 2 options: * *Run the client in UI Suppression mode, in which case you'll need to implement ALL UI yourself (not great...) *Use the API in automation mode, and dock the conversation in a window of your own - in which case you can create any functionality you want to in your own window From what you said about your application, it sounds like option 2 is the way to go. Roughly speaking, you'd do this: * *Create your WPF or WinForms window with the buttons you'd need, and a WindowsFormsHost and Panel(WPF) or just a Panel (WinForms) for docking the window *Listen out for new conversations using ConversationManager.ConversationAdded *Instantiate a new instance of your window, and dock the conversation window into it Most of this is described in the article I linked to. You could also check out the Tabbed Conversations application for an example of an app that's doing the same thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: message broker consumer/producer with reassign when client goes down? I am looking for a message broker API to use it with c#. Normally the things are quite simple. I have a server that knows what jobs are to do and I have some clients that need to get these jobs. And here are the special requirements I have: * *If a client got a job but fails to answer within a specific time, then another client should do the work. *More than one queue and priorities *If possible it needs to work with big message queues (this way I could just load all jobs sometimes a month and forget about it *secured communications would be good. *API for talking with the broker from c#. How much work is done? What is still to do? Delete some jobs... *If available replication to another broker would be good. *The broker needs to run on windows What is not an issue: * *low latency (there is no problem when a message needs minutes) Do you know such a message broker that is free to use? A: RabbitMQ and several other AMQP implementations satisfy most of (if not all of) these requirements. * *RabbitMQ allows clients to acknowledge receipt and/or processing of messages. As per http://www.rabbitmq.com/tutorials/amqp-concepts.html#message-acknowledge: If a consumer dies without sending an acknowledgement the AMQP broker will redeliver it to another consumer or, if none are available at the time, the broker will wait until at least one consumer is registered for the same queue before attempting redelivery. * *Many queues (and in fact many brokers) are supported, in a variety of different configurations *It scales particularly well, even for very large message queues: http://www.rabbitmq.com/faq.html#performance *Encryption is supported: http://www.rabbitmq.com/faq.html#channel-encryption *There is a .NET Client Users Guide and API docs: http://www.rabbitmq.com/documentation.html *There is live failover if a broker dies: http://www.rabbitmq.com/clustering.html *It runs on Windows, Linux, and probably anything else that has an Erlang implementation
{ "language": "en", "url": "https://stackoverflow.com/questions/7502288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Drawing without flickering I have a win32 application which was developed in c++. The application draws some stuff on the window using basic shapes (rectangles). The windows is repainted every 20ms (50hz) using InvalidateRect. All works well but the drawing is flickering. How can i prevent the flickering? In c# i normally use a double buffered component (such as pictureBox), how could i get rid of this in c++ using win32? A: You can create an in-memory device context, draw those shapes to it (just like you would to the window's device context) and then blit from it to window's device context when the window is invalidated. You also need to disable background clearing (handle WM_ERASEBKGND window message appropriately) before the draw happens. Edit: I stumbled upon a pretty exhaustive tutorial on flicker-free drawing in GDI, which explains all aspects of drawing in Windows and comes with examples. A: You can easily implement double buffering in Win32 as well. Assuming you are doing your painting directly on the Window using its device context, do this instead: Create a "memory" device context and do all your drawing on that device context, then copy the invalidated portions of the window to the actual device context when appropriate, using the BitBlt() function There's a pretty good (albeit high level) overview here. A: You can double buffer in C++, too. When you get the DC to paint to, you create an offscreen bitmap (CreateCompatibleBitmap) and a memory DC (CreateCompatibleDC). Do all your painting to that DC. At the end, do a BitBlt from the memory DC to the actual DC. For performance, you might want to cache the offscreen bitmap and DC, but remember to recreate them when the window size changes. A: Here's the greatest tutorial i've found yet: https://msdn.microsoft.com/en-us/library/ms969905.aspx In short - yes, you have to implement the double-buffering. It's done through creating the in-memory DC and then drawing everything you want to an in-memory bitmap using that DC, only afterwards commiting this bitmap to an actual DC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to use native Python logging or/and Twisted logger for multiple daemon/cron scripts? I use logging to one file with different scripts of one program - such as cron tasks, twisted daemons (HttpServers with some data) etc. If I use default Python logging in base class such as import logging import logging.handlers .... self.__fname = open(logname, 'a') logging.basicConfig(format=FORMAT, filename=logname, handler=logging.handlers.RotatingFileHandler) self._log = logging.getLogger(self.__pname) self._log.setLevel(loglevel) logging.warn('%s %s \033[0m' % (self.__colors[colortype], msg)) then it's work normally, sending output of all scripts in one file, but some important part of default twisted log missing - such as info about http request/headers etc else I use twisted logging such as from twisted.python.logfile import DailyLogFile from twisted.python import log from twisted.application.service import Application .... application = Application("foo") log.startLogging(DailyLogFile.fromFullPath(logname)) print '%s %s \033[0m' % (self.__colors[colortype], msg) then works with additional data, but some trouble with logging from different scripts exists - looks like cron tasks trouble appears. Looks like these cron tasks switch context of output and some part of logging output is missing and not restored Of, course - cron tasks working without Twisted reactor, but using twisted logging. What I should do with logging for log all data printed both Twisted/cron parts of app? Thanks for any help! A: I think the point is that you should not use DailyLogFile but use PythonLOggingObserver to redirect the log to standard lib log from twisted.python import log observer = log.PythonLoggingObserver() observer.start() log.msg('%s %s \033[0m' % (self.__colors[colortype], msg)) Also you might want to see the example in docs: http://twistedmatrix.com/documents/current/core/howto/logging.html#auto3
{ "language": "en", "url": "https://stackoverflow.com/questions/7502295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery: When clicking on checkbox, input box below will be visible I am not very good at jQuery, so I have a question; is there a quick way to code so when you click on a checkbox (equally to 1), there will appear a text box below. I am currently learning jQuery, so this would be a great example. Thanks in advance! A: $("#yourCheckboxId").change(function(){ if ($("#yourCheckboxId").is(":checked")){ $("#yourTextBoxId").show(); } }); and if you want to hide the textbox when you turn the checkbox off its: $("#yourCheckboxId").change(function(){ if ($("#yourCheckboxId").is(":checked")){ $("#yourTextBoxId").show(); } else{ $("#yourTextBoxId").hide(); } }); this is assuming you have a textbox in ur html that has a unique ID and also is hidden initially ("display:none") and that you have a checkbox with unique Id that is visible initially A: $('input:checkbox').change(function () { if ( $(this).is(':checked') && !$(this).next().is('textarea') ) { $(this).after( $('<textarea>') ); // OR $('<textarea>').insertAfter(this); } }); evan version shows an pre-existing version, mine creates it, you can combine both ;) A: If you wish to do this totally dynamically, you will want to make use of 2 methods. * *.after docs *.remove docs You can determine if the checkbox has been checked, and if so add the textbox after it, or if it has been unchecked and the textbox already exists and if so remove it. This boils down to the code: $('input[type=checkbox]').click(function(){ if($(this).is(':checked')){ var tb = $('<input type=text />'); $(this).after(tb) ; } else if($(this).siblings('input[type=text]').length>0){ $(this).siblings('input[type=text]').remove(); } }) Live example: http://jsfiddle.net/KQ56P/ A: Another way (http://jsfiddle.net/3r6nb/): //html <div> <input id="check" type="checkbox"/> <input id="text" type="text" class="hidden"/> </div> //css .hidden { /*hides any element given this class, you may also want to set display:none; as hidden elements still take up space*/ visibility:hidden; } .visible { visibility:visible;/*set display:inherit; if using display:none; above*/ } //javascript $("#check").change(function() { //toggleClass() removes the class from the element if it //exists or adds it if it doesn't $("#text").toggleClass('hidden'); $("#text").toggleClass('visible'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7502297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flex - how to download a string variable as a file to the local machine? I have a String variable in my flex (flash builder 4) application containing CSV data. I need to allow the user to download this data to a local file. For example, giving them a "csv" button to click and it might present them with a save file dialog (and I would be sending the contents of my string variable). Is this possible / how ? I am using the ResuableFX component for the datagrid to csv. This the code I ended up with that works to save the string to a text file for the user (in a web browser): var dg2CSV:DataGrid2CSV = new DataGrid2CSV(); dg2CSV.includeHeader=true; dg2CSV.target=adgEncounters; var csvText:String=dg2CSV.getCSV(); var MyFile:FileReference = new FileReference(); var csvFileNameDT:String = QuickDateFormatter.format(new Date().toString(),"YYYYMMDDJJNNSS"); MyFile.save(csvText,"Encounters"+csvFileNameDT+".csv"); A: If you're in an AIR App you can use File.browseForSave(). If you're in a web app, you can use FileReference.save() . The FileReference docs have a lot more info on this. In many cases, I would recommend using navigateToURL() to open the file outside of Flash and let the browser deal with it. I'm not sure if there is a way to do this without user interaction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic Linkify Text in ListView - Error : no intent found with data : specified url i am creating a listview. in that list each item has text view. and in text views i am defining linkify texts based on data from the web service.. now when i click on that linkify text i am getting error like 09-21 20:27:38.031: ERROR/AndroidRuntime(766): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=\"ticbeat.com/socialmedia/fa…" (has extras) please help me solving this problem.. any answer with solution will highly appreciated. Update: Code: if(urlentities[position]!=null && dpurlentities[position]!=null) holder.twtdata.setText(Html.fromHtml(timelines[position].replace(urlentities[position],"<a href=\\\""+dpurlentities[position]+"\">"+urlentities[position]+"</a>"))); A: Look like you need to put http:// at the beginning of that URL. Without the protocol specifier Android appears to assume "content://" is the intended url type. A: Linkify by default opens the default browser (new activity). I'm guessing you pass getBaseContext() as context to the TextView(Context context). You have to pass the activity as Context for that to work by default. If you are concerned about memory leaks you can try getApplicationContext() but haven't tested it. The best way to handle that is to create a listener at the TextView fired on onclick() of the span . Your activity (the one that created the textView() catches that listener and then the activity opens the browser. Here you can see how to make your own listener Another way to do that is to implement a WebView in you layout and all you have to do from the textView is to show that webView with the link clicked. getBaseContext() can do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: winforms switch between tabs while current one is busy doing processing i have winform (c#) with multi-tabs, the current focused tab is busy doing lengthy Async operation and embedded progressbasr "in that tab" showing the progress. i want to let the user be able to navigate to other tabs and perform other tasks in case he/she don't wanna wait. so how i can do that in simple and robust way? this is the lengthy op in short: foreach (DataRow _dr in _allDt.Rows) { //check if machine is online out of 100 machines list using async approach if (_connectionUtil.ConnectionIsOn(_dr["ipAddress"].ToString())) _onMachineAl.Add(_machineInfo); _progressBar.PerformStep(); } do i have to use thread?! or simpler way available? please provide code-segment or helpful source. EDIT: //async part: using (TcpClient tcpClient = new TcpClient()) { IAsyncResult result = tcpClient.BeginConnect(ipAddress, 3306, null, null); WaitHandle timeoutHandler = result.AsyncWaitHandle; thanks, A: You need to run your 'long-time' operation in separate thread or background worker. In this case UI will be free and user can continue work with application. But do not forget to notify user when operation is complete. Here is the sample: new System.Threading.Thread(new System.Threading.ThreadStart(delegate() { foreach (DataRow _dr in _allDt.Rows) { //check if machine is online out of 100 machines list using async approach if (_connectionUtil.ConnectionIsOn(_dr["ipAddress"].ToString())) _onMachineAl.Add(_machineInfo); this._progressBar.Invoke(new MethodInvoker(delegate() // Invoke you need for accessing the UI thread and controls { _progressBar.PerformStep(); })); } })).Start(); A: If you are already performing your task asynchronously, then the user should already be able to switch between tabs because the async operations will not be blocking the UI thread. If you are not really doing your task asynchronously the user will not be able to do much of anything because you are blocking the UI thread. That being said, I suspect you are in the second camp, so something like this should help you get going: var mi = new MethodInvoker(() => { foreach(dataRow _dr in _allDt.Rows) { if(_connectionUtil.ConnectionIsOn(_dr["ipAddress"].ToString())) _onMachineAl.Add(_machineInfo); this._progressBar.Invoke(() => { _progressBar.PerformStep(); }); } }); mi.BeginInvoke(null, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7502307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JTextField BeansBinding I have 2 JtextFields called "qty" and "amount". When the user types in qty, the value is gone under some calculation and set the last value to amount textfield. I have bound these 2 textfields to beansbinding class's properties. when the user types in qty, the property which is responsible for that textfield is called and then I have called the firepropertychange of the qty as well as the amount's firepropertychange to update the value of amount according to the qty. This works well.Also when qty's textfield's value is being deleted with backspace button the qty's value also change.but when qty textfield is empty, the amount textfield remains with its last value(let's say qty is having a number '22' and amount textfield shows '44', and when backspace is pressed the number is '2' and amount's showwing value is '4',but when the last value '2' in qty is aslo deleted, the amount textfield shows '4').I want that the amount textfield should be showing zero. Any solution for this please? A: just checked the default converters: they don't handle null/empty, you have to implement one that can do and set that to the binding. Something like, to see the difference uncomment the converter setting: @SuppressWarnings({ "rawtypes", "unchecked" }) private void bind() { BindingGroup context = new BindingGroup(); AutoBinding firstBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, // this is some int property this, BeanProperty.create("attempts"), fields[0], BeanProperty.create("text")); context.addBinding(firstBinding); // firstBinding.setConverter(INT_TO_STRING_CONVERTER); context.bind(); } static final Converter<Integer, String> INT_TO_STRING_CONVERTER = new Converter<Integer, String>() { @Override public String convertForward(Integer value) { return Integer.toString(value); } @Override public Integer convertReverse(String value) { if (value == null || value.trim().length() == 0) return 0; return Integer.parseInt((String) value); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7502309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question about the explanation of data segment on Wikipedia? Following yesterday's question, I did some research and I thought I had a more clear picture of linux process memory map. I think one reason of my initial confusion is the incorrect explanation on Wikipedia, which claims heap is a part of data segment, which is obviously wrong. Also, it claims that data segment is not read-only and thus different from Rodata. However, my understanding is that data segment contains rodata, BSS, and data, can anybody confirm my understanding? (It'd be even better if an expert could rewrite the Wikipedia article.) A: "Segments" are a rather old-fashioned concept, dating back to when modern paged-memory architectures weren't widely used. Segmented architectures forced quite a rigid memory layout, whereas paged memory allows the process to have many separate regions of virtual memory, each with its own access restrictions. A Linux process has a text (or code) region containing the executable's code (initialised from the text section of the executable), and a data region containing runtime data (initialised from the data, bss and (perhaps) rodata sections of the executable). These regions correspond (more or less) to the old-fashioned text and data segments. It will also have a stack, and may also have access to other regions of memory, for example memory-mapped files and code from dynamic libraries. [the article] claims heap is a part of data segment, which is obviously wrong It's not necessarily wrong. The heap can be created either by extending the data segment (using the brk() system call), or by creating new memory regions (using mmap() to create anonymous mappings), or a combination of both. Heap space created by the first method is part of the data segment, although in that case the article is incorrect in stating that the segment has fixed size. Also, it claims that data segment is not read-only and thus different from Rodata. However, my understanding is that data segment contains rodata, BSS, and data. The article is slightly confused here; you cannot compare a segment (a process's memory region) with a section (part of an executable file). Read-only data can be protected by putting it in a separate, write-protected region rather than the writable data region. Modern desktop/server operating systems will do this (typically by mapping the rodata section of the file directly into memory); simpler systems may not have a mechanism for write-protecting memory, and so will be more likely to place it in the data segment. A good way to see how memory is laid out in a Linux process is to look at the /proc/<PID>/maps file. This will show the virtual address range, access restrictions, and mapped file (if there is one) for each region available to the process. A: There's no segmentation in modern desktop operating systems at all. The memory has a flat model. Anything you find discussing sections is referring to the binary executable format- not the process or operating system at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kentico SmartSearch, Custom Results i'm using Kentico Smart Search but im looking to build a reference table, basically to boost particular pages for particular phrases i.e. if user searches for "XYZ" result = "www.examplesearchresult.com" if user searches for "ABC" result = "www.secondexampleresult.com" Any help would be greatly appreciated Thanks Ben A: The other way how to achieve this would be in modifying the dataset of results. You will check the search term and if it will fit your rules, you will access the returned datset with results (\CMSModules\SmartSearch\Controls\SearchResults.ascx.cs in Search() method) and add column(s) with your desired items. A: If you're searching for specific document types, you can extend the document type by adding another field and allowing it to be searchable. Then you can alter your lucene query to include that field as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BASH quotes in debug mode I'm using debug mode in a BASH script to trace the commands that have been executed by the script. So far this has all worked very well but now I need to run a command with some options contained in a string and that string contains quotes that seem to cause a problem in debug mode. Here is a short example #!/bin/bash job_opts='-q long -M5000000 -R"select[mem>5000] rusage[mem=5000]"' set -x bsub $job_opts # .... more options for job here set +x This script generates submissions to lsf job queues using the bsub command but that shouldn't matter. On STDERR I see this trace: + bsub -q long -M5000000 '-R"select[mem>5000]' 'rusage[mem=5000]"' Job submission rejected. The bsub command was supposed to look like this: + bsub -q long -M5000000 -R"select[mem>5000]' 'rusage[mem=5000]" So my bsub command has failed and I can also see that this is because it didn't see the -R switch, presumably because of the additional single quotes around the whole switch. I understand that BASH puts single quotes around quoted strings in debug mode but I didn't expect that this would affect the actual command that is being issued, which appears to have happened. Am I doing somethng wrong here or is there any way of avoiding this extra quoting in BASH debug mode? It's just very convenint to log commands in this way, so would be a shame if I couldn't do it anymore just because of those pesky quotes. Thanks for your help! A: You cannot do that with plain variables, the shell will parse it to separate arguments. You can do eval, but I wouldn't recommand it: eval bsub $job_opts You can do it with an array: http://mywiki.wooledge.org/BashFAQ/050 job_opts=("-q" "long" "-M5000000" '-R"select[mem>5000] rusage[mem=5000]"') bsub "${job_opts[@]}"
{ "language": "en", "url": "https://stackoverflow.com/questions/7502323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Saving AND using memchr's return value, in if? "if ( ptr = memchr(str1, '4', sizeof(str1)) )"? Problem: if you do if ( ptr = memchr( str1, '4', sizeof(str1) ) ) { // do stuff using ptr } then you'll enter and do "stuff" every time. But if you just do if ( memchr( str1, '4', sizeof(str1) ) ) { // would do stuff but don't have ptr! } then you'll enter but you won't have the pointer to where '4' is inside str1. I need to evaluate and do stuff for several possibilities ie if '4', else if '7', else if '1', etc. So what's the most efficient method to both evaluate if that character exists, and use the pointer returned if it does? Surely it's not if ( memchr( str1, '4', sizeof(str1) ) ) { ptr = memchr( str1, '4', sizeof(str1) ) // do stuff using ptr } A: The assignment operator returns the value being assigned, which (along with right associativity) is why a=b=c; works. So your first example will work just fine. A: do the memchr and assign the return value then do the if. like this: ptr = memchr(str1, '4', sizeof(str1)); if (ptr) { // do stuff using ptr; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7502332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I wrap execl in c I tried two ways: void func(const char *path, const char *arg0, ...){ va_list args; va_start(args, arg0); execl(path, arg0, args, NULL); va_end(args); } func("/bin/ls", "ls"); And: void func(const char *path, const char *arg0, ...){ va_list args; va_start(args, arg0); execl(path, arg0, args); va_end(args); } func("/bin/ls", "ls", NULL); But seems non work as expected after several test... What's wrong in my way of wrapping variable length parameters? A: Since you don't know how many arguments you'll be receiving, you'll need/want to use execv instead of execl. You'll need to walk through the arguments, retrieve a pointer to the beginning of each string, and put them into an array. You'll then pass the address of that array to execv. A: execl() is a variadic function, so this should compile. However, it won't work. execl expects each of its arguments to be a const char *, i.e. a pointer to a string. A va_list is not such a thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pick a random name from a text file in VB I have a file that has names of competitors. I want to write a VB code that selects a random name from the file.What I need is show the names moving quickly once I press enter it will select the name. I hope you got the idea. A: If i understand your problem correctly you want to show every names on the file to the user on a button which name is chances rapidly. If you want to do this little trick you need to load all the names from the file at the begging and keep them in a array so you will not need to reconnect to the file, that contains your names, every time you change the name of the button Once you get the names you will need to create an infinite loop and attach a timer so the loop will wait for a specific time to change the name of the button. last thing that you need to do is write a set of code under the button. That breaks the loop and gives the name of the button which was the assigned name at the time of the clicking. I hope that helps you! Have a good day
{ "language": "en", "url": "https://stackoverflow.com/questions/7502335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache Maven: What is the difference between Inheritance, Aggregation, and Dependencies? I'm new to Maven, and I'm trying to understand why my company's modules are organized into 'module groups', but also each sub-module declares its parent explicitly. I don't quite understand what the POM Reference is trying to say about the difference between inheritance and aggregation. For example, a parent module: <groupId>example.group</groupId> <artifactId>util</artifactId> <packaging>pom</packaging> <name>Util Parent</name> <modules> <module>util_client</module> <module>util_core</module> <module>util_server</module> </modules> And one of its children: <parent> <artifactId>util</artifactId> <groupId>example.group</groupId> <version>trunk-SNAPSHOT</version> </parent> <groupId>example.group.util</groupId> <artifactId>util_core</artifactId> <packaging>jar</packaging> <name>Util Core</name> Why declare it both ways? Is it redundant? To make things even more confusing, some of the util submodules depend upon eachother: <groupId>example.group.util</groupId> <artifactId>util_client</artifactId> <packaging>jar</packaging> <name>Util Client</name> <dependencies> <dependency> <groupId>example.group.util</groupId> <artifactId>util_core</artifactId> </dependency> </dependencies> Sorry if this is a doozy of a question, but wow this is confusing! Thanks for your help. A: When you define sub-modules, you can build and release them all at once from the top level. When you use inheritance in the second example, you can use definitions from the parent POM defined once, (Like which versions of software to use) In the last example, when one module needs resources from another module, you can add it as a dependency and it will download and include it in the build path automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Statistics, machine learning and data mining I am currently learning data mining and I have the following questions. * *what is the relationship between machine learning and data mining? *I found many data mining techniques are associated with statistics, while I "hear" data mining has many thing to do with machine learning. So my question is: is machine learning closely related with statistics? *If they are not closely related, is there such divisions that separate data mining focusing on statistical techniques and data mining focusing on machine learning skills? Because I found department of statistics of some graduate schools open data mining courses. A: Data mining is the process of extracting useful information from data, such as patterns, trends, customer/user behavior, liking/disliking etc. This involves the use of algorithms that are related to Artificial Intelligence and statistics. Wikipedia's definition of Data Mining is: Data Mining (the analysis step of the Knowledge Discovery in Databases process,[1] or KDD), a relatively young and interdisciplinary field of computer science,[2][3] is the process of discovering new patterns from large data sets involving methods from statistics and artificial intelligence but also database management. In contrast to for example machine learning, the emphasis lies on the discovery of previously unknown patterns as opposed to generalizing known patterns to new data. Machine Learning involves making the computers "learn" that behavior, trend etc, and to act according. For example, in credit card fraud, the computer "learns" the behavior of a customer, and if something strange occurs (a transaction involving very high amounts etc), it flags that transaction for potential fraud. Wikipedia's definition of machine learning is: Machine learning, a branch of artificial intelligence, is a scientific discipline concerned with the design and development of algorithms that allow computers to evolve behaviors based on empirical data, such as from sensor data or databases. Machine Learning is concerned with the development of algorithms allowing the machine to learn via inductive inference based on observing data that represents incomplete information about statistical phenomenon. Classification which is also referred to as pattern recognition, is an important task in Machine Learning, by which machines “learn” to automatically recognize complex patterns, to distinguish between exemplars based on their different patterns, and to make intelligent decisions. Machine learning uses Data Mining to learn the pattern, behavior, trend etc, because Data Mining is the way of extracting this information from a set of data. Data Mining and Machine Learning both use Statistics make decisions. So yes statistics is involved and is very important in Data Mining and Machine learning. A: There tends to be a lot of overlap between what different people call machine learning, data mining and statistics. The very definitions of the terms would depend on whom you ask. Here is a nice overview, with lots of great links. A: Although overlap between data Data mining and Machine Learning, we can distinguish between them; simply, such as: Data mining search for patterns to predict and/or describe huge data, Machine Learning goes further to use these patterns to learn. And both based on Statistics. A: A comprehensive answer was already given by @SpeedBirdNine. As a side note: * *Data-mining and Machine-learning are mainly based on the old but ingenious ideas of statisticians. (Inferential statistics, decision theories, etc.) *Classic Statistics + today's powerful computers = DM & ML *Since we are living in the era of big data, the barrier statisticians used to be faced with, in terms of the absence of enough data, is no longer an issue. Therefore, in many cases (but not all of course), it is safe to say that Data-mining/Machine-learning is the new Statistics! (The infinity symbol ∞ they used to have in their equations that if n (the sample size) goes to infinity, then everything's behavior is predictable (!), is not a compromised reality anymore!). Regarding your last question, in my opinion, in any meaningful research, you either need to apply some statistical methods on big data and this is when DM/ML comes in handy, or you need to apply a DM/ML method which is already designed based on classical statistics. These are the two sections that every DM/ML research is involved, and statistics is not excluded, let alone when the goal is to come up with a noble DM/ML algorithm to analyze/cluster/classify big data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RewriteCond breaking the RewriteRule for no apparent reason I've just started playing with mod_rewrite and I'm trying to forward all requests to old html file to go to php files instead. Here's the .htaccess contents: RewriteCond $1.php -f RewriteCond $1.html !-f RewriteRule ^(.*).html$ $1.php The problem is it doesn't work when I type in a url to a html page, I get a 404. Nothing in the error logs of Apache, just the 404 in the access log. It should redirect to the php. Now, the index.php does exist and I can go to that directly and the old index.html file doesn't exist. Yet, if I comment out the line RewriteCond $1.php -f It all works fine, i.e. it forwards my index.html requests to index.php. Any ideas why? The -f should test that the 'file exists' and $1 should be 'the file', I think? By the way, does anyone have a good, friendly mod_rewrite tutorial they'd recommend? A: In .htaccess you need not use ^ and $. All the rules apply to the urls relative to the current directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do task killers work? The usefullness of task killer apps is debated, but I'm wondering: how do they actually work? How is it possible to kill particular process? Is there an API for this, and if so what does it actually do? EDIT Worth adding: I saw task killer apps kill processes on not rooted devices. So, I wonder how is it possible to kill process, which you don't own in Android? A: In a nutshell, Automatic Task Killers work by polling the OS for a list of currently running processes and the memory they are consuming. Then either with an intelligent algorithm or with user input the Task Killers issue a call to the system telling the system to kill the process. There are two apis you can do this. They are * *Process.killProcess(int pid) *ActivityManager.killBackgroundProcesses(String packageName) This first works by invoking Process.killProcess(int pid) where pid is the unique identifier for a specific process. Android kills processes in the same way that linux does; however, a user may only kill processes that they own. In Android each app is run with a unique UID (UserID). Apps using this API an App can only kill their own processes, hence the following explanation in the docs for Process.killProcess(int pid): Kill the process with the given PID. Note that, though this API allows us to request to kill any process based on its PID, the kernel will still impose standard restrictions on which PIDs you are actually able to kill. Typically this means only the process running the caller's packages/application and any additional processes created by that app; packages sharing a common UID will also be able to kill each other's processes. When this method is called the signal is generated by the OS and sent to the process. Whenever a process receives a signal from the OS it must either handle that signal or immediately die. Signals such as SIG_KILL cannot be handled and result in the immediate death of the recipient process. If you want to kill processes that you don't have privileges to kill, i.e. its not your process, then you must switch users or escalate your privileges (on android this requires root privileges on the device). The second API works by telling the built in ActivityManager that you wan to kill processes associated with a specific Package. This API gets around the need for your UID to match the UID of the process because it requires the user to accept the KILL_BACKGROUND_PROCESSES permission. This permission signals to the OS that an app has been approved by the user as a task killer. When a task killer wants to kill an app, it tells the OS to kill the process allowing an app to get around the problem of only being able to kill processes that it owns. In the Android Docs it says that this API actually uses the first Process.killProcess API Have the system immediately kill all background processes associated with the given package. This is the same as the kernel killing those processes to reclaim memory; the system will take care of restarting these processes in the future as needed. If you want to know more I suggest you read about the Posix Signals and The Linux kill command
{ "language": "en", "url": "https://stackoverflow.com/questions/7502340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Centering Pascal's Triangle Output in C++ I have successfully written a code to output Pascal's Triangle in a somewhat triangular shape using cout.width(total_rows - current_row), but it looks like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1 1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1 I would like it to be completely centered. I figured out that I can take the number or characters in the bottom row, subtract the number of characters in the current row, and divide this by two to get the desired number of spaces per row [which would look like: cout.width((bottow_row_characters - current_row_characters) / 2) ], but I'm having trouble actually implementing this idea. I've tried computing just the bottom row and storing in it a string or array and then using string.length() or sizeof(array), but neither has worked. (sizeof always returns 4, which is incorrect) Here is the code: #include <iostream> #include <string> using namespace std; // Forward declaration of a function. int Pascal (int row, int column); /* The main function. * * Parameters: * none * * Return value: * 0 if we complete successfully, 1 if there was an error. */ int main () { // introduction cout << "\nPascal's Triangle!\n"; cout << "(Pascal's triangle is made by taking the sum of two numbers\n"; cout << "and placing that number directly underneath the two numbers.\n"; cout << "This creates a triangular array of binomial coefficients)\n\n"; // for loops to calculate and print out pascal's triangle for (int row = 0; row <= 15; row++) { cout.width(16 - row); for (int column = 0; column <= row; column++) { cout << Pascal(row, column) << " "; } cout << endl; } cout << endl; } /* This function calculates Pascal's triangle based on row and column position. * * Parameters: * row, column * * Return value: * the numbers in Pascal's triangle */ int Pascal (int row, int column) { // if statements to calculate pascal's triangle through recursion if (column == 0) return 1; else if (row == column) return 1; else return Pascal(row - 1, column - 1) + Pascal(row - 1, column); } A: I figured it out. You have to use the stringstream library to convert the integer line from the Pascal function to a string. You can then just use string.length() to figure out how many characters are in the string. Then you do the math that I was explaining earlier to adjust the output. Here's my code: /* * Pascal's Triangle: Prints the first 15 rows of Pascal's triangle. * */ #include <iostream> #include <string> #include <iomanip> #include <sstream> using namespace std; // Forward declaration of a function. int Pascal (int row, int column); int rowLength (int row, int column); /* The main function. * * Parameters: * none * * Return value: * 0 if we complete successfully, 1 if there was an error. */ int main () { // introduction cout << "\nPascal's Triangle!\n"; cout << "(Pascal's triangle is made by taking the sum of two numbers\n"; cout << "and placing that number directly underneath the two numbers.\n"; cout << "This creates a triangular array of binomial coefficients)\n\n"; // determination of how long the bottom row is int bottom_row; string bottom_row_characters; stringstream out; for (int row = 15; row <= 15; row++) { for (int column = 0; column <= row; column++) { out << " " << Pascal(row, column) << " "; } bottom_row_characters += out.str(); } // for loops to calculate and print out pascal's triangle for (int row = 0; row <= 15; row++) { cout.width((bottom_row_characters.length() - rowLength(row, 0)) / 2); for (int column = 0; column <= row; column++) { cout << " " << Pascal(row, column) << " "; } cout << endl; } cout << endl; } /* This function calculates Pascal's triangle based on row and column position. * * Parameters: * row, column * * Return value: * the numbers in Pascal's triangle */ int Pascal (int row, int column) { // if statements to calculate pascal's triangle through recursion if (column == 0) return 1; else if (row == column) return 1; else return Pascal(row - 1, column - 1) + Pascal(row - 1, column); } /* This function converts a row from Pascal's Triangle from integers to a string * * Parameters: * row, column * * Return value: * a string representing a row in Pascal's triangle */ int rowLength (int row, int column) { int current_row; string current_row_characters; stringstream out; for (int current_row = row; current_row <= row; current_row++) { for (int column = 0; column <= row; column++) { out << " " << Pascal(row, column) << " "; } current_row_characters += out.str(); } return current_row_characters.length(); } A: Make all the outputs constant width with std::setw: cout << setw(5);
{ "language": "en", "url": "https://stackoverflow.com/questions/7502344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Using reCAPTCHA with ASP.NET Does the reCAPTCHA usercontrol post a request to http://www.google.com/recaptcha/api/verify to verify the entered text matches the captcha, or is this done in the dll? A: Turns out it does make requests to Google. The first is a request from the client for a captcha image The second is a request from the server to validate the entered text against the image http://code.google.com/apis/recaptcha/docs/display.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7502346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rawprinterhelper network printer ASP.NET MVC I'm having trouble trying to print a document from a ASP.NET MVC3 application using RawPrinterHelper (the printer support class developed by Microsoft). I need to send RAW data to a printer which is locally connected to a computer in the network. In my development environment (MS Visual Studio 2010) everything works well. I installed the printer in my OS as a network printer and I pass the name of that printer to RawPrinterHelper. On the real test server things don't work at all. The OS is Windows 7 with IIS7. Indeed I need to use a network printer installed on the local Windows7 client from my application running on IIS. The applicationpooling identity is set as "Network Service". Everything works using the built-in web server for Visual Studio 2010. All the printers are tested and work. Thanks. A: I solved the problem. The issue is that the ASP.NET application is running on the IIS server and does not have access to network printers, but only to local printers. Then, every user in Windows OS has access only to his own network printers. The problem can be solved in this way: 1) Impersonate the ASP.NET application with a user of the OS 2) Grant the user privileges to use databases, etc 3) Create, logged in with THAT specific user profile, your network printers 4) Ready It is very important to provide RawPrinterHelper with the right name in string format. To do so check System.Drawing.Printing.PrinterSettings and get the list of installed printers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to use several images as the Google Maps v3 MarkerImage? I want a map marker composed of three images. Two images will be the same across all markers where one is variable. There doesn't seem to be a way to specify multiple images on the MarkerImage class. The only way that I can think of is to draw all the images to a canvas then outputting it as a png dataURL for the MarkerImage class. That seems like overkill though. A: I don't think it is possible with three separate images. If two of the images are always the same I guess you could combine them into one and store it in the icon property and then use the variable image in the shadow property or vise versa (the icon will always be on top of the shadow). You just need to manipulate the size and position of the MarkerImage objects. working example: http://jsfiddle.net/mG4uz/1/ var image1 = new google.maps.MarkerImage( 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png', new google.maps.Size(45, 90), //adjust size of image placeholder new google.maps.Point(0, 0), //origin new google.maps.Point(0, 25) //anchor point ); var image2 = new google.maps.MarkerImage( 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png', new google.maps.Size(45, 45), new google.maps.Point(0, 0), new google.maps.Point(0, 0) ); var marker = new google.maps.Marker({ position: centerPosition, map: map, icon: image1, shadow:image2 }); A: I would try to define a new class which would inherit from google.maps.MarkerImage that would allow it and then just call marker.setIcon() with this object. Also have a look here and here. A: Yes, you can use multiple images and set them as one image for each Marker Icon in your array of the map markers. What's more important is that you can use images that are on a remote server. For example, in my case, I loaded an array of sites that each has an image for the site, so I'm merging an image of a marker with the image of the site (received from server). Here is my solution: mergeImages(element) { var canvas: HTMLCanvasElement = this.canvas.nativeElement; var context = canvas.getContext('2d'); let img1 = new Image(); let img2 = new Image(); img1.onload = function () { canvas.width = img1.width; canvas.height = img1.height; img2.crossOrigin = 'anonymous'; img2.src = element.info.image || './assets/img/markers/markerIcon42.png'; }; img2.onload = () => { context.clearRect(0, 0, canvas.width, canvas.height); context.globalAlpha = 1.0; context.drawImage(img1, 0, 0); context.globalAlpha = 1; //Remove if pngs have alpha context.globalCompositeOperation = 'destination-over'; if (element.info.image === null) { context.drawImage(img2, 11, 4, 42, 42); } else { context.drawImage(img2, 15, 7, 35, 35); } var dataURL = canvas.toDataURL('image/png', 1.0); console.log(dataURL); this.markers.push({ lat: element.info.location.latitude, lng: element.info.location.longitude, controllerInfo: element.info, icon: { url: dataURL, labelOrigin: { x: 32, y: -10 }, scaledSize: { width: 64, height: 64 }, origin: { x: 0, y: 0 }, anchoriconAnchor: { x: 7, y: 7 }, }, controllerStaus: element.status, label: { text: element.info.siteName, color: "#ED2C2C", fontWeight: "500", fontSize: "14px" } }); console.log(this.markers); }; img1.src = './assets/img/markers/map-marker64.png'; } One Important thing to add is "img2.crossOrigin = 'anonymous';" this will prevent toDataUrl cors-orign error. This solution is good also for clustering I hope it will help A: You can use an excellent small library, RichMarker. Its documentation is here. You can even inherit it and create a custom marker class, something like this: Ns.Marker = function(properties) { RichMarker.call(this, properties); this.setContent('<div class="three-images-marker">' + properties.NsImage1 ? '<div class="marker-image-1"><img src="'+properties.NsImage1+'"/></div>' : '' + properties.NsImage2 ? '<div class="marker-image-2"><img src="'+properties.NsImage2+'"/></div>' : '' + properties.NsImage3 ? '<div class="marker-image-3"><img src="'+properties.NsImage3+'"/></div>'+ '</div>'); }; Ns.Marker.prototype = Object.create(RichMarker.prototype); And then use it like this: var gorgeousMarker = new Ns.Marker({ position: yourMarkerLatlng, map: yourMap, NsImage1: 'example.com/image1.png', NsImage2: 'example.com/image2.png', NsImage3: 'example.com/image3.png', }); 'Ns' is whatever namespace you use, if you do. From here on it's CSS work, you can position the images as you like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ICU upgrade for intl extension on zend server ce macosx Where do I install the new version of icu for intl ext on zend server ce macosx? I tried as described on readme file but it installed it in /usr/local/lib and zend server is in /usr/local/zend Zend phpInfo still shows the old one. How do I get it to work with zend? Thanks. A: Found great article in http://devzone.zend.com/1442/compiling-php-extensions-with-zend-server/ . worked for ubuntu 10.04.3 so also should work for mac: * *Install php sources from zend repository *install/update your libicu-dev and libicu42 *cd /usr/local/zend/share/php-source/php-5.3.7RC4/ext/intl/ */usr/local/zend/bin/phpize *./configure --with-php-config=/usr/local/zend/bin/php-config *make *make install
{ "language": "en", "url": "https://stackoverflow.com/questions/7502353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Windows Mobile C++ - Application design-type question i have my application skeleton working as expected - it might be that somebody has a good solution to what i am trying to achieve within Windows Mobile 6.5 enviroment. Here's what i am actually trying to do: Application running in background ( it sends periodically network packets to office server, packets are loaded with statistics data and pushed onto the server via Winsock2 and custom made protocol ). What 'background' means here - is an application that creates a window of 0,0 size and is minimized - i am thinking about going into the services with this, but the next thing that i require stops me today from doing this. I need this application to be 'visible' somewhere as an icon - i already know i can't do this in the 'tray' area as stated in this post: Windows Mobile C++ Tray Icon Now i was trying to utilize the: SHNotificationAdd - but this is ok for a 'notification' as the name says type of thing. So it popsup and you can click to hide it - this is bad. What i need to achieve is an icon that is visible during the application run cycle, so it flashes when there is no synchronization possible, it changes the icon when synchronization is done. I am a bit worried it can't be done - i even tried to go and code the "Home" plug-in for this purpose, but was told that some people have themes installed and it might be that my application won't be even visible to those guys. Now as we're going to deploy it to few places around ( 3 data centers spread across the country - around 130 people smart phones only ) - i need to be sure this application is visible even when there is a theme applied or customization done. Any chance this can be done ? I was kinda sure it can be done with a classic 'tray icon approach' until i found that 'tray icons' are not supported for normal applications. If there is something i can do - i would really appreciate if somebody could shed a bit of light on this for us all please. A: You'll have to move to a Windows Mobile paradigm for your app, as what you're trying to do isn't possible (as you're finding). A home screen plug in has problems if the user customizes it, and you are correct that there is no "tray". The icons in the corner (battery, signal strength, etc) are reserved for OEM use only. My recommendation would be to actually create a visible Form for your application. Maybe it shows just some simple status info like last upload time, amount of data transferred, etc. You then use the notifications to place a user notification during "events" such as the inability to connect (replacing your "flashing icon" idea) or when synchronization is complete (replacing your "changed icon" idea).
{ "language": "en", "url": "https://stackoverflow.com/questions/7502356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is a cursor the only alternative to do this kind of operation I'm trying to optimize a long transaction and I've seen that the following is done quite a few times: Declare @myCursor CURSOR FAST_FORWARD FOR SELECT field1, MIN(COALESCE(field2, -2)) FROM MyTable tempfact LEFT JOIN MyTable sd ON tempfact.ID = sd.ID AND sd.TransactionId = @transactionId WHERE tempfact.SomeField IS NULL AND tempfact.TransactionId = @transactionId GROUP BY tempfact.field1 OPEN @myCursor FETCH NEXT FROM @myCursor INTO @field1Variable, @field2Variable WHILE @@FETCH_STATUS = 0 BEGIN EXEC USP_SOME_PROC @field1Variable, @field2Variable FETCH NEXT FROM @myCursor INTO @field1Variable, @field2Variable END CLOSE @myCursor DEALLOCATE @myCursor The code for the USP_SOME_PROC sproc is as follows: IF NOT EXISTS (SELECT * FROM SomeTable WHERE Field1 = @field1) BEGIN INSERT INTO SomeTable (Field1, Field2) VALUES (@field1, @field2) END Like I mentioned this is done in quite a few places, tables and fields involved are different but the idea remains the same, and I'm sure that there might be a way to increase the performance of these sprocs if cursors are not used and probably by making this transaction faster an issue that we're having with a deadlock (a subject for another post) might be solved. A: You can use MERGE for this ;WITH Source AS ( SELECT field1, MIN(COALESCE(field2, -2)) as field2 FROM MyTable tempfact LEFT JOIN MyTable sd ON tempfact.ID = sd.ID AND sd.TransactionId = @transactionId WHERE tempfact.SomeField IS NULL AND tempfact.TransactionId = @transactionId GROUP BY tempfact.field1 ) MERGE SomeTable AS T USING Source S ON (T.Field1 = S.Field1) WHEN NOT MATCHED BY TARGET THEN INSERT (Field1, Field2) VALUES (field1, field2) ; A: I haven't had a chance to test this, but this should be close: you need to insert from a SELECT statement but also need to make sure that a corresponding record doesn't already exist in SomeTable INSERT INTO SomeTable (Field1, Field2) SELECT field1, MIN(COALESCE(field2, -2)) FROM MyTable tempfact LEFT JOIN MyTable sd ON tempfact.ID = sd.ID AND sd.TransactionId = @transactionId LEFT JOIN SomeTable st ON st.Field1 = tempfact.field1 WHERE tempfact.SomeField IS NULL AND tempfact.TransactionId = @transactionId AND st.Field1 IS NULL GROUP BY tempfact.field1 A: You need not have a cursor and can use bulk insert logic something like below INSERT INTO SomeTable (Field1, Field2) SELECT field1, MIN(COALESCE(field2, -2)) FROM MyTable tempfact LEFT JOIN MyTable sd ON tempfact.ID = sd.ID AND sd.TransactionId = @transactionId WHERE tempfact.SomeField IS NULL AND tempfact.TransactionId = @transactionId GROUP BY tempfact.field1 Hope this helps!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7502360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I use PHP or JS/HTML to dual post to a URL I know that it probably isn't possible to submit a form from one button to 2 various locations so I was wondering if someone knew of a solution. When I click submit on a form I have the following form tag: <FORM ACTION="http:site.com/servlets/RequestServlet" method="post"> But I want the form to have 2 action parameters. This way as soon as a user fills this form out, submits the form, the form is submitted to a SERVER AND a PHP script that will pull out the parameters submitted by the the form and email the user details about their form submission such as request ID etc. Over here the Servlet is submitted to so that a record can be made in the network but an email is required to be sent to a user after form submission in-case they need to reference later on to a rep about their request id for further assistance. How can I achieve the submission to a PHP script in addition to the submission to the Servlet that's already occurring? NOTE: I cannot modify the Servlet in any way as it does not belong to me. All I want to do as add the email function for a user to later reference their ticket id. A: Set a javascript onclick parameter for the submit button. So it will post to the action you set, but also run a function such as: function secondSubmit() { url = "myphpscript.php"; data = { someData: "data", someOtherData: 2 }; $.post(url, data, function(returnedData) { // can do something on return if you'd like here }); } someData and someOtherData will show up in PHP as $_POST["someData"] and $_POST["someOtherData"]. So basically, you will have the form submit to the first URL via the HTML form, and have the second form submitted via jQuery with this function. Alternatively, you can do both submissions in this function and have the form have no action. For more info, see here: http://api.jquery.com/jQuery.post/
{ "language": "en", "url": "https://stackoverflow.com/questions/7502362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change the image in the Inno Setup wizard banner How do I change the image in the banner of wizards. I know how to change it in the first page, using this command: WizardImageFile=C:\Documents and Settings\mybmp.bmp But my question is about following pages, where it shows standard image banner at the top. A: The banner at the top is controlled by the WizardSmallImageFile directive. For example: [Setup] ... WizardSmallImageFile=mysmallimage.bmp The maximum size of the bitmap is 55x58 pixels.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: SQL PhP insert query problem I have a html form on local pc which has a form, on submits POST's values to a php file on my server. The php file is supposed to enter the form values into database, but I keep getting the following error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc, lat, lng) VALUES ('test', '51.489755', '-3.177407')' at line 1 html form: <form action="http://www.myurl.co.uk/folder/Add.php" method="POST"> <input type="text" name="desc" id="desc" /> <input type="text" name="lat" id="lat" /> <input type="text" name="lng" id="lng" /> <input type="submit" value="submit" name="submit" /> </form> php: if($_POST) { $desc = mysql_real_escape_string(trim($_POST['desc'])); $lat = $_POST['lat']; $lng = $_POST['lng']; $posting = mysql_query("INSERT INTO tableName (desc, lat, lng) VALUES ('$desc', '$lat', '$lng')") or die(mysql_error()); I am pretty sure that the insert statement is correct as I have done this so many times, but for some reason won't do. I know the values from the form ar being sent, as if you look at the error I am getting, the form values are in the VALUES section in the query. any feedback is much appreciated A: desc is a reserved word. You have to escape it: $posting = mysql_query("INSERT INTO tableName (`desc`, `lat`, `lng`) VALUES ('$desc', '$lat', '$lng')") or die(mysql_error()); A: desc is a reserved word. Try this: $posting = mysql_query("INSERT INTO `tableName` (`desc`, `lat`, `lng`) VALUES ('$desc', '$lat', '$lng')") or die(mysql_error()); A: desc is a reserved keyword in mysql. In your query, replace desc by `desc` A: desc or DESC is a reserved keyword in SQL to signify the order of result. ASC = Ascending DESC = Descending. Change your SQL to INSERT INTO tableName (`desc`, lat, lng) VALUES ('$desc', '$lat', '$lng')
{ "language": "en", "url": "https://stackoverflow.com/questions/7502366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting CSV to array I have this array with airport codes and city names (around 3500 lines). code,city "Abilene, TX ",ABI "Adak Island, AK ",ADK "Akiachak, AK ",KKI "Akiak, AK ",AKI "Akron/Canton, OH ",CAK "Akuton, AK ",KQA "Alakanuk, AK ",AUK "Alamogordo, NM ",ALM I need to convert that file into a php array. This is my code so far: if(($handle = fopen('test.csv', 'r')) !== FALSE) { while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) { echo '<pre>'; print_r($data); echo '</pre>'; } fclose($handle); } Although I'm setting the delimiter and enclousure characters for the fgetcsv function, im getting this as a result: Array ( [0] => code [1] => city "Abilene [2] => TX " [3] => ABI "Adak Island [4] => AK " [5] => ADK "Akiachak [6] => AK " [7] => KKI "Akiak [8] => AK " [9] => AKI "Akron/Canton [10] => OH " [11] => CAK "Akuton [12] => AK " [13] => KQA "Alakanuk [14] => AK " [15] => AUK "Alamogordo [16] => NM " [17] => ALM ) A: Try this:- ini_set('auto_detect_line_endings', TRUE);/// (PHP's detection of line endings) write at the top. $csvrows = array_map('str_getcsv', file($filepath)); $csvheader = array_shift($csvrows); $csv = array(); foreach ($csvrows as $row) { $csv[] = array_combine($csvheader, $row); } A: If it's the linebreaks, you can try the brute-force method with: $file = file_get_contents("test.csv"); $data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file)); print_r($data); str_getcsv is available with PHP 5.3, or as workaround in the manual, via upgradephp or PHP_Compat. A: try- $csv = array(); if (($file = fopen('test.csv', 'r')) === false) { throw new Exception('There was an error loading the CSV file.'); } else { while (($line = fgetcsv($file, 1000)) !== false) { $csv[] = $line; } fclose($handle); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7502370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Graph API end point to get the new "per-app post privacy" controls A facebook user can now specify post privacy on per-application basis. This is explained by facebook on their blog. In my web application I let people specify privacy settings while posting to their news feed. If a user has specified rather restrictive privacy than the one with he is posting to, facebook will enforce the restrictive settings as specified by user. This results in bad user experience. I want to know if there is a way, preferably a Graph API end point, that lets me know this setting for a user. If I could fetch this information from Facebook, I could show a proper alert message, 'that to use a rather less restrictive privacy settings, (s)he will have to change his/her application specific privacy settings'. Or I could show only more restrictive privacy settings to the user while posting something in my UI. Any pointer to where Facebook has documented this new feature from developer point of view in details is also appreciated. A: I believe the privacy_setting table (available via FQL) provides what you're looking for. https://developers.facebook.com/docs/reference/fql/privacy_setting/ *An FQL table that returns the default privacy settings that a user has set for an app. To read the privacy table you need the following permissions: User access_token The data returned is for the user and the application associated with the given access token. Example Select the default settings you have set for this app (try this query for a test application): SELECT name, value, description, allow, deny, networks, friends FROM privacy_setting WHERE name = 'default_stream_privacy'*
{ "language": "en", "url": "https://stackoverflow.com/questions/7502375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Streaming PulseAudio to file (possibly with GStreamer) I'm on Ubuntu and I want to record PulseAudio output to a file, to make a recording of a pygame program. The format doesn't matter, because I can change it afterward, so raw audio is fine. Looking around, it seems like GStreamer may be able to handle this, but I'm not familiar with it, and extensive searching has not yielded an answer. So answers involving GStreamer or otherwise are welcome. Thanks! A: There is a monitor for each pulseaudio sink. You just need to get it's name: $ pactl list ... Sink #0 State: RUNNING Name: alsa_output.pci-0000_00_1b.0.analog-stereo Description: Internal Audio Analog Stereo Driver: module-alsa-card.c Sample Specification: s16le 2ch 44100Hz Channel Map: front-left,front-right Owner Module: 4 Mute: no Volume: 0: 40% 1: 40% 0: -23.87 dB 1: -23.87 dB balance 0.00 Base Volume: 96% -1.00 dB Monitor Source: alsa_output.pci-0000_00_1b.0.analog-stereo.monitor Latency: 119973 usec, configured 210000 usec Flags: HARDWARE HW_MUTE_CTRL HW_VOLUME_CTRL DECIBEL_VOLUME LATENCY ... Note line Monitor Source: alsa_output.pci-0000_00_1b.0.analog-stereo.monitor. It is your monitor source. First, you need to unmute it: $ pacmd Welcome to PulseAudio! Use "help" for usage information. >>> set-source-mute alsa_output.pci-0000_00_1b.0.analog-stereo.monitor false >>> exit And now you can record sound form it: $ parec \ > --format=s16le \ > --device=alsa_output.pci-0000_00_1b.0.analog-stereo.monitor \ > | oggenc --raw --quiet -o dump.ogg - Or with lame: $ parec \ > --format=s16le \ > --device=alsa_output.pci-0000_00_1b.0.analog-stereo.monitor \ > | lame -r - dump.mp3 The same could be done with gstreamer, but there is not much sense in it if you don't need some complex processing: $ gst-launch-0.10 \ > pulsesrc device=alsa_output.pci-0000_00_1b.0.analog-stereo.monitor \ > ! lame \ > ! filesink location=dump.mp3
{ "language": "en", "url": "https://stackoverflow.com/questions/7502380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to allow xml:lang attribute in XMLSchema? I want to allow the use of xml:lang attributes in some of my element of my XMLSchema. But i can't find anything which describes how to to it. A: You have to do a bit of hunting to piece this together from the standards. Here's the magic sauce you need in order to allow xml:lang attributes on your XML elements. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- Import xml: namespace --> <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="https://www.w3.org/2009/01/xml.xsd" /> <!-- ... ---> <xs:complexType name="myLanguagedElement"> <!-- ... --> <!-- use ref="" instead of name="", here in your attribute --> <xs:attribute ref="xml:lang" use="optional" /><!-- or "required" if you like --> </xs:complexType> </xs:schema> Edit: The new schemaLocation changed to https://www.w3.org/2009/01/xml.xsd A: You can either create your own attribute with xmlschema type language, or reference xml:lang attribute as in the example Import another XML schema. I hope this will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Wix: Passing Dialogue Control Values to Configurable Merge Modules I'm having trouble accomplishing a task with the Wix Toolset. In particular, I have a scenario where I have an MSI that configures an MSM (Configurable Module). The MSI has a custom UI dialogue from which user input is to be used to configure the MSM. When I try to configure the MSM using a hardcoded value for the address property as shown below it works fine and the MSM is configured correctly. (I believe this configuration happens and build-time as opposed to run-time - the issue may lay there.). The problem occurs when I use a custom dialogue to set the value of the address property at installation time (i.e run-time). The configurable module still uses the hardcoded value, rather than the users input. Is the problem because merge module configuration is done during build-time only. Is there a way to pass a value to the merge module from the UI of the main MSI? Here is an over simplified version: <?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> <Product Id="cf1d176d-2d57-435e-8e7f-abba14de821c" Language="1033"> <Media Id="1" Cabinet="SemanticEvolution.cab" EmbedCab="yes" /> <Property Id="Address" Value="http://127.0.0.1" /> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="INSTALLLOCATION" Name="Semantic Evolution"> <Merge Id="MergeModule" Language="1033" SourceFile="Module.msm" DiskId="1"> <ConfigurationData Name="EndpointAddressConfiguration" Value="[Address]" /> </Merge> </Directory> </Directory> </Directory> <Feature Id="SemanticEvolutionFeatures" Title="Semnatic Evolution" Level="1"> <Feature Id="TestFeature" Title="TestFeature" Level="1"> <MergeRef Id="MergeModule" /> </Feature> </Feature> <UI Id="CustomWixUI"> <UIRef Id="WixUI_FeatureTree" /> <DialogRef Id="ConfigurationDlg" /> <Publish Dialog="LicenseAgreementDlg" Control="Next" Event="NewDialog" Value="ConfigurationDlg">LicenseAccepted = "1"</Publish> <Publish Dialog="CustomizeDlg" Control="Back" Event="NewDialog" Value="ConfigurationDlg">NOT Installed</Publish> </UI> </Product> </Wix> Here is a snipet of the merge module: <Configuration Name="EndpointAddressConfiguration" Format="Text" /> <Substitution Table="CustomAction" Row="SetEndpointAddress" Column="Target" Value="[=EndpointAddressConfiguration]" /> <CustomAction Id="SetEndpointAddress" Property="EndpointAddress" Value="[EndpointAddress]" /> <InstallExecuteSequence> <Custom Action="SetEndpointAddress" Before="LaunchConditions">1</Custom> </InstallExecuteSequence> Eventually in the merge module the configured property is used as follows: <util:XmlFile Id="EndpointAddress" Action="setValue" ElementPath="/configuration/system.serviceModel/client/endpoint/@address" File="[#Se.Gui.exe.config]" Value="[EndpointAddress]/ApiDataService"/> A: Remember that public properties must be in UPPERCASE. You can find the answer here: http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Passing-properties-to-merge-modules-td5417112.html A: To access a property from a merge module you must append the merge module id to the property name. Something like: MyProp.msm_guid http://msdn.microsoft.com/en-us/library/aa370051(VS.85).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7502383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PS3 Browser Capabilities I am trying to find out what the PS3 web browser is like in terms of CSS, JS, Flash, etc. I found some articles saying it is pretty bad, but these are several years old and the PS3 software is frequently updated so I can't trust things like this. Can anyone point me at official specs or a recent analysis? Your own test results are welcome but please state how recent they are. A: This is an old post, but thought I'd add to it. A quick visit to acid3.acidtests.com shows that my (up-to-date) PS3 is now getting a 99% score. It's actually a little lower since the test also requires pixel-perfect rendering and smooth animation, neither of which it has yet. (One of the boxes is gray when it should be yellow, and the animation is jerky.) Whatsmyuseragent.com shows that it's running WebKit 531.22.8, which must be behind the improvement. It's strange that they're using 531 in a 2012 system update since that build is almost three years out of date. But regardless it's a huge leap forward compared to what they had before. A: The latest specs I could find showed the PS3 getting an ACID3 score of 27 (http://en.wikipedia.org/wiki/Acid3) and a similar Wikipedia page details the capabilities of the NetFront engine, which is used by the PS3: http://en.wikipedia.org/wiki/NetFront. These results are from a January 2011 release, but the release notes for subsequent updates don't show any modifications to it. There are also a few questions on here which can give you a pointer to potential issues such as: Javascript not working on PS3 Browser. A: As of PS3 firmware 4.50, a custom fork of the WebKit browser is used that masquerades as Netfront NX. It is roughly equivalent in HTML, CSS, and JavaScript functionality to an iPad 1 running iOS 5.0 in terms of functionality -- except that the PS3 also includes a Flash 9.x runtime. Having the Flash 9 runtime allows for using polyfills for WebSockets, Promises, and other HTML5/ES6 features. It does effectively pass the Acid3 test, which some minor alignment issues like most 2012-era browsers. A decent JavaScript development setup that is using webpack and Flash 9 polyfills should be able to produce a JS bundle targeting PS3, Xbox 360, and Android 2.x with pretty advanced functionality comparable to modern mobile browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Toggle Map Markers I wonder whether someone may be able to help me please. I'm trying to put some code together where I can load markers from a mySQL database onto my map with the markers falling into one of four categories. What I would like to do, if possible, is to toggle which markers are shown or hidden by way of check boxes which I've set up on my form. I can get the code to work which pulls the marker data and plots them on my map but I'm struggling to get the section that allows the markers to be shown or hidden to work. I've used this as a starting point, but I've obviously not understood the example correctly. I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong. Many thanks and kind regards Chris <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Map My Finds - Public Finds</title> <link rel="stylesheet" href="css/publicfinds.css" type="text/css" media="all" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script> <script type="text/javascript"> var customIcons = { "Artefact": { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Coin": { icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Jewellery": { icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Precious Metal": { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' } }; function load() { var map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(54.312195845815246,-4.45948481875007), zoom:6, mapTypeId: 'terrain' }); var infoWindow = new google.maps.InfoWindow; // Change this depending on the name of your PHP file downloadUrl("PHPFILE.php", function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName("marker"); var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < markers.length; i++) { var findcategory = markers[i].getAttribute("findcategory"); var findname = markers[i].getAttribute("findname"); var finddescription = markers[i].getAttribute("finddescription"); var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("findosgb36lat")), parseFloat(markers[i].getAttribute("findosgb36lon"))); var html = "<b>" + 'Find : ' + "</b>" + findname + "<p>" + "<b>" + 'Description: ' + "</b>" + finddescription + "</p>" var icon = customIcons[findcategory] || {}; var marker = new google.maps.Marker({ map: map, position: point, icon: icon.icon, shadow: icon.shadow }); bounds.extend(point); map.fitBounds(bounds); bindInfoWindow(marker, map, infoWindow, html); } }); } // == shows all markers of a particular category, and ensures the checkbox is checked == function show(category) { for (var i=0; i<markers.length; i++) { if (markers[i].mycategory == findcategory) { markers[i].setVisible(true); } } // == check the checkbox == document.getElementById(category+"box").checked = true; } // == hides all markers of a particular category, and ensures the checkbox is cleared == function hide(category) { for (var i=0; i<markers.length; i++) { if (markers[i].mycategory == findcategory) { markers[i].setVisible(false); } } // == clear the checkbox == document.getElementById(findcategory+"box").checked = false; // == close the info window, in case its open on a marker that we just hid infowindow.close(); } // == a checkbox has been clicked == function boxclick(box, findcategory) { if (box.checked) { show(findcategory); } else { hide(findcategory); } function bindInfoWindow(marker, map, infoWindow, html) { google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(map, marker); }); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } function doNothing() {} } </script> </head> <body onLoad="load()"> <p>&nbsp;</p> <form id="Public Finds" method="post" action=""> <p align="left"> <input name="artefact" type="checkbox" id="artefact" value="checkbox" /> Artefact </p> <p align="left"> <input name="coin" type="checkbox" id="coin" value="checkbox" /> Coin</p> <p align="left"> <input name="jewellery" type="checkbox" id="jewellery" value="checkbox" /> Jewellery</p> <p align="left"> <input name="preciousmetal" type="checkbox" id="preciousmetal" value="checkbox" /> Precious Metal</p> </form> <p>&nbsp;</p> <div id="map"></div> </body> </html> UPDATED CODE <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Map My Finds - Public Finds</title> <link rel="stylesheet" href="css/publicfinds.css" type="text/css" media="all" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script> <script type="text/javascript"> var customIcons = { "Artefact": { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Coin": { icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Jewellery": { icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' }, "Precious Metal": { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png', shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png' } }; var gmarkers = []; function load() { var map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(54.312195845815246,-4.45948481875007), zoom:6, mapTypeId: 'terrain' }); var infoWindow = new google.maps.InfoWindow; // Change this depending on the name of your PHP file downloadUrl("PHPFILE.php", function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName("marker"); var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < markers.length; i++) { var findcategory = markers[i].getAttribute("findcategory"); var findname = markers[i].getAttribute("findname"); var finddescription = markers[i].getAttribute("finddescription"); var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("findosgb36lat")), parseFloat(markers[i].getAttribute("findosgb36lon"))); var html = "<b>" + 'Find : ' + "</b>" + findname + "<p>" + "<b>" + 'Description: ' + "</b>" + finddescription + "</p>" var icon = customIcons[findcategory] || {}; var marker = new google.maps.Marker({ map: map, position: point, icon: icon.icon, shadow: icon.shadow }); marker.mycategory = findcategory; bounds.extend(point); map.fitBounds(bounds); bindInfoWindow(marker, map, infoWindow, html); } }); } // == shows all markers of a particular category, and ensures the checkbox is checked == function show(findcategory) { for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].mycategory == findcategory) { gmarkers[i].setVisible(true); } } // == check the checkbox == document.getElementById(findcategory+"box").checked = true; } // == hides all markers of a particular category, and ensures the checkbox is cleared == function hide(category) { for (var i=0; i<gmarkers.length; i++) { if (gmarkers[i].mycategory == findcategory) { gmarkers[i].setVisible(false); } } // == clear the checkbox == document.getElementById(findcategory+"box").checked = false; } // == a checkbox has been clicked == function boxclick(box,findcategory) { if (box.checked) { show(findcategory); } else { hide(findcategory); } function myclick(i) { google.maps.event.trigger(gmarkers[i],"click"); } // == show or hide the categories initially == hide("artefact"); hide("coin"); hide("jewellery"); hide("precious_metal"); function bindInfoWindow(marker, map, infoWindow, html) { google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(map, marker); }); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } function doNothing() {} } </script> </head> <body onLoad="load()"> <p>&nbsp;</p> <form action="#"> Artefact: <input type="checkbox" id="artefactbox" onclick="boxclick(this,'artefact')" /> &nbsp;&nbsp; Coin: <input type="checkbox" id="coinbox" onclick="boxclick(this,'coin')" /> &nbsp;&nbsp; Jewellery: <input type="checkbox" id="jewellerybox" onclick="boxclick(this,'jewellery')" /> &nbsp;&nbsp; Precious Metal: <input type="checkbox" id="preciousmetalbox" onclick="boxclick(this,'preciousmetal')" /><br /> </form> <p>&nbsp;</p> <div id="map"></div> </body> </html> A: Looks like you need to have something that actually calls your boxclick function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: visual svn / tortoise svn authentication issue I setup visual SVN on windows server 2008 named myserver It asked me to create a username/password since I selected Subversion Authentication. I then created an empty repository called myproject. I also installed tortoise svn on my Dev box Windows 7 and trying to access with repository browser http://myserver:8080/svn/myproject/ however it gives me the same error all the time. "OPTIONS of 'http://myserver:8080/svn/myproject/' Could not read status line: An existing connection was closed by the remote host. http://myserver:8080/" I also tried windows basic with the same result. What's missing here? Also when I try to browse to http://myserver:8080/svn/ it says "Repository moved permanently to 'http://myserver:8080/'; please relocate" Is this some sort of permissions issue? One more thing - when I navigate to 'http://myserver:8080/svn/myproject/' on my web browser it asks me for the user/password and lets me browse the folders. A: I also install VisualSVN in Windows Server 2003(ESERVER,222.200.164.202), use TortoiseSVN in local Windows 7. And I choose Using Subversion Authentication as well. For the whole Repositories, or the repository call "myproject", check your account has the right to access. Using https instead of http. VisualSVN suggest using https instead of http. VisualSVN may prevent access thought http. All of All, try https plz. :) A: The problem was I had to specify the ip address in server bindings. once i did that all worked as expected. A: * *For Subversion Authentication (in VisualSVN Server) you must create at least 1 user in Management Console and give him appropriate permissions for repo|repos *Check for must-have files in repo-root htpasswd (contain users and digestedpasswords) authz (groups and path-based ACLs) when I try to browse to http://myserver:8080/svn/ it says "Repository moved permanently to 'http://myserver:8080/'; please relocate" Is this some sort of permissions issue? No, it's configuration issue for Location. Anyway, best way to find correct URL for repo inside VisualSVN server is Copy URL from repo context-menu in management console
{ "language": "en", "url": "https://stackoverflow.com/questions/7502398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to download/gunzip a file and obtain an InputStream of the actual file? I have a url of a gzipped file. I would like to obtain an InputStream of the actual file in Java. What is the best way to achieve this? A: Do you mean, something like GZIPInputStream? InputStream is = .... InputStream gis = new GZIPInputStream(is);
{ "language": "en", "url": "https://stackoverflow.com/questions/7502404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bitwise operation there is 4 properties and each one of them can be activated. To know which one is activated i receive an int value. Using bitwise and operation i get 1, 2, 4 or 8 each number correspond to an activated property. if((state & 1) == 1) { status = 1; } else if ((state & 2) == 2) { status = 2; } else if((state & 4) == 4) { status = 4; } else if((state & 8) == 8) { status = 8; } I was wondering if could calculate status with one bitwise operation ? Thanks. A: If state always has exactly one of the four bits set, then your code is not very useful, as it is the same as status = state; If state can have any number of bits set, your code sets status to the least significant set bit in state. This can also be done with: status = state & -state;
{ "language": "en", "url": "https://stackoverflow.com/questions/7502409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to pass Table-Valued Parameters (Array-like Parameter) to Stored Procedure in Microsoft SQL Server 2008 R2 using JDBC? How to pass Table-Valued Parameters (Array-like Parameter) to Stored Procedure in Microsoft SQL Server 2008 R2 using Microsoft SQL Server 2008 R2 JDBC Driver ? Is it possible with jTDS? A: The current (3.0) Microsoft driver doesn't support passing TVPs. At one point, Microsoft was soliciting votes for TVP vs. Bulk Copy: http://blogs.msdn.com/b/jdbcteam/archive/2011/09/22/tvp-or-bulk-copy.aspx TVP got more votes, but it remains to be seen what actually got done. The most recent CTP for version 4.0 doesn't appear to have TVP support. A: While this question was about SQL Server 2008, and while it really wasn't possible to pass table valued parameters at the time, it is now. This is documented here in the JDBC driver manual. For example, it could be done like this: SQLServerDataTable table = new SQLServerDataTable(); table.addColumnMetadata("i" ,java.sql.Types.INTEGER); table.addRow(1); table.addRow(2); table.addRow(3); table.addRow(4); try (SQLServerPreparedStatement stmt= (SQLServerPreparedStatement) connection.prepareStatement( "SELECT * FROM some_table_valued_function(?)")) { // Magic here: stmt.setStructured(1, "dbo.numbers", table); try (ResultSet rs = stmt.executeQuery()) { ... } } I've also recently blogged about this here. A: I have solved this problem by myself. I have created CLR .Net Stored Proc with accepts a BLOB parameter. This BLOB is just a list of serialized INTs. It is possible to deserialize it using T-SQL or .Net CLR SP. .Net CLR SP has better performance, which was really important for my project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create table by clicking buttons Here's what I want to do. Hopefully it's not too hard. I need to create a table with a div inside each td which is created by clicking buttons... for example Please select the number of rows in the table Please select the number of columns in the table.. Result: So if you clicked on 4 and 4 it would create a table 4 X 4. If you clicked 3 X 1, you would create a table 3 X 1, etc... Any help would be greatly appreciated!! Here's a jfiddle of something I'm trying to get working. I'm still looking over all your comments! http://jsfiddle.net/irocmon/7WD8v/ I know I need to add in the Javascript how to get the element by id. A: I would use 2 forms, 1 for the top row of numbers and one for the second row of numbers, where each number is a predefined value of the user input. Assign the submit button to each of the numbers using javascript for each form and from there grab the results with javascript and perform the code/script that is required to complete the task in mind. I would recommend using jquery for this. Have fun... A: you should be able to achieve this with some pretty simple if statements or a switch if you have 2 variables rows & columns //loop for number of rows for "x" number of rows{ document.write("<tr>"); if(columns > 0) { switch statement to output column 1: document.write("<td></td>"); 2: document.write("<td></td><td></td>"); } document.write("</tr>"); } the syntax is very very psuedo here, this code wont work but it might get you started, what are you actually wanting to do with the table once you have it? A: Using javascript, have 2 local variables: width and height. Within each DIV, have an onclick function that assigns that value to the proper variable, then checks to see if both variables have been assigned (this way they can click on either height or width first). If both are, use these variables within a for loop to generate HTML code within javascript: var HTML = '<table>'; for(var i = 0; i < height; i++) { HTML += '<tr>'; for(var j = 0; j < width; j++) { HTML += '<td>...</td>';} HTML += '</tr>';} document.getElementById('where_you_want_the_table').innerHTML = HTML; A: This is tested and work of note it doesn't handle if they keep trying to build the tables over and over it will keep adding cols and rows but I will let you handle that. :) <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> var Rows = 0; var ColString = ""; var TableBuilder; $(document).ready(function () { $("#Rows input").click(function () { Rows = $(this).val(); }); $("#Cols input").click(buildCols); $("#Submit").click(CreateTable); }); function buildCols() { for (i = 0; i < $(this).val(); i++) { ColString = ColString + "<td></td>"; } return ColString; } function CreateTable() { if (Rows == 0 || ColString == "") { $("#PleaseSelect").removeClass("displayNone"); } else { for (i = 0; i < Rows; i++) { TableBuilder = TableBuilder + "<tr>" + ColString + "</tr>"; } $("#table tbody").html(TableBuilder); } } </script> <style type="text/css"> .displayNone { display: none; } </style> </head> <body> <table id="table" border="1"> <tbody> </tbody> </table> <br><br> How many Rows? <div id="Rows"> <input type="button" value="1"> <input type="button" value="2"> <input type="button" value="3"> <input type="button" value="4"> </div> <br /> How Many Columns? <div id="Cols"> <input type="button" value="1" > <input type="button" value="2"> <input type="button" value="3"> <input type="button" value="4"> </div> <br /> <div id="PleaseSelect" class="displayNone">Please select both a column number and a row number.</div> <input type="button" id="Submit" value="Build Table" /> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7502411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I add a condition to an existing conditional expression? I had a programmer write a Perl script for my site. One of the functions is to update price/stock when a certain condition is met. # update when price/stock conditions met if ( ($force_price_updates == 1) || ($data->{'price'} <= $product_price && $data->{'quantity'} > 0) || ($product_quantity == 0 && $data->{'quantity'} > 0) ) { What the above is not doing is not updating the price if the new price is higher. It updates the stock value, but if the new stock comes at a higher price, I lose out. Stock gets updated and but the price is not. The script goes through a number of feeds and if the same product is found in any of the feeds, the script should amend price/stock change according to the rule above. I can't find the programmer and my Perl knowledge is limited. I understand what the code is doing, but don't know what it should do if the price is higher and stock is greater than zero. A: You can add the extra condition you're looking for to that statement. The condition you're looking to match is: $data->{'price'} > $product_price && $product_quantity > 0 So the final version would look like this: if (($force_price_updates == 1) || ($data->{'price'} <= $product_price && $data->{'quantity'} > 0) || ($product_quantity == 0 && $data->{'quantity'} > 0) || ($data->{'price'} > $product_price && $product_quantity > 0)) {
{ "language": "en", "url": "https://stackoverflow.com/questions/7502420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set pixels on screen efficiently I am using WindowAPI (http://www.mathworks.com/matlabcentral/fileexchange/31437) to show a black full screen in matlab. When drawing on screen, turns out drawing using line() and rectangle() functions is extremely slow. How can I set values of pixels without going through matlab's mechanism? Getting the window's canvas for example would be great. A: One way to imitate a "canvas" is by using a MATLAB image. The idea is to manually change its pixels and update the 'CData' of the plotted image. Note that you can use an image with the same dimensions as your screen size (image pixels will correspond to screen pixels one-to-one), but updating it would be slower. The trick is to keep it small and let MATLAB map it to the entire fullscreen. That way the image can be thought of as having "fat" pixels. Of course the resolution of the image is going to affect the size of the marker you draw. To illustrate, consider the following implementation: function draw_buffer() %# paramters (image width/height and the indexed colormap) IMG_W = 50; %# preferably same aspect ratio as your screen resolution IMG_H = 32; CMAP = [0 0 0 ; lines(7)]; %# first color is black background %# create buffer (image of super-pixels) %# bigger matrix gives better resolution, but slower to update %# indexed image is faster to update than truecolor img = ones(IMG_H,IMG_W); %# create fullscreen figure hFig = figure('Menu','none', 'Pointer','crosshair', 'DoubleBuffer','on'); WindowAPI(hFig, 'Position','full'); %# setup axis, and set the colormap hAx = axes('Color','k', 'XLim',[0 IMG_W]+0.5, 'YLim',[0 IMG_H]+0.5, ... 'Units','normalized', 'Position',[0 0 1 1]); colormap(hAx, CMAP) %# display image (pixels are centered around xdata/ydata) hImg = image('XData',1:IMG_W, 'YData',1:IMG_H, ... 'CData',img, 'CDataMapping','direct'); %# hook-up mouse button-down event set(hFig, 'WindowButtonDownFcn',@mouseDown) function mouseDown(o,e) %# convert point from axes coordinates to image pixel coordinates p = get(hAx,'CurrentPoint'); x = round(p(1,1)); y = round(p(1,2)); %# random index in colormap clr = randi([2 size(CMAP,1)]); %# skip first color (black) %# mark point inside buffer with specified color img(y,x) = clr; %# update image set(hImg, 'CData',img) drawnow end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7502422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dataset XML question In VB.NET when I use the WriteXML of DataSet, can I customize it? That is to say; I want to make a structure like this: <products> <product id="" title=""> <product id="" title=""> <product id="" title=""> </products> How can I do? Thanks.. A: you can use DataSet.GetXml Method and ColumnMapping accordingly Dim column As DataColumn For Each column In ds.Tables.Item(0).Columns column.ColumnMapping = MappingType.Attribute Next Dim xml As String = ds.GetXml()
{ "language": "en", "url": "https://stackoverflow.com/questions/7502423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTTP post from android to PHP not working I am trying to get a Android device to send some information to a local host. I believe I have the Android sending the information, but my PHP code is not accepting or not displaying the code. I have attached my code, is there something I have missed? I am running wamp server also, and have put the permissions into the manifest. Java Code: # HttpPost httppost; HttpClient httpclient; // List with arameters and their values List<NameValuePair> nameValuePairs; String serverResponsePhrase; int serverStatusCode; String bytesSent; String serverURL = "http://10.0.2.2/test/index.php"; httppost = new HttpPost(serverURL); httpclient = new DefaultHttpClient(); nameValuePairs = new ArrayList<NameValuePair>(2); // Adding parameters to send to the HTTP server. nameValuePairs.add(new BasicNameValuePair("parameterName1", "git")); nameValuePairs.add(new BasicNameValuePair("parameterName2", "git")); // Send POST message with given parameters to the HTTP server. try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } bytesSent = new String(baf.toByteArray()); // Response from the server serverResponsePhrase = response.getStatusLine().getReasonPhrase(); serverStatusCode = response.getStatusLine().getStatusCode(); System.out.println("COMPLETE"); } catch (Exception e) { // Exception handling System.out.println("Problem is " + e.toString()); } PHP Code: <?php echo "param1 value: ".$_POST['parameterName1']."\n"; echo "param2 value: ".$_POST['parameterName2']."\n"; ?> I also tried this code, but it did not work with my PHP HttpPost httppost; HttpClient httpclient; // List with arameters and their values List<NameValuePair> nameValuePairs; String serverResponsePhrase; int serverStatusCode; String bytesSent; String serverURL = "http://10.0.2.2/test/index.php"; httppost = new HttpPost(serverURL); httpclient = new DefaultHttpClient(); nameValuePairs = new ArrayList<NameValuePair>(2); // Adding parameters to send to the HTTP server. nameValuePairs.add(new BasicNameValuePair("'parameterName1'", "git")); nameValuePairs.add(new BasicNameValuePair("'parameterName2'", "git")); // Send POST message with given parameters to the HTTP server. try { HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs); httppost.addHeader(entity.getContentType()); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } bytesSent = new String(baf.toByteArray()); // Response from the server serverResponsePhrase = response.getStatusLine().getReasonPhrase(); serverStatusCode = response.getStatusLine().getStatusCode(); System.out.println("response" + response.toString()); System.out.println("COMPLETE"); } catch (Exception e) { // Exception handling System.out.println("Problem is " + e.toString()); } A: Make sure the Content-Type HTTP header is getting set. Try replacing httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); with this HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs); httppost.addHeader(entity.getContentType()); httppost.setEntity(entity); Also, instead of response.toString(), try EntityUtils.toString(response.getEntity()) if you want to see the body of the response
{ "language": "en", "url": "https://stackoverflow.com/questions/7502430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle - How to create a readonly user It's possible create a readonly database user at an Oracle Database? How? A: A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges. When you create a user CREATE USER ro_user IDENTIFIED BY ro_user DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp; the user doesn't even have permission to log in to the database. You can grant that GRANT CREATE SESSION to ro_user and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like GRANT SELECT ON schema_name.table_name TO ro_user Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like Create the role CREATE ROLE ro_role; Grant the role SELECT access on every table in a particular schema BEGIN FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME') LOOP EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || ' TO ro_role'; END LOOP; END; And then grant the role to the user GRANT ro_role TO ro_user; A: Execute the following procedure for example as user system. Set p_owner to the schema owner and p_readonly to the name of the readonly user. create or replace procedure createReadOnlyUser(p_owner in varchar2, p_readonly in varchar2) AUTHID CURRENT_USER is BEGIN execute immediate 'create user '||p_readonly||' identified by '||p_readonly; execute immediate 'grant create session to '||p_readonly; execute immediate 'grant select any dictionary to '||p_readonly; execute immediate 'grant create synonym to '||p_readonly; FOR R IN (SELECT owner, object_name from all_objects where object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP execute immediate 'grant select on '||p_owner||'.'||R.object_name||' to '||p_readonly; END LOOP; FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP execute immediate 'grant execute on '||p_owner||'.'||R.object_name||' to '||p_readonly; END LOOP; FOR R IN (SELECT owner, object_name FROM all_objects WHERE object_type in('TABLE', 'VIEW') and owner=p_owner) LOOP EXECUTE IMMEDIATE 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"'; END LOOP; FOR R IN (SELECT owner, object_name from all_objects where object_type in('FUNCTION', 'PROCEDURE') and owner=p_owner) LOOP execute immediate 'create synonym '||p_readonly||'.'||R.object_name||' for '||R.owner||'."'||R.object_name||'"'; END LOOP; END; A: create user ro_role identified by ro_role; grant create session, select any table, select any dictionary to ro_role; A: you can create user and grant privilege create user read_only identified by read_only; grant create session,select any table to read_only; A: It is not strictly possible in default db due to the many public executes that each user gains automatically through public.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to do an onListItemClick? I have an Activity and I want to do a setOnListItemClick on my Listview but I seem unable to do it. I am only able to do it with ListActivity but I need an EditText so I can't use the ListActivity. Can anyone help me? public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listview = (ListView) findViewById(R.id.listview); edittext = (EditText) findViewById(R.id.search_box); arrayA = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, eventTitle); setListAdapter(arrayA); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // Get the item that was clicked } A: When you use a listactivity youcan use other layout elements and views. The only rule is, there must be a listview with an id as @android:id/list. Here's the doc explaining it clearly. So there should be nothing preventing you from using an edittext in an listactivity. Are you having doubt's on creating a xml layout with an edittext and listview?
{ "language": "en", "url": "https://stackoverflow.com/questions/7502439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display image with requestFileSystem and toUrl() function I made an application who use requestFileSystem. Everything works fine. Add a new image and store it in an persistent local file system. Does anybody know how to display an image with toUrl() ? ... window.requestFileSystem(window.PERSISTENT, 5*1024*1024, function(fs){ fs.root.getDirectory(itemId, {create: false}, function(dirEntry) { var dirReader = dirEntry.createReader(); var entries = []; var readEntries = function() { dirReader.readEntries (function(results) { if (!results.length) { listResults(entries.sort(), itemId); } else { entries = entries.concat(fsdatas.dir.toArray(results)); readEntries(); } }, errorHandler); }; readEntries(); }); }, errorHandler); ... And function listResults(entries, itemId) { document.querySelector('#listRecordFiles-'+itemId).innerHTML = ''; var fragment = document.createDocumentFragment(); var i = 0; entries.forEach(function(entry, i) { i++; var img = document.createElement('img'); img.src = entry.toURL(); fragment.appendChild(img); }); document.querySelector('#listRecordFiles-'+itemId).appendChild(fragment); } The output is : <img src="filesystem:http://domain.tld/persistent/1/image-test.jpg"> But nothing is displayed on browser. A: The example below is a snippet of code responsible for reading the images saved in the application's root directory, and show in the document body. Remember, in this case, I used navigator.camera.DestinationType.DATA_URL to open the PHOTOLIBRARY, and saved the image content using atob (ascii to binary), so carry the image with btoa (binary to ascii) function myLoadFile(filename) { var myDocument = document.querySelector("body"); filesystem.root.getFile(filename, {}, function(fileEntry) { fileEntry.file(function(file) { var reader = new FileReader(); reader.onload = function(e) { var img = document.createElement('img'); // if you save the file with atob (ascii to binary), then: img.src = "data:image/jpeg;base64,"+btoa(this.result); // if you don't save the file without atob, then: // img.src = "data:image/jpeg;base64,"+this.result; myDocument.appendChild(img) }; reader.readAsText(file); }, errorHandler); }, errorHandler); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7502452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Process.Start opens too many browsers in XNA game I'm creating a game in XNA that runs on a PC. On the splash screen, the user has three options. If they press "Enter" the game will begin, if they press "M" they'll go to the Help menu and if they press "W" I want that to take them to my website. I'm using Process.Start to open the browser to my website. The problem is that when I press "W", sometimes it will open 1 browser with the website. However, most of the time it will open anywhere from 3 - 7 browsers simultaneously. Why is it opening multiple browsers simultaneously? How do I make it open only 1 browser when "W" is pressed? Here is my code. I haven't built my website yet, so I'm using yahoo.com as the destination: private void UpdateSplashScreen() { KeyboardState keyState = Keyboard.GetState(); if (gameState == GameState.StartScreen) { if (keyState.IsKeyDown(Keys.Enter)) { gameState = GameState.Level1; explosionTime = 0.0f; } if (keyState.IsKeyDown(Keys.M)) { gameState = GameState.HelpScreen; } if (keyState.IsKeyDown(Keys.W)) { Process.Start("IExplore.exe", "www.yahoo.com"); } } Thanks, Mike A: A common way to handle this is to always track the keyboard state from the previous frame. If a key wasn't down on the previous frame, but is down this frame then you know it was just pressed. If the key was down on the previous frame then you know it's being held down. // somewhere in your initialization code KeyboardState keyState = Keyboard.GetState(); KeyboardState previousKeyState = keyState; ... private void UpdateSplashScreen() { previousKeyState = keyState; // remember the state from the previous frame keyState = Keyboard.GetState(); // get the current state if (gameState == GameState.StartScreen) { if (keyState.IsKeyDown(Keys.Enter) && !previousKeyState.IsKeyDown(Keys.Enter)) { gameState = GameState.Level1; explosionTime = 0.0f; } if (keyState.IsKeyDown(Keys.M) && !previousKeyState.IsKeyDown(Keys.M)) { gameState = GameState.HelpScreen; } if (keyState.IsKeyDown(Keys.W) && !previousKeyState.IsKeyDown(Keys.W)) { Process.Start("IExplore.exe", "www.yahoo.com"); } } I usually create a KeyPressed function which cleans things up a bit. bool KeyPressed(Keys key) { return keyState.IsKeyDown(key) && !previousKeyState.IsKeyDown(key); } A: The code you are using runs about 60 times a second; you may only press your key down for 100ms or so but in that time it checks to see if W is pressed down about 7 times. As such, it opens a large number of browser windows. Try recording a timestamp (using DateTime.Now) of when you open the browser and then check that a certain time has elapsed (~2 secs?) before allowing another window to be opened. Or, create a boolean flag that is set false by opening the browser, so the browser can be opened only once. A: Thanks guys, that's what the problem was. Callum Rogers solution was the easiest: I declared a boolean: bool launchFlag = false; Then checked it and set it to true after the website launched. private void UpdateSplashScreen() { KeyboardState keyState = Keyboard.GetState(); if (gameState == GameState.StartScreen) { if (keyState.IsKeyDown(Keys.Enter)) { gameState = GameState.Level1; explosionTime = 0.0f; } if (keyState.IsKeyDown(Keys.M)) { gameState = GameState.HelpScreen; } if (keyState.IsKeyDown(Keys.W)) { if (launchFlag == false) { Process.Start("IExplore.exe", "www.yahoo.com"); launchFlag = true; } } } I held the W key down for 30 seconds and it launched just 1 browser! Thanks, Mike
{ "language": "en", "url": "https://stackoverflow.com/questions/7502454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hibernate: "InstantiationException: Cannot instantiate abstract class or interface" I have the following class hierachy: public class MailAccount{ IncomingMailServer incomingServer; OutgoingMailServer outgoingServer; } public class MailServer{ HostAddress hostAddress; Port port; } public class IncomingMailServer extends MailServer{ // ... } public class OutgoingMailServer extends MailServer{ // ... } public class ImapServer extends IncomingMailServer{ // ... } public class Pop3Server extends IncomingMailServer{ // ... } public class SmtpServer extends OutgoingMailServer{ // ... } My (simplified) mapping file looks like this: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.mail.account"> <class name="MailAccount" table="MAILACCOUNTS" dynamic-update="true"> <id name="id" column="MAIL_ACCOUNT_ID"> <generator class="native" /> </id> <component name="incomingServer"> <component name="hostAddress"> <property name="address" column="IS_HOST_ADDRESS"></property> </component> <component name="port"> <property name="portNumber" column="IS_PORT_NUMBER"></property> </component> </component> <component name="outgoingServer"> <component name="hostAddress"> <property name="address" column="OS_HOST_ADDRESS"></property> </component> <component name="port"> <property name="portNumber" column="OS_PORT_NUMBER"></property> </component> </component> </class> </hibernate-mapping> The problem: Hibernate throws this exception when I call session.save(mailAccountInstance);: org.hibernate.InstantiationException: Cannot instantiate abstract class or interface: IncomingMailServer So, I added the following lines to the incomingServer component: <discriminator column="SERVER_TYPE" type="string"/> <subclass name="ImapServer" extends="IncomingMailServer" discriminator-value="IMAP_SERVER" /> <subclass name="Pop3Server" extends="IncomingMailServer" discriminator-value="POP3_SERVER" /> And to the outgoing server: <discriminator column="SERVER_TYPE" type="string"/> <subclass name="SmtpServer" extends="OutgoingMailServer" discriminator-value="SMTP_SERVER" /> But now, Hibernate gives me this error message: org.xml.sax.SAXParseException: The content of element type "component" must match "(meta*,tuplizer*,parent?,(property|many-to-one|one-to-one|component|dynamic-component|any|map|set|list|bag|array|primitive-array)*)". Obviously, Hibernate does not like these tags in components. How could I work around this? Ps: I already tried moving IncomingServer and OutgoingServer each to their own tables and map them via a one-to-one. That works but leads to inconsistencies in the database because I noticed that MailAccount and IncomingServer/OutgoingServer must always have the same primary key id. If not, everything gets out of sync and the autoincrement value for the primary keys don't match any more (between Mailaccount and Servers). A: This mapping worked for me: Hibernate Mapping <class name="MailServer" abstract="true" table="SERVER"> <id name="id" column="id"> <generator class="native" /> </id> <discriminator column="SERVER_TYPE" type="string"/> <subclass name="IncomingMailServer" abstract="true"> <property name="address" column="IS_HOST_ADDRESS"></property> <property name="portNumber" column="IS_PORT_NUMBER"></property> </subclass> <subclass name="OutgoingMailServer" abstract="true"> <property name="address" column="OS_HOST_ADDRESS"></property> <property name="portNumber" column="OS_PORT_NUMBER"></property> </subclass> </class> <subclass name="IMAPServer" extends="com.mail.account.IncomingMailServer" discriminator-value="IMAP_SERVER"/> <subclass name="POP3Server" extends="com.mail.account.IncomingMailServer" discriminator-value="POP3_SERVER"/> <subclass name="SMTPServer" extends="com.mail.account.OutgoingMailServer" discriminator-value="SMTP_SERVER" /> Class Hierarchy Abstract classes: * *MailServer is an abstract class *IncomingServer is an abstract class : this helped NOT specifing DISCRIMINATOR VALUE *OutgoingServer is an abstract class : this helped NOT specifing DISCRIMINATOR VALUE Concrete classes: * *IMAPServer extends IncomingServer with DISCRIMINATOR VALUE : IMAP *POP3Server extends IncomingServer with DISCRIMINATOR VALUE : POP3 *SMTPServer extends IncomingServer with DISCRIMINATOR VALUE : SMTP All the concrete servers are mapped to the same table "SERVER" however if need be they can be mapped to individual tables using join table. Code Snippet I was able to save the instances using the following simple code snippet: Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction txn =session.beginTransaction(); IMAPServer imap=new IMAPServer(); imap.setAddress("SMTP_01"); imap.setPortNumber("SMTP_PORT_0001"); session.save(imap); SMTPServer smtp=new SMTPServer(); smtp.setAddress("STMP_01"); smtp.setPortNumber("STMP_PORT_0001"); session.save(smtp); MailAccount account=new MailAccount(); account.setIncomingServer(imap); account.setOutgoingServer(smtp); session.save(account); txn.commit(); Let me know if this solves the problem. :) EDIT: added the mapping from MailAccount to MailServer. <class name="MailAccount" table="MAILACCOUNT" dynamic-update="true"> <id name="id" column="id"> <generator class="native" /> </id> <many-to-one name="incomingServer" column="incoming" unique="true"/> <many-to-one name="outgoingServer" column="outgoing" unique="true"/> </class> A: My approach would be this: * *Create a Entity (with it's own mapping) MailServer with discriminators and all. Mark it abstract just to be sure. *Create the hierarchy of MailServer (one hbm for each) with it's own discriminator. *Map MailAccount with 2 one-to-one relationships to MailServer. One incoming, one outgoing. And, please, show us more code. It's hard to help without know :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7502455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what is the escape oracle sql sequence while inserting a record? I'm inserting a record in oracle database, where I'm taking values from a java bean. It goes like this:: insert into allergy (patient_id, allergy, reaction) values(seq_patient.nextval, '" + bean.getPatient_allergy() + "', '"+ bean.getReaction()+"')"; But the values for allergy can gave an apostrophe which causes the sql to fail with ORA-00917: missing comma. is there any way to overcome this problem? A: Use parameterized statements instead of injecting variables into a query: http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html A: It's better to use bind variables in preference to building your query as a string. That'll take care of your problem. It will also prevent SQL injection attacks (also, see Bobby Tables). Here is some info on how to use prepared statements and bind variables in Java: link. A: How about using parameterized query instead of assembling the INSERT command? Tha would also fix your current SQL Injection vulnerability.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check variables from different lines with awk I want to combine values from multiple lines with different lengths using awk into one line if they match. In the following sample match values for first field, aggregating values from second field into a list. Input, sample csv: 222;a;DB;a 222;b;DB;a 555;f;DB;a 4444;a;DB;a 4444;d;DB;a 4444;z;DB;a Output: 222;a|b 555;f 4444;a|d|z How can I write an awk expression (maybe some other shell expression) to check if the first field value match with the next/previous line, and then print a list of second fields values aggregated and separated by a pipe? A: awk ' BEGIN {FS=";"} { if ($1==prev) {sec=sec "|" $2; } else { if (prev) { print prev ";" sec; }; prev=$1; sec=$2; }} END { if (prev) { print prev ";" sec; }}' This, as you requested, checks the consecutive lines. A: does this oneliner work? awk -F';' '{a[$1]=a[$1]?a[$1]"|"$2:$2;} END{for(x in a) print x";"a[x]}' file tested here: kent$ cat a 222;a;DB;a 222;b;DB;a 555;f;DB;a 4444;a;DB;a 4444;d;DB;a 4444;z;DB;a kent$ awk -F';' '{a[$1]=a[$1]?a[$1]"|"$2:$2;} END{for(x in a) print x";"a[x]}' a 555;f 4444;a|d|z 222;a|b if you want to keep it sorted, add a |sort at the end. A: Assuming that you have set the field separator ( -F ) to ; : { if ( $1 != last ) { print s; s = ""; } last = $1; s = s "|" $2; } END { print s; } The first line and the first character are slightly wrong, but that's an exercise for the reader :-). Two simple if's suffice to fix that. (Edit: Missed out last line.) A: Slightly convoluted, but does the job: awk -F';' \ '{ if (a[$1]) { a[$1]=a[$1] "|" $2 } else { a[$1]=$2 } } END { for (k in a) { print k ";" a[k] } }' file A: this should work: Command: awk -F';' '{if(a[$1]){a[$1]=a[$1]"|"$2}else{a[$1]=$2}}END{for (i in a){print i";" a[i] }}' fil Input: 222;a;DB;a 222;b;DB;a 555;f;DB;a 4444;a;DB;a 4444;d;DB;a 4444;z;DB;a Output: 222;a|b 555;f 4444;a|d|z
{ "language": "en", "url": "https://stackoverflow.com/questions/7502459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: when closing google marker go back to center of map I have a map which opens multiple markers then when you click on one of the markers a street view of that location opens up. What Im trying to do is when you close the marker have it re-center the map A: You can always get the center of a map (getCenter()), so you will know the lat/long before you open a Street View image. There are then setCenter() and panTo() methods in the API: http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
{ "language": "en", "url": "https://stackoverflow.com/questions/7502464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LESS mixin with multiple variables I'm trying to make a mixin with multiple variables in LESS, but for some reason it's not working. I have this LESS: .rgbabg(@r: 0, @g: 0, @b: 0, @a: .5) { @val: rgba(@r, @g, @b, @a); background: @val; } I call it like this: .rgbabg(255, 0, 0, .5); But I don't get any background on my element at all. Is my syntax ok? A: Your syntax of your mixin is fine, and it compiles fine. I tried it out in my LESS converter and it's all good. I applied the rule to a page for an a tag selector: a { .rgbabg(255); } And it outputs: a { background: rgba(255, 0, 0, 0.5); } which colors my links just like it sounds like it should. What version of LESS are you compiling with - what platform and version of the complier? I wouldn't recommend the Ruby compiler as I don't think it's kept up much anymore, and all the cool new features and support are on the Javascript less.js project. If you're doing it in PHP or .NET then you should check with those projects respectively.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to store configuration variables in mysql? M'y script's variables are currently stored in a php File as an array. I want to store them in mysql database, however I don't if I should store them as rows or columns. If I use columns it would be easier to retrieve them (only one query), but if I have too many variables the page would have to scroll horizontally and I think it would be hard to find data in phpmyAdmin. If I use rows then how would I retrieve all of them using a single query and store them in the $config array? Any ideas or suggestions? A: Create config table, with 2 columns Name | Value and select it with SELECT * FROM config so it will look like Name | Value offline | 1 message | Hello guys! This is my custom message to get them into $config, use $result = (mysql_query("SELECT * FROM config")); while($row = mysql_Fetch_assoc($result){ $config[$result['Name']] = $result['Value']; } that's it! A: Depends.. Are the variables user-based? Do you need to search them? One way to store is in a serialized format (string data in a text field) -- this will suffice if you don't need to search the variables. Otherwise, just store one row per (user-)key-value combination.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is an API introduced in Honeycomb working on Gingerbread? In the documentation for DatabaseUtils.concatenateWhere(...) it is stated that it is supported from API level 11+ (HONEYCOMB). However, while testing compatibility on various devices, that on my Droid X running Cyanogenmod 7 nightly build 98 (based on gingerbread 2.3.5), the method call not only does not cause a crash, but works as expected. Is this some inconsistency with my custom ROM, or can anyone else reproduce this functionality on another device that is running Gingerbread or lower? Could this be an error in the SDK documentation? A: It looks like an error in the documentation. GrepCode shows that the method exists in Android 2.3.4_r1. In fact, the method exists in all versions including 1.5_r4. A: Well, Android 2.3.5 was released after Honeycomb. I don't find it unreasonable that Google might have implemented certain APIs from Honeycomb to help fight fragmentation. I wouldn't count on it working in other versions of Gingerbread though, without thorough testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to transform Unicode characters to a different font? I was able to transform sinhala Unicode characters to symbols by just copying those characters into MS word and changing the font to TIMES NEW ROMAN, The letters are in the link image; sequence of symbols and letters = fnda, rduqj - .Kl rduqj But now I can't changed those Unicode characters into sequence of symbols and letters. Every time I paste those characters it doesn't allow me to change to another font type. How can I make it changeable or is there a better way of getting that sequence of letters?
{ "language": "en", "url": "https://stackoverflow.com/questions/7502475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using getch() to hold command prompt open Visual C++ 2010 Im currently learning c++ from a book called 'Ivor Hortons Beginning Visual c++ 2010'. In all the examples i've attempted so far I've had to use getch() to hold open the command prompt, and sometimes remove the return 0 statement from the end of the main method. Is this a vagary of windows 7 and will it cause problems further down the line? It's no problem doing this at the moment but since this is not included in the book I was wondering if it might be something I've set up wrong. Many Thanks :) A: Use _getch() in place of getch() A: getch() is not operating system specific, but it is not directly portable. The preferred method for doing this in C++ is to use std::cin.get();. The main function can return 0 implicitly (you don't need to actually have that code, see below). int main() { // valid, return 0 implied. } See this question for more details about the implicit return 0 from main. A: When a program ends, any resources created by that program including the terminal window will be released. By using getch you prevent the program from ending. This is normal behavior and should continue to work that way until Windows is a distant memory. If you start the program from within an already existing command window, the window will not close because it wasn't created by the program. A: First, getch() isn't a standard C or C++ function. Even under Windows, I think its use is deprecated; its semantics go back to CP/M and early MS-DOS. Secondly, it really isn't necessary, at least not for console apps (and I don't think it's available for non-console apps). If you're running the program from a console window, the window stays open. And if you're running it from Visual Studios, it's trivial to set a breakpoint on the return statement, which blocks the program, and keeps the window open (although there's really no reason for the IDE to close it just because your program has terminated).
{ "language": "en", "url": "https://stackoverflow.com/questions/7502476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Category.php - products show in subcats but not in categories if it has no subcategories Below is my category.php that uses a switch statement to either show subcategories or products. When i click on a subcategory, it displays the products like it's supposed to. However, if the category has NO SUBCATEGORIES, no products will show at all. Is this a case where the switch statement needs to be altered, the entire foreach loop needs to be in an if statement or is there something wrong with the db and the ids... all of my cats in the menu have a parent_id = 0, subcats correspond to the id for the category table, the products are assigned a category_id. Is this a JOIN thing? <?php foreach ($listing as $key => $list){ echo "<img src='".$list['thumbnail']."' border='0' align='left' />"; echo "<h4>"; switch($level){ case "1": echo anchor('welcome/cat/'.$list['id'],$list['name']); break; case "2": echo anchor('welcome/product/'.$list['id'],$list['name']); break; } echo "</h4>"; echo "<p>".$list['shortdesc']."</p><br style='clear:both'/>"; } ?> Any help is much appreciated. the $level is located in the welcome controller. function cat($id){ $cat = $this->MCats->getCategory($id); if (!count($cat)){ redirect('welcome/index','refresh'); } $data['title'] = "Company |" .$cat['name']; if ($cat['parentid'] < 1){ // show other cats $data['listing'] = $this->MCats->getSubCategories($id); $data['level'] = 1; }else{ // show products $data['level'] = 2; $data['listing'] = $this->MCats->getProductsByCategory($id); } $data['category'] = $cat; $data['main'] = 'category'; $data['navlist'] = $this->MCats->getCategoriesNav(); $this->load->vars($data); $this->load->view('template'); } get products by category function... This selects the products based on category_id in the products table. still no show though... function getProductsByCategory($catid){ $data = array(); $this->db->select('id,name,shortdesc,thumbnail'); $this->db->where('category_id',$catid); $this->db->where('status','active'); $Q = $this->db->get('products'); if ($Q->num_rows() > 0){ foreach ($Q->result_array() as $row){ $data[] = $row; } } $Q->free_result(); return $data; } A: Count the number of sub categotries returned in your model; if it's 0; return false to the controller. Then do a test to see if $listing is an array, or false, and output the appropiate data or message to the user. A: Try doing following. First you check in database, does requested category have products. Then check does it have subcategories. If sencond is false, then choose first and display products linked to main category. If main category has no products, but it does have subcategories and the do have products, then it work as described in your code. If main category has no products and no subcategories, then there is no point in displaying it at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Anything similar to a microcontroller interrupt handler? Is there some method where one could use a try statement to catch an error caused by a raise statement, execute code to handle the flag e.g. update some variables and then return to the line where the code had been operating when the flag was raised? I am thinking specifically of an interrupt handler for a micro-controller (which does what ive just described). I am writing some code that has a thread checking a file to see if it updates and I want it to interrupt the main program so it is aware of the update, deals with it appropriately, and returns to the line it was running when interrupted. Ideally, the main program would recognize the flag from the thread regardless of where it is in execution. A try statement would do this but how could I return to the line where the flag was raised? Thanks! Paul EDIT: My attempt at ISR after comments albeit it looks like a pretty straight forward example of using locks. Small test routine at the bottom to demonstrate code import os import threading import time def isr(path, interrupt): prev_mod = os.stat(path).st_mtime while(1): new_mod = os.stat(path).st_mtime if new_mod != prev_mod: print "Updates! Waiting to begin" # Prevent enter into critical code and updating # While the critical code is running. with interrupt: print "Starting updates" prev_mod = new_mod print "Fished updating" else: print "No updates" time.sleep(1) def func2(interrupt): while(1): with interrupt: # Prevent updates while running critical code # Execute critical code print "Running Crit Code" time.sleep(5) print "Finished Crit Code" # Do other things interrupt = threading.Lock() path = "testfil.txt" t1 = threading.Thread(target = isr, args = (path, interrupt)) t2 = threading.Thread(target = func2, args = (interrupt,)) t1.start() t2.start() # Create and "Update" to the file time.sleep(12) chngfile = open("testfil.txt","w") chngfile.write("changing the file") chngfile.close() time.sleep(10) A: One standard OS way to handle interrupts is to enqueue the interrupt so another kernel thread can process it. This partially applies in Python. I am writing some code that has a thread checking a file to see if it updates and I want it to interrupt the main program so it is aware of the update, deals with it appropriately, and returns to the line it was running when interrupted. You have multiple threads. You don't need to "interrupt" the main program. Simply "deal with it appropriately" in a separate thread. The main thread will find the updates when the other thread has "dealt with it appropriately". This is why we have locks. To be sure that shared state is updated correctly. You interrupt a thread by locking a resource the thread needs. You make a thread interruptable by acquiring locks on resources. A: In python we call that pattern "function calls". You cannot do this with exceptions; exceptions only unroll the stack, and always to the first enclosing except clause. Microcontrollers have interrupts to support asynchronous events; but the same mechanism is also used in software interrupts for system calls, because an interrupt can be configured to have a different set of protection bits; the system call can be allowed to do more than the user program calling it. Python doesn't have any kind of protection levels like this, and so software interrupts are not of much use here. As for handling asynchronous events, you can do that in python, using the signal module, but you may want to step lightly if you are also using threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ant compiling error for junit testcase in other source folder with similar package structure <target name="compile.src" depends="init" description="compile the source code " > <javac srcdir="${src}" destdir="${build}/src"> <classpath> <fileset dir="lib"> <include name="**/*.jar"/> </fileset> </classpath> <compilerarg value="-Xlint"/> </javac> </target> <path id="classpath.test"> <fileset dir="${basedir}/lib"> <include name="**/*.jar"/> </fileset> <fileset dir="${build}/src"> <include name="**/*.class"/> </fileset> </path> <echo>${src.test} and tausif ${build}\test </echo> <target name="compile.test" depends="compile.src" description="compile the test code " > <javac srcdir="${src.test}" destdir="${build}/test" debug="true" classpathref="classpath.test"> <!--classpath refid="classpath.test" /--> <compilerarg value="-Xlint"/> </javac> </target> my structure for project is project > src > example.samplePackage > test > example.samplePackage I am trying to compile first source folder in src and then trying to include all class files during compiling junit testcases in test source folder in similar package structure. But it is showing me below Error.Please suggest something. [javac] C:\Project\test\examples\samplePackage\SampleTest.java:9: cannot find symbol [javac] symbol : class Sample [javac] location: package examples.samplePackage [javac] import example.samplePackage.Sample; ^ A: Your compile.test Ant target uses the compile.test classpath which is declared as: <path id="classpath.test"> <fileset dir="${basedir}/lib"> <include name="**/*.jar"/> </fileset> <fileset dir="${build}/src"> <include name="**/*.class"/> </fileset> Is the "C:\Project\test\" folder amongst those?
{ "language": "en", "url": "https://stackoverflow.com/questions/7502485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bubble sort algorithm JavaScript Please can you tell me what is wrong to this implementation of bubble sort algorithm in JavaScript? for (var i=1; i<records.length; i++){ for (var j=records.length; j<1; j--){ if (parseInt(records[i-1]) < parseInt(records[i])){ var temp = records[i-1]; records[i-1] = records[i] records[i] = temp; } } } A: for (var j=records.length; j<1; j--){ Shouldn't that be for (var j=records.length; j>1; j--){ A: Couple of codes for bubble sort bubblesort should not be used for larger arrays, can be used for smaller ones for its simplicity. Optimized way, with all Checks const bubble_Sort = (nums) => { if(!Array.isArray(nums)) return -1; // --->if passed argument is not array if(nums.length<2) return nums; // --->if array length is one or less let swapped=false temp=0, count=-1, arrLength=0; do{ count ++; swapped=false; arrLength = (nums.length-1) - count; //---> not loop through sorted items for(let i=0; i<=arrLength; i++){ if(nums[i]>nums[i+1]){ temp=nums[i+1]; nums[i+1]=nums[i]; nums[i]=temp; swapped=true; } } } while(swapped) return nums; } console.log(bubble_Sort([3, 0, 2, 5, -1, 4, 1])); Method 1 var a = [33, 103, 3, 726, 200, 984, 198, 764, 9]; function bubbleSort(a) { var swapped; do { swapped = false; for (var i=0; i < a.length-1; i++) { if (a[i] > a[i+1]) { var temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; swapped = true; } } } while (swapped); } bubbleSort(a); console.log(a); Method 2 function bubbleSort(items) { var length = items.length; //Number of passes for (var i = 0; i < length; i++) { //Notice that j < (length - i) for (var j = 0; j < (length - i - 1); j++) { //Compare the adjacent positions if(items[j] > items[j+1]) { //Swap the numbers var tmp = items[j]; //Temporary variable to hold the current number items[j] = items[j+1]; //Replace current number with adjacent number items[j+1] = tmp; //Replace adjacent number with current number } } } } Method 3 function bubbleSort() { var numElements = this.dataStore.length; var temp; for (var outer = numElements; outer >= 2; --outer) { for (var inner = 0; inner <= outer-1; ++inner) { if (this.dataStore[inner] > this.dataStore[inner+1]) { swap(this.dataStore, inner, inner+1); } } console.log(this.toString()); } } A: A simple implementation in ES6 JavaScript will be function BubbleSort(arr) { const sortedArray = Array.from(arr); let swap; do { swap = false; for (let i = 1; i < sortedArray.length; ++i) { if (sortedArray[i - 1] > sortedArray[i]) { [sortedArray[i], sortedArray[i - 1]] = [sortedArray[i - 1], sortedArray[i]]; swap = true; } } } while (swap) return sortedArray; } console.log(BubbleSort([3, 12, 9, 5])); A: you should use j instead of i in the second loop, and don't forget to change the j<1 to j>1 A: I believe that in a bubble sort, once the i loop has completed an iteration, then the i'th element is now in its correct position. That means that you should write the j loop as for (var j = i + 1; j < records.length; j++) Otherwise your bubble sort will be (even more) inefficient. A: My solution: function bubbleSort(A){ var swapped, len = arr.length; if(len === 1) return; do { swapped = false; for(var i=1;i<len;i++) { if(A[i-1] > A[i]) { var b = A[i]; A[i] = A[i-1]; A[i-1] = b; swapped = true; } } } while(swapped) } var arr = [1, 6, 9, 5, 3, 4, 2, 12, 4567, 5, 34]; bubbleSort(arr); document.write(arr); A: the second for loop is coded wrong it should be for (var i=0; i<records.length; i++){ for (var j=0; j<records.length; j++){ if (parseInt(records[i]) > parseInt(records[j])){ var temp = records[i]; records[i] = records[j]; records[j] = temp; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7502489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Questions About Creating An Order Total In Magento I am attempting to create an order total module to do some custom price adjustments. Just to get started with this I am just trying to get it to add $20 to every single order (eventually putting in the real logic). I am having issues with the module that I created. The first issue is that it appears to be running twice (so it is taking $40 off instead of only $20 -- Logging showed me that both the collect and fetch methods are being run twice) The second issue is that the discount line item is appearing below the Grand Total line. Can someone tell me what I am doing wrong here? The contents of my config.xml and order total class are below. config.xml Content <global> <sales> <quote> <totals> <mud> <class>Wpe_Multiunitdiscount_Model_Multiunitdiscount</class> <before>grand_total</before> </mud> </totals> </quote> </sales> </global> Wpe_Multiunitdiscount_Model_Multiunitdiscount Content class Wpe_Multiunitdiscount_Model_Multiunitdiscount extends Mage_Sales_Model_Quote_Address_Total_Abstract { public function collect(Mage_Sales_Model_Quote_Address $address) { $address->setGrandTotal($address->getGrandTotal() + 20 ); $address->setBaseGrandTotal($address->getBaseGrandTotal() + 20); return $this; } public function fetch(Mage_Sales_Model_Quote_Address $address) { $address->addTotal(array( 'code' => $this->getCode(), 'title' => Mage::helper('sales')->__('Super Tax'), 'value' => 20, )); return $this; } } A: Regarding the "double" issue, as far as I understand it, it's because magento collects your total twice, once for the shipping address and once for the billing address. I'm sure there has to be a better way to manage this, but for now I've added in the first line of my collect method: if ($address->getData('address_type')=='billing') return $this; And for the "placement", have you try with "after" instead of "before" (changing the total alias, of course, let's say "tax" for example")? HTH A: You cannot touch any other totals when adding your own custom total. Please see this thread for more information: Magento upfront payment
{ "language": "en", "url": "https://stackoverflow.com/questions/7502491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect if cookies are turned off I would like to detect if a user has cookies turned off and redirect them. Ideally I would like this to work throughout my site so that at any stage if the user turns cookies off they would be redirected to a page of my choice. Who anyone have a idea of how to achieve this. I was thinking of creating a helper but I'm hoping there might be a neater simpler method of doing this? A: This is not as simple as it may first seem, because there are several aspects of your application that affect functionality here: * *What do you do when user first visits your root URL *What to do when users get a link that is not root URL *Can cookies be periodically checked Why do you need users to have cookies turned on? Please explain your business process maybe it this can be mitigated differently. Additional info You say you're persisting user info using a cookie. This is basically the same as Session stores its Session ID. Inside a cookie. This is also the same as any forms authentication where upon login you store all or part of user information inside a cookie that gets accessed every time user makes a request. This makes it possible for you to use existing methods to achieve the same goal and not reinvent the wheel. 1. Write a custom HttpModule Your module should be checking for that extra bit of information that you'd like to pass over each time your users make requests. If that data is not present you can redirect your user even before it gets to the application pipeline. But invest enough time to think out the whole process with all different possible executions like first access, turned off cookies, turning them off afterwards etc. 2. Use cookies or/and Sessions By using Sessions you have to make sure that your module executes after session module otherwise session data will always be missing. Using just cookies won't have this issue. But this heavily depends on the amount of data that you wish to preserve. If there's too much of it (and is volatile) you should put some in session and just keep a handle in cookie that will get you to session data. A completely different cookie-less option A completely different option is a combination of Asp.net MVC routing and server persistence (Session/Cache/DB whatever). This is somehow similar to cookie-less sessions, but this time manually done with Asp.net MVC routing. Suppose this routing definition: routes.MapRoute( "Retention" "{handle}/{controller}/{action}/{id}", new { Controller = "Home", Action = "Index", Id = UrlParameter.Optional }, new { Handle = "\d+" } // set your own constraint according to your needs ); routes.MapRoute( "Default" "{controller}/{action}/{id}", new { Controller = "Home", Action = "Index", Id = UrlParameter.Optional } ); This way you will keep your user persistence data handle in URL which will still work even though user would turn off cookies. To avoid failing sessions along with it you should persist data in some other storage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Execute .NET code at runtime Suppose i write 'piece of code' in a text file. Is it possible to read that file at runtime and...execute ? For example, suppose my software have a method1, method2 and method3 methods. In a text file i write any simple piece of code, like: dim i as integer i = method1() + method2() console.write(i) How can execute it dinamically, at runtime ? A: CodeDOMProvider and the System.CodeDom.Compiler Namespace is where you will want to start. But you will have to write more extensive code than your sample. A: There is an example on MSDN for both VB and C#
{ "language": "en", "url": "https://stackoverflow.com/questions/7502501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MSVCP90.DLL is missing I installed Microsoft Visual Studio 9.0 and created a simple command line C++ project (.EXE file). When I'm trying to execute it an error modal windows is saying: "The program can't start because MSVCP90.DLL is missing from your computer". The file exists on the machine at c:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\msvcp90.dll. What am I doing wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7502503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Values from two group by select statements into one I have a table for logging method calls. It has LogId, MethodId, DateTime columns. I need to write a select statement that counts all logs for specific method IDs over a specific time period and also show the number of logs for the specific methods over a different time period. The first bit is simple: select l.[MethodId], count(l.[LogId]) as [Count] from [Log] l (nolock) where l.[DateTime] between @from and @to and l.[MethodId] in @methodIds group by l.[MethodId] But now I need a second column in that table, Previous, which would look like this if it was in a separate statement: select l.[MethodId], count(l.[LogId]) as [Previous] from [Log] l (nolock) where l.[DateTime] between @before and @from and l.[MethodId] in @methodIds group by l.[MethodId] Not all methods will will have logs for the two time periods, so would be nice if the join would insert 0 in the count/previous columns in those cases instead of them being null. It's ok if a method doesn't have any logs in either periods. What I want to see is MethodId, Count, Previous in one table. How do I make this happen? A: Something like: select l.[MethodId], sum(case when datetime between @from and @to then 1 else 0 end) as count, sum(case when datetime between @before and @from then 1 else 0 end) as previous from [Log] l where l.[DateTime] between @before and @to and l.[MethodId] in @methodIds group by l.[MethodId] The BETWEEN clause in the where doesn't affect the output then, but it might affect performance if you have an index on datetime. And if this table can get big, you probably should have such an index. A: Try this: select l.[MethodId], count(isnull(l.[LogId],0)) as [Previous] from [Log] l (nolock) where l.[DateTime] between @before and @from and l.[MethodId] in @methodIds group by l.[MethodId]
{ "language": "en", "url": "https://stackoverflow.com/questions/7502507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Super simple MVC question, how does it know what the ID is of an object you're editing? Having trouble grasping this: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Movie movieToEdit) { var originalMovie = (from m in _db.MovieSet where m.Id == movieToEdit.Id select m).First(); In this case you've posted your form, and it gets the movie you're going to edit by checking movieToEdit.Id However I don't understand how it knows what the Id is. I thought that movieToEdit was created by examining the View. The fields on the View are only: <fieldset> <legend>Fields</legend> <p> <label for="Title">Title:</label> <%= Html.TextBox("Title", Model.Title) %> <%= Html.ValidationMessage("Title", "*") %> </p> <p> <label for="Director">Director:</label> <%= Html.TextBox("Director", Model.Director) %> <%= Html.ValidationMessage("Director", "*") %> </p> <p> <label for="DateReleased">DateReleased:</label> <%= Html.TextBox("DateReleased", String.Format("{0:g}", Model.DateReleased)) %> <%= Html.ValidationMessage("DateReleased", "*") %> </p> <p> <input type="submit" value="Save" /> </p> </fieldset> Presumably when you hit save it will construct the movieToEdit based on the textboxes on the page automatically. But Id isn't one of the fields on the page, so how does it know what it is? Does it create hidden fields for properties such as Id automatically? A: ID is most likely in your URL since default MVC route definition is: {controller}/{action}/{id} Your <form> in the view most likely posts back to something like: http://www.yourappaddress.com/movies/edit/N where N is movie ID. All other movie property values are sent via form POST values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7502511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Wait until other frame in frameset has finished loading I am trying to do some changes to a different frame using javascript, but I need to wait until it is properly loaded. I have frame-B which does some changes to the content of frame-A. I have set a flag in frame-A when it has finished loading: frame-A: // Flag to indicate that the page is loaded. Used by frame-B var documentLoaded = false; $(document).ready(function () { documentLoaded = true; }); frame-B: function onLeftFramesLoad(loops) { // Check if the menu frame is finished loading, if not try again in Xms. // To Avoid eternal loop if for some reason the documentLoaded flag is not set after Y seconds: break loop. if (!parent.frames[0].window || !parent.frames[0].window.documentLoaded && loops < 40) { setTimeout(onLeftFramesLoad(loops + 1), 250); return; } // do changes to frame-A } // Using jQuery here to wait for THIS frame to finish loading. $(document).ready(function() { onLeftFramesLoad(0); }); My problem is that when frame-B loads before frame-A it doesn't wait for frame-A to load. I.e. the setTimeout part doesn't seem to work. frame-B only takes about 30ms so it doesn't time out. Firebug gives me this message in the javascript console: useless setTimeout call (missing quotes around argument?) Tested in FF and chrome. A: setTimeout(onLeftFramesLoad(loops + 1), 250); What this does is execute the return value of onLeftFramesLoad(loops + 1), so it executes onLeftFramesLoad before the setTimeout. this is basically the same as writing: setTimeout(undefined, 250); // onLeftFramesLoad always returns undefined undefined() doesn't work, obviously. The correct way to do this would be setTimeout(function() { onLeftFramesLoad(loops + 1); }, 250); As this is a function and thus executable. For more info on the setTimeout function, check https://developer.mozilla.org/en/window.setTimeout A: You must pass a function to setTimeout. You are currently immediately calling the function and passing the return value (which there isn't). So you'd need to wrap it into a function, and pass that function: setTimeout(function() { onLeftFramesLoad(loops + 1); }, 250);
{ "language": "en", "url": "https://stackoverflow.com/questions/7502512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }