text
stringlengths
8
267k
meta
dict
Q: Would this LINQ statement ever return null? Given the following C# code: List<string> source = new List<string>(); IEnumerable<string> values = from value in source select value; Will values ever be null or will it always return an empty sequence? A: Yes it CAN return null if you have an extension method defined in your code somewhere like the following: public static IEnumerable<string> Select(this List<string> list, Func<string, string> action) { return null; } Otherwise no; it will return an empty sequence. A: The values sequence itself will never be null. If source is empty then values will be an empty sequence containing no items. (And, of course, it's possible that one or more of the string items in the sequence might be null.) A: Linq returns empty sequences If you want to test if the sequence is empty use the .Any() method
{ "language": "en", "url": "https://stackoverflow.com/questions/7554026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: handle security popup using vbscript (without QTP/Selenium) I am automating an application login using vbscript. I am using the code - Dim objIE Set objIE = Wscript.CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate "https://portal url" after this, there is a security pop up which asks for user name and password. I dont want to disable the pop-up. Rather i want to be able to put user id and password in to it. I tried handling it through NewWindow3 method and NewWindow2 method which MSDN has provided for handling extra windows(This for development rather than for automation I guess) but does not work out. `objIE.Document.GetElementByID also does not work out becuse the pop-up does not come under 'Document' object. it comes directly under objIE, but could not find anything to handle it. A: I use following code for pass credentials to the Windows Authentication dialog. I hope it helps. Dim objIE, objWshShell Set objIE = WScript.CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate "http://url" Set objWshShell = WScript.CreateObject("WScript.Shell") With objWshShell WScript.Sleep 100 .SendKeys "myusername" 'Focused by Default - Username WScript.Sleep 100 .SendKeys "{TAB}" 'Skip To Password Field WScript.Sleep(100) .SendKeys "mypassword" 'Password WScript.Sleep 100 .SendKeys "{TAB}" 'Skip To "Remember Me" Checkbox WScript.Sleep 100 .SendKeys "{TAB}" 'Skip To Submit Button WScript.Sleep 100 .SendKeys "{ENTER}" 'GO End With Set objWshShell = Nothing Set objIE = Nothing
{ "language": "en", "url": "https://stackoverflow.com/questions/7554027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is string::c_str() no longer null terminated in C++11? In C++11 basic_string::c_str is defined to be exactly the same as basic_string::data, which is in turn defined to be exactly the same as *(begin() + n) and *(&*begin() + n) (when 0 <= n < size()). I cannot find anything that requires the string to always have a null character at its end. Does this mean that c_str() is no longer guaranteed to produce a null-terminated string? A: Strings are now required to use null-terminated buffers internally. Look at the definition of operator[] (21.4.5): Requires: pos <= size(). Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified. Looking back at c_str (21.4.7.1/1), we see that it is defined in terms of operator[]: Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()]. And both c_str and data are required to be O(1), so the implementation is effectively forced to use null-terminated buffers. Additionally, as David Rodríguez - dribeas points out in the comments, the return value requirement also means that you can use &operator[](0) as a synonym for c_str(), so the terminating null character must lie in the same buffer (since *(p + size()) must be equal to charT()); this also means that even if the terminator is initialised lazily, it's not possible to observe the buffer in the intermediate state. A: Well, in fact it is true that the new standard stipulates that .data() and .c_str() are now synonyms. However, it doesn't say that .c_str() is no longer zero-terminated :) It just means that you can now rely on .data() being zero-terminated as well. Paper N2668 defines c_str() and data() members of std::basic_string as follows: const charT* c_str() const; const charT* data() const; Returns: A pointer to the initial element of an array of length size() + 1 whose first size() elements equal the corresponding elements of the string controlled by *this and whose last element is a null character specified by charT(). Requires: The program shall not alter any of the values stored in the character array. Note that this does NOT mean that any valid std::string can be treated as a C-string because std::string can contain embedded nulls, which will prematurely end the C-string when used directly as a const char*. Addendum: I don't have access to the actual published final spec of C++11 but it appears that indeed the wording was dropped somewhere in the revision history of the spec: e.g. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf § 21.4.7 basic_string string operations [string.ops] § 21.4.7.1 basic_string accessors [string.accessors] const charT* c_str() const noexcept; const charT* data() const noexcept; * *Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()]. *Complexity: constant time. *Requires: The program shall not alter any of the values stored in the character array. A: Well spotted. This is certainly a defect in the recently adopted standard; I'm sure that there was no intent to break all of the code currently using c_str. I would suggest a defect report, or at least asking the question in comp.std.c++ (which will usually end up before the committee if it concerns a defect). A: The "history" was that a long time ago when everyone worked in single threads, or at least the threads were workers with their own data, they designed a string class for C++ which made string handling easier than it had been before, and they overloaded operator+ to concatenate strings. The issue was that users would do something like: s = s1 + s2 + s3 + s4; and each concatenation would create a temporary which had to implement a string. Therefore someone had the brainwave of "lazy evaluation" such that internally you could store some kind of "rope" with all the strings until someone wanted to read it as a C-string at which point you would change the internal representation to a contiguous buffer. This solved the problem above but caused a load of other headaches, in particular in the multi-threaded world where one expected a .c_str() operation to be read-only / doesn't change anything and therefore no need to lock anything. Premature internal-locking in the class implementation just in case someone was doing it multi-threaded (when there wasn't even a threading standard) was also not a good idea. In fact it was more costly to do anything of this than simply copy the buffer each time. Same reason "copy on write" implementation was abandoned for string implementations. Thus making .c_str() a truly immutable operation turned out to be the most sensible thing to do, however could one "rely" on it in a standard that now is thread-aware? Therefore the new standard decided to clearly state that you can, and thus the internal representation needs to hold the null terminator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: Converting Timestamp value in a prticular Date Time Format I have a problem that I have a timestamp value which is coming from JSON parsing, I am converting that timastamp in Date Time Format which is desired, all is working fine but month always return 1 in any case. means If timestamp contains aug month but it returns only 1 for any month. I don't know how to resolve this. Please suggest me the solution for the same. Thanks in advance. Code: public String create_datestring(String timestring){ try{ final Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(timestring)); timestring = String.valueOf(cal.get(Calendar.MONTH)+1) + "/" +String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(cal.get(Calendar.YEAR)); }catch(NumberFormatException e){ timestring = "9/23/2011";--->timestring always returns 1 for month. } A: private String getDate(String timeStampStr){ try{ DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date netDate = (new Date(Long.parseLong(timeStampStr))); return sdf.format(netDate); } catch(Exception ex){ return dateInStr; } } A: Try this one It may gives you satisfied output. String DATE_FORMAT="hh:mm aa dd MMMM yyyy"; @SuppressLint("SimpleDateFormat") private String getDate(long time) { return new SimpleDateFormat(DATE_FORMAT).format(time * 1000); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7554042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show a WinForms Modal Dialog from a WPF App Thread I have a WPF application. The main window of this application has a button. I am opening a WinForms modal dialog in a separate thread when this button is clicked. The trouble I am having is that the dialog does not behave like a modal i.e it is still possible to switch focus to the main window, whereas, I require to allow focus on the newly opened dialog and it should not be possible to select the main window. Note: I cannot move the modalDialog.ShowDialog(); outside of the delegate because the dialog form creates controls dynamically and this means that these controls must remain on the thread that it was created. To be more clear, if I move the modalDialog.ShowDialog(); outside I will get an exception like so: Cross-thread operation not vaild: Control 'DynamicList' accessed from a thread other than the one it was created on. Any ideas as to how I might make the form behave as a modal? Here is the code: private void button1_Click(object sender, RoutedEventArgs e) { DoSomeAsyncWork(); } private void DoSomeAsyncWork() { var modalDialog = new TestForm(); var backgroundThread = new Thread(( delegate() { // Call intensive method that creates dynamic controls modalDialog.DoSomeLongWaitingCall(); modalDialog.ShowDialog(); } )); backgroundThread.Start(); } A: You should always create controls on the UI thread. If you do that, calling ShowDialog() through Dispatcher should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Application cache: strange behaviour on iPad I'm making a website where a user can say which items he wants to cache. Based on this, a manifest file is generated. By doing this the user can still browse in the website when he is offline. This is all working fine in google chrome. But on iPad it's not working as it should. Sometimes things get cached sometimes not, not even the pages i visited. We have been testing with 2 iPads all morning, but we haven't been able to get the same result on both iPads. Even if we do exactly the same, we sometimes get different results. So what we do: * *turn WiFi on *browse to the website *make some settings so some pages/images/... are added to the manifest file *turn WiFi off *go back to safari refresh/browse to pages that should be cached. Sometimes on one iPad (this is an iPad 1) it works exactly as it should, but sometimes it doesn't work at all. On the other iPad (this is an iPad 2) it never works completely as it should. Just some random results. It also looks like the results are different when we completely shutdown safari, and then clear the cache and then do the whole process of downloading and caching stuff... Somebody can help me with this problem? It's a real pain in the ass at the moment... :( A: * *Open web server (IIS) *Select website *Open MIME type *Add or edit to text/cache-manifest *Reset iis at command prompt iisreset It works for me. A: I've encountered some problems as well with ipad caching. * *MIME type of the manifest file is not set right due to windows hosting. The standard MIME type on a windows server is "application/x-ms-manifest". This was created when the ClickOnce applications came to life. The MIME type that is necessary to work on safari is: "text/cache-manifest" *Cache size is too small on ipad (you should get a warning to enlarge it) *the Ipad needs time! I've noticed that the cache is not filled when you see all assets or when the website is "loaded". Give it twice the normal time to load before you place the website to your homescreen. *Cache of the cache :) The iPad only reloads the files when the modified date on the server is changed. So when you really want to test, clear all cache on the iPad, remove the link on the homescreen and upload all your files again. Conclusion: Time consuming! Hint: Turn on the debug console in safari on your desktop or iPad. It gives a fair idea if you did something wrong or if it is a cache problem on the iPad. A: It looks like the problem didn't have anything to do with the application cache. It was somehow a problem with the cookies/the way i was dynamically building the manifest file. A: I'd like to slightly echo Pieter-Paulus Vertongen, I had a similar experience with Windows hosting. According to the debugging console in Safari, the mime type for the manifest file was being misread and nothing was being downloaded as a result. I copied all of my files, including the .htaccess file, over to a linux server without changing any content within the files...and then the caching worked beautifully. So yes, it's possible this may be an issue of where the files are hosted. Use the debugging console and Jonathan Stark's code to find out: http://jonathanstark.com/blog/debugging-html-5-offline-application-cache?filename=2009/09/27/debugging-html-5-offline-application-cache/
{ "language": "en", "url": "https://stackoverflow.com/questions/7554054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cross compile issue with simple hello program Background : Trying to setup a cross compiler environment for arm target (TQ2440/Mini2440) On HOST running Red Hat: * *Wrote a simple hello program *gcc -o hello hello.c *compiles successfully *./hello *displays the hello world message *rm hello *arm-linux-gcc -o hello hello.c *file hello *It says 32bit compiled for ARM compatible for Linux 2.0.0 Transfer the "hello" binary file to TARGET * *chmod a+x hello *./hello *The problem: /bin/sh: ./hello: not found Can anyone point out my mistake or what am I missing here? I executed ldd on host: ldd hello and I got: /usr/local/arm/3.3.2/bin/ldd: line 1: /usr/local/arm/3.3.2/lib/ld-linux.so.2: cannot execute binary file /usr/local/arm/3.3.2/bin/ldd: line 1: /usr/local/arm/3.3.2/lib/ld-linux.so.2: cannot execute binary file ldd: /usr/local/arm/3.3.2/lib/ld-linux.so.2 exited with unknown exit code (126) A: Solved. I was transfering the file through ftp. You need to enter bin to switch to binary transfer mode. Works fine now. A: Try running ldd hello and see if it complains about any missing dynamic libraries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: remove date from DateTimePicker for Compact Framework http://msdn.microsoft.com/en-us/library/aa446530.aspx but there is no possibility to null date or to delete date from text field. how to remove date from textfield or how to connect TextField with DateTimePicker A: To display blank you can set it as DateTimePicker1.Format = DateTimePickerFormat.Custom; DateTimePicker1.CustomFormat = ""; and then reset the format in ValueChanged event to the desired format. The picker doesn't allow null values since it requires a valid DateTime object. You may choose to have a custom control also as found here
{ "language": "en", "url": "https://stackoverflow.com/questions/7554056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cursor with result from multiple content providers - Android I want to query two different content providers: MediaStore.Images.Media.EXTERNAL_CONTENT_URI and MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI First I need to query the "MediaStore.Images.Media.EXTERNAL_CONTENT_URI" so that I can get a cursor to all images that were added after a specific date. I know now how to do this. The problem is with the thumbnails. I also need to query the "MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI" for obtaining the thumbnail images so that I can show them in a listview. This is were I somehow need to combine the result from the two queries because I only want the Thumbnails for the Images that were added after a specific date. But the "MediaStore.Images.Thumbnails" doesn't have information about when the image was added. It only has an ID to the original image in "MediaStore.Images.Media". So, to sum up what I need help with: I need to get a cursor that contains the following columns: MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN How can this be done? Thanks for help! A: You can select the data from one provider, and select per row using a ViewBinder. Within MyActivity.onCreate() { ... cursorAdapter.setViewBinder(myViewBinder), ... } And somewhere you implement your ViewBinder like this... private final ViewBinder myViewBinder=new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if(columnIndex==INDEX_OF_THUMB) { int id=cursor.get("_id"); // get thumb-image data for id from somewhere // and display in view } }; Hope this helps. A: AFAIK, you will manually need to do the join and pour the results into a MatrixCursor (if you are sure that you really need a Cursor) or some other data structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DataGrid editcommand in UpdatePanel My page uses Multiview with 3 views. the third view for searching and has a datagrid in updatepanel, in datagrid has editcommand column. when user click edit on edicommand comlumn, the activeviewindex of multiview set to 1, but it throws and postback error. "Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation." I think my problem is activeviewindex method, because when user click edit on editcommandcolumn, I set activeviewindex to 1, while my datagrid is inside updatepanel and updatepanel in view 3. How can I fix it? A: I think there are some options to consider: * *If you don't care too much about security you can turn off event validation on that page. *Why are you using an update panel if when editing the grid you go to another view? Consider giving it up. *Try to put all three views within a single update panel.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Embed images in library project using Monotouch 4.2? I have a library project that contains a couple of UIViewControllers that are shared across various applications that make use of the libray. One of the view controllers needs some images. They are located in my myLibrary/Controllers/TestController/Images. Which build action do I have to specify for the images and how can I access them using UIImage.From*() methods? A: You want to set a build action of "Content" on each of the images. Then for referencing the images from code use the following (my images are in the images folder in my project): UIImage.FromFile("images/mycoolimage.png");
{ "language": "en", "url": "https://stackoverflow.com/questions/7554063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is a .aspx page loading twice when I click a button on the page? When clicking on a button in a .aspx page, the page loads twice. In the first load, the page's IsPostBack property is true and on the second load, this property will become false, which is a problem for my website. Does anyone have any ideas why it is loading twice? A: Following are the possible means of postback twice: 1- please check that you are not explicitly making postback from client-side. 2- Please check that in your page img tag src attribute is not empty. Because when you create an img element and leave its src attribute empty, it will automatically set as your root directory (e.g. “http://www.mysite.com/”). Therefore, when the Page_Load event fire for the first time, with the original post back (POST request) the Page.IsPostBack will be set with “true”. But when the server response will be parsed at the client side, another GET request will be fired to the server, requesting that image (that its src was set to the root url by default) and this is why the Page.IsPostBack property will be initialized with “false” value for the second time. A: For your button to work, it must use a PostBack to notify the server that an event has occurred. The way the ASP.Net lifecycle works, the page must be loaded before a post back event (like clicking a button) is handled, so that it knows how to handle that event. So when you click a button, the page calls the following events PreInit -> Init -> InitComplete -> PreLoad -> Load -> Your event handler If your button causes a redirect, at this point, the page will be redirected and restart the page life cycle. Without knowing exactly what your button is doing, it's hard to say if you can avoid the second page load. If you want to share your event code, I can update this answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7554065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ajax and Jquery in Symfony I'm a beginner in Symfony (version 2), I have a project achieved with plain basic PHP, and now I'm redoing my pages in dealing with Symfony framework, and arrived to my jquery ajax functions, surely, things gonna be different, I used to do like this: $("#div").click(function(){ $.post("targetFile.php",{/*parameters*/,function(data){ }); }); Q: How to make that works on Symfony? What to put instead of targetFile.php? a route most probably. and what to do on the controller and router sides? I looked out on Google and here, but didn't get any clear answers. Regards. A: You realy just have to replace the targetFile.php by a custom route of yours. So if you have this in your routing.yml: # app/config/routing.yml hello: pattern: /ajax/target defaults: { _controller: AcmeHelloBundle:Site:index } You can use this javascript: $("#div").click(function(){ $.post("/ajax/target",{/*parameters*/,function(data){ }); }); On the Symfony2 side, the method indexAction of the SiteController of the AcmeHelloBundle will be called. A: If you set inside routing.yml this: _admin_ajax: resource: "@SomethingAdminBundle/Controller/AjaxController.php" type: annotation prefix: /admin/ajax ... and inside controller, that will handle ajax call this: /** * @Route("/ajaxhandler", name="_admin_ajax_handler") */ public function handlerAction() { $isAjax = $this->get('Request')->isXMLHttpRequest(); if ($isAjax) { //... return new Response('This is ajax response'); } return new Response('This is not ajax!', 400); } ... then inside for example TWIG template you should call it like this: $("#div").click(function(){ $.post("{{ url('_admin_items_add') }}",{/*parameters*/,function(data){ }); }); ... and the real route for your action will be generated with templating engine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: issue with virtual keyboard scrolling in BB LWUIT I have done a j2me application when I port it to Blackberry using LWUIT framework I have a problem in virtual keyboard as it does not automatically scrolls because of which the user is unable to view what he is typing in the text field . Can help me solve the issue. Thanks A: This is a common problem in many platforms that feature a VKB. Currently LWUIT doesn't make solving that problem seamless which it should (feel free to file an issue on that, this should be resolved for Android/RIM, in J2ME the input is within the VKB itself). To resolve it for now you can either change your UI to place the text field in a location that is more easily reachable to the VKB. Alternatively you can try to scroll it up when detecting touch (before invoking super), this obviously requires quite a bit of coding and isn't trivial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails, Nginx and PostgreSQL - 502 Gateway Errors I'm running Ubuntu 11.04 on Linode and I'm trying to get Rails 3.1, Nginx 1.0.6, Passenger 3.0.9 and PostgreSQL 8.4 set-up and running. I've managed to deploy my application and it all appears to work perfectly but after a few successful HTTP requests the server begins to return 502 Gateway Errors. I've looked in the Nginx log and it seems to be a PostgreSQL problem, I use the same set-up on my OS X development machine (PostgreSQL 8.4, Rails 3.1 and WEBrick) and it works perfectly. Does anyone know what the problem could be? 2011/09/26 11:43:41 [error] 19694#0: *152 upstream prematurely closed connection while reading response header from upstream, client: <REDACTED>, server: localhost, request: "GET /news/new HTTP/1.0", upstream: "passenger:unix:/passenger_helper_server:", host: "<REDACTED>" [ pid=19978 thr=-609427238 file=utils.rb:176 time=2011-09-26 11:43:41.504 ]: *** Exception PGError in application (server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.** ) (process 19978, thread #<Thread:0xb759c1b4>): from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:276:in `query' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:276:in `clear_cache!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:275:in `each_value' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:275:in `clear_cache!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/postgresql_adapter.rb:303:in `disconnect!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:202:in `disconnect_without_synchronization!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:201:in `each' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:201:in `disconnect_without_synchronization!' from /var/lib/gems/1.8/gems/activesupport-3.1.0/lib/active_support/core_ext/module/synchronization.rb:35:in `disconnect!' from /usr/lib/ruby/1.8/monitor.rb:242:in `synchronize' from /var/lib/gems/1.8/gems/activesupport-3.1.0/lib/active_support/core_ext/module/synchronization.rb:34:in `disconnect!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:395:in `clear_all_connections!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:395:in `each_value' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:395:in `clear_all_connections!' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:123:in `__send__' from /var/lib/gems/1.8/gems/activerecord-3.1.0/lib/active_record/connection_adapters/abstract/connection_specification.rb:123:in `clear_all_connections!' from /opt/passenger-3.0.9/lib/phusion_passenger/utils.rb:398:in `before_handling_requests' from /opt/passenger-3.0.9/lib/phusion_passenger/rack/application_spawner.rb:204:in `start_request_handler' from /opt/passenger-3.0.9/lib/phusion_passenger/rack/application_spawner.rb:170:in `send' from /opt/passenger-3.0.9/lib/phusion_passenger/rack/application_spawner.rb:170:in `handle_spawn_application' from /opt/passenger-3.0.9/lib/phusion_passenger/utils.rb:479:in `safe_fork' from /opt/passenger-3.0.9/lib/phusion_passenger/rack/application_spawner.rb:165:in `handle_spawn_application' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:357:in `__send__' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:180:in `start' from /opt/passenger-3.0.9/lib/phusion_passenger/rack/application_spawner.rb:128:in `start' from /opt/passenger-3.0.9/lib/phusion_passenger/spawn_manager.rb:253:in `spawn_rack_application' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add' from /opt/passenger-3.0.9/lib/phusion_passenger/spawn_manager.rb:246:in `spawn_rack_application' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server_collection.rb:82:in `synchronize' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize' from /opt/passenger-3.0.9/lib/phusion_passenger/spawn_manager.rb:244:in `spawn_rack_application' from /opt/passenger-3.0.9/lib/phusion_passenger/spawn_manager.rb:137:in `spawn_application' from /opt/passenger-3.0.9/lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:357:in `__send__' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop' from /opt/passenger-3.0.9/lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously' from /opt/passenger-3.0.9/helper-scripts/passenger-spawn-server:99 ---------- Thanks! A: What write to logs PostgreSQL in this case? There must be some reasons to close connection - maybe old version of PostgreSQL?
{ "language": "en", "url": "https://stackoverflow.com/questions/7554074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update an Image uploaded to SQL Server in ASP.NET MVC 3 I have successfully uploaded an Image on my SQL Server using ASP.NET MVC 3 C#. Also I have managed to successfully displayed/downloaded that image in the Index view. However, the problem occurs when in the Edit view of the data, If the Image has been changed by selecting the file in the view, the new image stores in the DB and everything is okay. But when the user does not change the image, the value stored in the SQL Server is a null? How to avoid this. i.e, if the image is not selected/updated in the edit view, the previously stored image in the database should not be updated to a null value. A: The problem is that when the user doesn't change the image the post doesn't contain the image data. You are bluntly updating all the fields in your table and therefore set image field to NULL. You can either check if you've actually received an image in the post and do not set it to NULL in update statement, or extract the image upload to separate action. It may be even more friendly for the user to have a clearly separated UI for image upload (otherwise they could be confused: if I edit some other fields, will my image disappear? ) A: For the edit page, you should have add default post data which was previously stored. If you are not giving default value in the edit form (default value should come from previously stored data), the form will be submitted with NULL data. In that case you will get NULL during update. Hope this question will be a great help for you- How update/edit uploaded files in asp.net mvc 5 without redundancy?
{ "language": "en", "url": "https://stackoverflow.com/questions/7554076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django-nonrel on Google App Engine API creation I'm developing an app that interfaces with an iPhone app via an API. I am building it on Google App Engine, using django-nonrel. I'm looking for a solution that allows me to build read-write APIs that perform CRUD operations. I've tried django-tastypie, but it doesn't work with django-nonrel. The biggest restriction of django-nonrel is no JOINs. What is the best way to write those APIs? Should I just write the views from scratch, or is there some library that I could use? Thanks in advance! A: I got tastypie working, with two small code changes. It was pretty simple. See here: http://eatdev.tumblr.com/post/12076483835/tastypie-on-django-nonrel-on-app-engine
{ "language": "en", "url": "https://stackoverflow.com/questions/7554079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to access a graphic that has been added to the stage in Adobe Flash Pro (CS5) I added a graphic to the stage and I need to access it from actionscript, any idea how to do that? A: You need to convert your graphic to a MovieClip: * *Click on your graphics *Press F8 *Click OK *Click on the newly created MovieClip, then assign an instance name to it in the Properties dialog You can then access the MovieClip from ActionScript. Edit: To convert the graphic to a BitmapData, just use the draw function: var bmpData:BitmapData = new BitmapData(yourMc.width, yourMc.height); bmpData.draw(yourMc); var bmp:Bitmap = new Bitmap(bmpData); addChild(bmp);
{ "language": "en", "url": "https://stackoverflow.com/questions/7554085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check if Datatype from schematable and user data match I'm having a little problem with checking user inputs. I want to check if an input is of a "given" datatype. The problem is in the "given" as you might have guessed :-) I get an SQLschematable via a Datareader. The database can be exchanged, for the program should be able to work with any foreign database. Therefore I don't know anything else about it. The schematable lists all columns from the database table. It contains a column "DataType" where the .Net datatype corresponding to the databases column datatypes are listed. The user can specify a data input for each column in a datagridview. That is: the user is given the schematable and an editable extra column. Now I want to check if the given user input matches the .Net datatype. Normaly I would check this by using something like Input is String or String test = Input as String; if (test = null) .... but the problem is in creating the Datatype (i.e. the String) if I do something like this: foreach (DataRow row in MyDataTable.Rows){ System.Type t = (System.Type) row["DataType"]; if (! ( ((Object) row["Input"]) is t ) ){ MessageBox.Show("Error"); } } than t is not recognized as a datatype and the "is" command is not used properly. I also tried the more direct aproach with foreach (DataRow row in MyDataTable.Rows){ if ( ! (row[Input] is ((System.Type) row["DataType"] ))) ... and many similar lines, but it seems this "is" command only works with types that are directly referenced form System.Type, like in "is String". How could one solve this? thanks in advance, Peter A: This depends a bit whether the actual row-columns have a valid datatype (from the database) or all columns contain string types (as a generic user input type) In practice I would go for a list of Try Convert.ToX Catch 'oops not type X End try For all expected datatypes with 'string' as a catch all. Ordered a bit from Integer to float etc so the datatypes are a bit restricted with some Money and Date types added for completeness. Sure this is a dirty list but there isn't any other way that I know of. A: Something like this might be helpful try { object o = Convert.ChangeType(row["Input"], Type.GetType(row["DataType"])); } catch (Exception ex) { // Its not a type }
{ "language": "en", "url": "https://stackoverflow.com/questions/7554087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic URL change without page reload Is there a way to change URL of a website without reloading page? (Without "#" or Javascript.popState() event ). For example : if I click a button change URL from / to /new_url with no page reload. If is it possible, I'd like to use pure JavaScript, and I need cross browser support. A: I think the answer is: No You will need to use the URL hash. They were created just to do that. In JavaScript, the fragment identifier of the current HTML or XHTML page can be accessed in the "hash" property location.hash — note that Javascript can be also used with other document types. With the rise of AJAX, some websites use fragment identifiers to emulate the back button behavior of browsers for page changes that do not require a reload, or to emulate subpages. Wikipedia Still, I don't get it. What is your problem with hashes anyway? A: This is possible using pushState, although cross browser support is limited (but you can fall back to reloading the page).
{ "language": "en", "url": "https://stackoverflow.com/questions/7554088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with xml parser (foundCDATA not always working) I'm developping an app which get data from a web xml file. I'm basically following this reference, but with the function - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock because the xml from the web has the following structure: <?xml version="1.0" encoding="iso-8859-1"?> <lista> <elemento> <id><![CDATA[1468]]></id> <tipo><![CDATA[1]]></tipo> <fecha><![CDATA[01/09/2011]]></fecha> <evento><![CDATA[Rodrigo]]></evento> <descripcion><![CDATA[La selección musical de Rodrigo no deja de sorprendernos. Desde el soul y el funk a los ritmos más bailongos este Dj's hace saltar las chispas de todos aquellos que tienen el placer de escucharlo, si todavía no lo has disfrutado no lo dudes acude los jueves y disfrútalo en directo, es como los polos Colaget, enganchan.]]></descripcion> <flyer><![CDATA[mad_sep11.jpg]]></flyer> </elemento> </lista> Well, usually this is working correctly, and I can get the "id", "tipo", and "fecha" data withouth problems, but the "evento" an "descripcion" info is null. After trying to debug this problem I realise that the "parser founCDATA" function only get the blocks from the others tags (even the last one "flyer" tag), and i have no idea why is that. Here is my "parser founCDATA" function: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSLog(@"CDATABLOCK %@", CDATABlock); NSString *textWithBlanks = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]; currentStringValue = [[NSMutableString alloc] initWithCapacity:50]; stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]; [currentStringValue appendString:[textWithBlanks stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]]; NSLog(@"CURRENT STRING %@", currentStringValue); } And here is the output of that function after the parsing: 2011-09-26 12:29:55.188 project[462:707] CDATABLOCK <31343638> 2011-09-26 12:29:55.192 project[462:707] CURRENT STRING 1468 2011-09-26 12:29:55.196 project[462:707] CDATABLOCK <31> 2011-09-26 12:29:55.199 project[462:707] CURRENT STRING 1 2011-09-26 12:29:55.202 project[462:707] CDATABLOCK <30312f30 392f3230 3131> 2011-09-26 12:29:55.206 project[462:707] CURRENT STRING 01/09/2011 2011-09-26 12:29:55.218 project[462:707] CDATABLOCK <6d61645f 73657031 312e6a70 67> 2011-09-26 12:29:55.221 project[462:707] CURRENT STRING mad_sep11.jpg As you could see, it works perfectly for 3 of the tags, but not for the "evento" and "descripcion" where the the function is even not running at all, and i have no idea of the reason. Any ideas??? Sorry for such an specific question and thanks for everyone. Yandrako
{ "language": "en", "url": "https://stackoverflow.com/questions/7554089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Character Issue When Run Through The Release Process I'm using MSBuild to release my .net code and update the database. I'm having an issue with certain characters. The following scripts work fine when run in the SQL management studio. However when they are run a part of the release process the first two lines set the symbols to question marks and the second pair of update scripts add a black diamond with a question mark. update dbo.Currency set symbol = '£' where id = 1 update dbo.Currency set symbol = '€' where id = 2 update dbo.Currency set symbol = N'£' where id = 1 update dbo.Currency set symbol = N'€' where id = 2 Any help would be greatly appreciated. Luke A: Your script files need to be in unicode or at least ANSI to preserve the characters set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Internationalization with PDFBox I have been using PDFBox in my project to create pdf files containing som data from my program. It has been working great up till now as starting to add new languages starting with japanese. I have tried this: font = PDTrueTypeFont.loadTTF( doc, new File( "fontFile.ttf" ) ); It seems to be an encoding problem in pdfbox. font.setFontEncoding(new PdfDocEncoding()); I have tried diffrent fonts like Unicode font from my computer and MPlus but not realy getting anywhere. Looking around the internet it seems pdfbox has truoble handling characters in diffrent languages. My question is, should I continue this? next comes russian, persian, thai, languages like that. I fear i will get stuck with each new language even if I get japanese to work. My options as I see them is to try a diffrent library, flying-saucer, beeing the hot candidate. The other option would be to write a .doc file with open office UNO, as discussed here, and hopefully get around the whole headache of handling diffrent encodings. Soo.. have anyone been working with pdfbox and gotten internationalization to work or should i try a diffrent strategy?
{ "language": "en", "url": "https://stackoverflow.com/questions/7554093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: can get a username and password match from mysql db as the title suggests I can get a match on password and username when trying to retrieve a user from my database. When I first create a user I use this method that also hashes the password: mysql_select_db($user); $username = $_REQUEST['username']; $password = $_REQUEST['password']; function hash_password($password1, $username1) { return hash_hmac('sha512', $password1 . $username1, $site_key); } $sql=mysql_query("INSERT INTO _SCD_BACKUP_USERS (username, password) VALUES ('".$username."','".hash_password($password, $username)."')"); $r=mysql_query($sql); if(!$r)echo "Error in query: ".mysql_error(); mysql_close();` this seems to work fine! To get what I want in the database. When I retrieve the info I can't get a match using this code: $username = $_REQUEST['username']; $password = $_REQUEST['password']; function hash_password($password1, $username1) { return hash_hmac('sha512', $password1 . $username1, $site_key); } $encrypted = hash_password($username, $password); $sql = 'SELECT username FROM _SCD_BACKUP_USERS WHERE username = ? AND password = ?'; $result = $db -> query($sql, array($username, $encrypted)); if ($result -> numRows() < 1) { $arr = array('same' => true); } else { $arr = array('same' => false); } print(json_encode($arr)); mysql_close(); Any suggestions? //André A: Parameters are backwards $encrypted = hash_password($username, $password); should be $encrypted = hash_password($password, $username);
{ "language": "en", "url": "https://stackoverflow.com/questions/7554097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLCODE=-723 during insertions in DB2 I have a series of insert statements in my code. The table has few triggers to update last updated date and time. Certain insertions are succeeding while other similar inserts into the table fails with DB2 SQL Error: SQLCODE=-723, SQLSTATE=09000, SQLERRMC=CMSDB.ITNPROD_AUDIT_AFTER_INSERT;-818;51003;, DRIVER=4.8.87 What could be the problem. My worry is it works for certain records whereas fails for other. A: Look up the errors in the DB2 Message reference. The SQL0723N error (here) is telling us that an error occurred in the named trigger (in your case, the trigger is named CMSDB.ITNPROD_AUDIT_AFTER_INSERT). Furthermore, in the second part of the message, DB2 is telling us that the error that is occurring in the trigger is SQL0818N (SQLSTATE 51003) which is here. I don't really understand what 818 is saying, but it seems you may have some sort of timestamp problem with a package. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Storing Array elements in an order specified by the user I'd like users of my application to be able to rearrange a number of elements in an array into an order of their choice, while maintaining the original array structure. What's the best representation of this data? I've considered using decimals (e.g when moving element 4 between element 2 and 3, it gets a value of 2.5) however it seems like this would quickly get complex when working with many values, and may have an unnecessary overhead. Is there a simpler solution to this problem that I've overlooked? A: How are they doing the reordering? If it is some kind of drag-and-drop or button to swap two elements or to move one element up or down, the most logical way is to simply swap those two elements in the array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which python to install if I have an Intel Core i7 and 64-Bit Windows 7? I have to install Python 2.5.4 from http://www.python.org/download/releases/2.5.4/ which is required for the pcraster program. However there are three python choices For x86 processors: python-2.5.4.msi For Win64-Itanium users: python-2.5.4.ia64.msi For Win64-AMD64 users: python-2.5.4.amd64.msi I know I have Win64 but I am not sure if my i7 processor is Itanium or AMD? Can someone knowledgeable please help me? A: It really depends if your Windows is 64-bits or not. If it is, you should install Win64-AMD64, if not (32-bits) then x86. Cheers. A: Install the Win64-AMD64 version. Since AMD won the race to implement the 64 bit architecture before Intel, the architecture is still commonly known as AMD64. Irony! Intel licensed x86 architecture to AMD. Years later. AMD licensed AMD64 (based on the x86 architecture) to Intel! Read more about it from Wikipedia: x86-64. A: Both the 32- and 64-bit (AMD) versions will work on a 64-bit Win7 system. Which you want to install depends on the 3rd-party libraries you wish to use. Many libraries only support the 32-bit version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: HashMap absolute capacity I 've been doing some performance checks with one HashMap object in my code and discovered that it slows down adding objects inside at around 2000-2400 objects. In fact when it arrives to 2400 objects circa, it remains blocked and doesn't admit more entries. Is there a limit in this kind of objects that when they've been kept in memory don't admit more entries until they are emptied someway or recycled? Thank you very much. A: The only thing I can think of which might explain the problem is if your objects are very large and you are almost running out of heap. When this happens the JVM can stop for increasingly long period of time trying to clean up. In Java 6 it tries to detect this before it gets really bad and throw an OutOfMemoryError (before it has completely run out but it failed to clean up much) Java 5.0 doesn't do this. It would explain why things speed up again when you discard a few objects. The standard implementation of HashMap is limited to around 750 million entries (depending on how you use it e.g. your load average) The maximum capacity it can have is 2^30 (one billion) and with a load factor of 0.75f (~750m entries) it will try to grow the underlying array to double this size which it cannot do. (As the maximum size is Integer.MAX_VALUE) You can use LinkedHashMap as a cache, evicting the "eldset" entry based on a rule you have to provide. However, unless the HashMap is synchronized it will not block. If it going to fail it will throw an exception. The only consistent way to get a Map to block this way is to have a deadlock. Another way this can happen is if you are using the same map in two threads in an unsafe manner. In this case the behaviour is undefined, however I have seen it cause problem in the JVM (very rarely) and even "hang" the thread involved. Even if this were the case, I would expect it to have on a growing of the HashMap with a default load factor this would be 3072 (i.e. 4096*0.75) rather than the value you see. Even having a bad hashCode implementation would not explain this problem. static class BadHash { @Override public int hashCode() { return 1; } } public static void main(String... args) { Map<BadHash, Boolean> map = new HashMap<BadHash, Boolean>(); for (int i = 0; i <= 100000; i++) { if (i % 10000 == 0) System.out.println(i + ": " + new Date()); map.put(new BadHash(), true); } } prints the following in 14 seconds. 0: Mon Sep 26 12:23:39 BST 2011 10000: Mon Sep 26 12:23:39 BST 2011 20000: Mon Sep 26 12:23:39 BST 2011 30000: Mon Sep 26 12:23:40 BST 2011 40000: Mon Sep 26 12:23:41 BST 2011 50000: Mon Sep 26 12:23:42 BST 2011 60000: Mon Sep 26 12:23:44 BST 2011 70000: Mon Sep 26 12:23:46 BST 2011 80000: Mon Sep 26 12:23:48 BST 2011 90000: Mon Sep 26 12:23:51 BST 2011 100000: Mon Sep 26 12:23:53 BST 2011 A: Run this program (in a main class): Map<Long, String> map = new HashMap<Long, String>(); for (long l = 0L; l < 100000; l++) { map.put(Long.valueOf(l), String.valueOf(l)); } System.out.println(map.size()); On my machine this runs, outputs and terminates so quickly that I don't even notice it. HashMap can support many elements if the hashCode() algorithm is good. Obviously, yours is bad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to host a multi-tenant software on Django? Imagine you have a main django project which hosts software for different tenants -> The software would be hosted on -> www.tenantdomain.com The main project is hosted on -> www.ourdomain.com Supppose the software is accessed at this url -> www.ourdomain.com/tenant_id/home/ This should translate to -> www.tenantdomain.com/home/ How can one do that ? One more thing, www.tenantdomain.com and www.ourdomain.com our both hosted on one server and both of them access one database. A: The Django way for this gives you two choices. The fast way would be to host the various tenant's applications all on the same project with the Django sites framework. This is useful if the applications are sharing data. If this is not the case, you should clarify what you mean by your applications accessing one database. "One database" in Django means one project. Doing this basically means having URL proxying from tenant.com/{whatever} to yourapp.com/tenant/5/{whatever}. The more complicated way would be total separation of of your tenant's applications to separate Django project instances. This means manually (or programatically) deploying each instance. This option requires more sys-admin tasks to happen in the background, but allows you maximum flexibility. More importantly, each application is completely separated from the others, so this is best in terms of security.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript window.location in new tab I am diverting user to some url through window.location but this url opens in the same tab in browser. I want it to be open in new tab. Can I do so with window.location? Is there another way to do this action? A: Rather going for pop up,I personally liked this solution, mentioned on this Question thread JavaScript: location.href to open in new window/tab? $(document).on('click','span.external-link',function(){ var t = $(this), URL = t.attr('data-href'); $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click(); }); Working example. A: You can even use window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk'); This will open it on the same tab if the pop-up is blocked. A: window.open('https://support.wwf.org.uk', '_blank'); The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :) A: I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs. A: This works for me on Chrome 53. Haven't tested anywhere else: function navigate(href, newTab) { var a = document.createElement('a'); a.href = href; if (newTab) { a.setAttribute('target', '_blank'); } a.click(); } A: with jQuery its even easier and works on Chrome as well $('#your-button').on('click', function(){ $('<a href="https://www.some-page.com" target="blank"></a>')[0].click(); }) A: let url = 'yourUrl?Param=' + Param; window.open(url, '_blank'); A: We have to dynamically set the attribute target="_blank" and it will open it in new tab. document.getElementsByTagName("a")[0].setAttribute('target', '_blank') document.getElementsByTagName("a")[0].click() If you want to open in new window, get the href link and use window.open var link = document.getElementsByTagName("a")[0].getAttribute("href"); window.open(url, "","height=500,width=500"); Don't provide the second parameter as _blank in the above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "205" }
Q: How to avoid numeric exception : overflow in Maple 14? Maple 14 has isprime command which testing whether number is prime or not. It's allowed to write expressions as input data so we may write the next command : isprime(2^(3^43-5)-1); but I get the following error when trying to run a test : Error, numeric exception: overflow So my question is how to avoid this overflow error ? Should I change default stack size and if it's so how to do that on win 7 ultimate ? A: Since 3^43-5 is composite, then so is 2^(3^43-5)-1. See the wikipedia page on Mersenne primes. And you can get this result quickly in Maple. So if that's all you wanted, then you're done. > isprime( 3^43-5 ); false Now, suppose that you had a prime p of comparable size to 3^43. Let's say, the very next prime higher than that. nextprime( 3^43-5 ); 328256967394537077679 numtheory[mersenne]( nextprime( 3^43-5 ) ); FAIL Ok, so that's too unfortunate. Try applying isprime to 2^(10^6+3)-1. (Due to normal evaluation rules of maple procedures, isprime gets the expanded argument, so has no chance to see the special form and do the cheaper test against only 10^6+3. That's what numtheory[mersenne] is for.) You'll wait a while. Now imagine how long it would take isprime to handle a number about 10^11 times as large, which is about what you'd have if you used 2^nextprime(3^43-5)-1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: browser close event in GWT/GXT? Hi I am using EditableGrid. i have a requirement as below, when user edits any record in grid and moves away without saving, then i need to alert the user saying that he has some data to be saved. and user should be given yes/cancel options. currently i am using below code, but the problem below code is executed every time when browser is closed/refreshed/logoff. but that message should be displayed when there are changes to be saved in the grid. Window.addWindowClosingHandler(new Window.ClosingHandler() { @Override public void onWindowClosing(ClosingEvent closingEvent) { closingEvent.setMessage("Closing? Really?, you have unsaved data. you will loose it."); } }); Thanks, Salmon A: I don't think I have understood your question correctly, but from provided code snippet, I can't see any checks, which would prevent the code of executing? So, what is the problem to check, if there are any changes in your model and only then setMessage into the event?
{ "language": "en", "url": "https://stackoverflow.com/questions/7554114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: $ ssh -T git@github - permission denied (public key) I'm first time GitHub user. I installed Git for Windows, following instructions: http://help.github.com/win-set-up-git/ Came to the point of generating a public ssh-key. Opened Git Bash. Generated the key, saved it on github.com in my SSH Public Keys, now trying ssh access: $ ssh -T git@github.com Permission denied (publickey). What's wrong? The instruction sais that everything should go fine. Maybe I need to reboot or wait when github.com server gets to know my key? Please help. Thanks in advance! A: You need to set up your ssh keys and then add your public key to your github account A: ssh-keygen -t rsa copy the key generated in the file ~/.ssh/id_rsa.pub (open with notepad) paste this key in the "add ssh key" section of your github account A: I had the same problem. Although every instruction was followed; Public Key genereated and added to my Github account, i kept getting the error...Until i restarted my machine. I suggest you do the same. Hopefully this should fix it. A: Had to use exec ssh-agent bash. It helped: $ exec ssh-agent bash bash-3.1$ ssh-add f:/GIT/.ssh/id_rsa Enter passphrase for f:/GIT/.ssh/id_rsa: Identity added: f:/GIT/.ssh/id_rsa (f:/GIT/.ssh/id_rsa) bash-3.1$ ssh git@github.com Hi MichaelZelensky! You've successfully authenticated, but GitHub does not provi de shell access. Connection to github.com closed. A: For me (windows xp, reasonably fresh install) when generating the ssh keys via mingw32, the .ssh directory did not exist that I was saving the keys to. Instead of ssh-keygen creating it, they were put in the root of the user directory (C:\Documents and Settings\). This gave the Permission Denied (public key) error. Simple solution... Move the key files to the .ssh directory! (incidentally, this seemed to be created when I said yes to continue connecting after the authenticity of host.... message) A: You need to generate your ssh key first get to the ssh directory cd ~/.ssh Now generate a ssh key ssh-keygen -t rsa -C "YOUREMAILID" Key will be generated. Now install x-clip using this command sudo apt install xclip Now run the following command to copy the key to clipboard xclip -sel clip < ~/.ssh/id_rsa.pub replace id_rsa with the file location which you gave to save the key during generation now run the following command to know whether it is properly executed ssh -T git@github.com following message will occur Hi USERNAME! You've successfully authenticated, but GitHub does not provide shell access. now you are ready to perform any task in git without this issue... A: I had the same problem, I generated my ssh-keygen, after I added my public key to GitHub, and they told me same problem, but what happens you need give permission to folder .ssh, I solve that problem, I know is basic make that, but I was foregetting that, but check it, maybe is the same solution. sudo chmod 777 -R .ssh
{ "language": "en", "url": "https://stackoverflow.com/questions/7554117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: is there a tool to check unused uses in delphi? Possible Duplicate: How can I identify and get rid of unused units in the “uses clause” in Delphi 7? is there a too that can check for unneeded uses units, that expand the project beyond its needs? example we have unit a; uses b,c; procedure aP; var bI:Tb; begin bI := Tb.create; bI.free; end; end. where there is no use of c. c was introduced to the project, and never being used at the project. A: Yes, you can use the tool in CnPack or the one in Peganza. Beware that even if you do not refer to a symbol defined in a unit, the inclusion of that unit can have an impact on your project. Including a unit means that code in any initialization or finalization sections runs and that can, of course, change the meaning of your program. The canonical example of this is a replacement memory manager. The FAQ for GExperts discusses this issue and explains why they do not offer such a facility.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: opencv android sample error I'm having trouble running pure native OpenCV app on Android sample that is described here. "Tutorial 2 Advanced - 1. Add Native OpenCV" I'm able to compile it properly, but it doesn't install on virtual device. It says invalid apk file. My Android Manifest, default.properties specify virtual device 2.2 (with camera support). I'm running OpenCV 2.3.1 version (binary), Eclipse 3.5.2, NDK 6, Android Virtual Device 2.2, Ubuntu 10.4. My Log Cat seems to be empty. My console Output: Gdbserver : [arm-linux-androideabi-4.4.3] libs/armeabi-v7a/gdbserver Gdbsetup : libs/armeabi-v7a/gdb.setup Install : libnative_camera_r2.2.2.so => libs/armeabi-v7a/libnative_camera_r2.2.2.so Install : libnative_camera_r2.3.3.so => libs/armeabi-v7a/libnative_camera_r2.3.3.so Install : libnative_sample.so => libs/armeabi-v7a/libnative_sample.so Android Launch! adb is running normally. Performing org.opencv.samples.tutorial3.Sample3Native activity launch Automatic Target Mode: Several compatible targets. Please select a target device. Uploading Tutorial 2 Advanced - 1. Add Native OpenCV.apk onto device 'emulator-5554' Installing Tutorial 2 Advanced - 1. Add Native OpenCV.apk... Installation failed due to invalid APK file! Please check logcat output for more details. Launch canceled! A: What device are you using? It seems that you are trying to install .apk built for armv7 device to the armv6 or older device. Try to add/modify the line APP_ABI := armeabi in the Application.mk file and rebuild the project. A: Try cleaning the build! Go to Project --> Clean... and then running that. It'll delete your APK's and then when you run they'll be rebuilt. Worked for me! A: if you try to create an apk from eclipse (right click on the project-> android tools->export signed application, sign it with the debug certification unless u have your own signature) and try to install that one o an emulator and a device what's the result ? You said you require camera, but basically emulators do not support camera, not as far as i know, if u load the camera app you get some animation but no camera\web cam support. maybe that's the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: when should I use JFrame.add(component) and JFrame.getContentPane().add(component) in java Is there a difference between them and are there any conditions in which one should be used instead of the other? A: From what I understand from Javadocs, JFrame.add calls the latter. It is a convenience method to get around the incompatibility between AWT's frame and Swings JFrame. From javadocs for JFrame: The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write: `frame.add(child);` And the child will be added to the contentPane. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. Refer to RootPaneContainer for details on adding, removing and setting the LayoutManager of a JFrame. A: if your question is only about JFrame#add(JComponent) v.s. JFrame.getContentPane()#add(JComponent) then there isn't difference, but if you want to change f.e. BackGround then depends if you call methods from JFrame#setBackground(Color) or nested or inherits methods from awt.Frame JFrame.getContentPane()#setBackground(Color) ... A: add() will forward the work to addImpl() for which the JavaDoc of JFrame states the following: By default, children are added to the contentPane instead of the frame. Thus, both methods have the same basic behaviour, besides the fact that using getContentPane().add(...) is more explicit. Note that you could alter the default behaviour for add (using setRootPaneCheckingEnabled(false)), but I'm not sure you'd want to do that. A: Both calls are the same. In Java 5, they changed jframe.add to forward calls to the content pane. From the Java 5 release notes: Lastly, after seven years, we've made jFrame.add equivalent to jFrame.getContentPane().add(). Also, see the javadocs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Pass a function as an argument to another function, by reference (C++ rookie) I am having trouble passing a function as an argument to another function. I know this has been addressed already here, but I would appreciate a little more help because I'm having no success. I have tried to adapt this example to my needs: C++:How to pass reference-to-function into another function? I'm trying to make my code more readable. I have a huge amount of code and a lot of it is repetitive. For example: CreateDatabaseEntry( A_key, name_vector, name_vector2, dimension, "_mySuffix" ); CreateDatabaseEntry( B_key, name_vector, name_vector2, dimension, "_mySuffix" ); ... Let's say I have 26 of these calls in my current main file, one each for B_key, C_key, etc. I would like to move this kind of stuff to functions in a separate "helper" file (helper.cpp/h). For example, into CreateDatabaseEntries(). Problem Here's my problem. I would have to pass CreateDatabaseEntry into CreateDatabaseEntries. Each call to CreateDatabaseEntry takes different arguments (for example, A_key, then B_key, and so on). I have tried using the example at the link I provided above. But I get "no matching function call" errors. My guess is that I would not get errors if I were calling ONLY one CreateDatabaseEntry. Because I could hard-code "A_key" in the definition of CreateDatabaseEntries. The problem seems to be that I can't generalize the definition of CreateDatabaseEntries to take A_key, B_key, C_key, or whatever. Also, this is just a simple representation. In practice, I would want to create several "umbrella" functions like CreateDatabaseEntries that would take not only arbitrary A_key, B_key,..., but also arbitrary name_vector and other arguments. I am a rookie and it is possible that I'm totally barking up the wrong tree. If my explanation makes any sense to anyone, maybe there is a completely different way I could accomplish this? If so, it would be great to know about it. Thanks. A: Sending the functions seems strange. Parameter passing is indeed better as m0skit0 said. Why don't you just create an array of parameters, then use a loop to pass each line ? Should be simpler and you don't need to worry about pointers or memory allocation (depending on the parameters and inner mechanics from the function , of course). imagine this: int paramList [5] = { 0, 2, 4, 6, 8 }; for (i = 0; i < 5; ++ i) myFunc(paramList[i]); Well obviously in your case you'd make pairs if you have more than 1 parameter... but you get the idea, I think. If at any point you decide to change the parameter type, you could just use polymorphism on the parameters (or switch to templates), unless you want to keep it all C.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Teamprojects in subfolder not as root I try to set up a new structure to a new TFS repository and I try to map team projects to subfolders in a structure like this: Root * *Trunc * *(TeamProject)Proj1 * *SubProj1 *SubProj2 *SubProj ... *(TeamProject)Proj2 * *... *(TempProject)... *Global *Release * *Proj1 * *SubProj1 V3.5 * *Proj1(Branch) * *SubProj2(Branch) *SubProj4(Branch) *Global(Branch) *SubProje1 V3.6 * *Proj1(Branch) * *SubProj2(Branch) *SubProj4(Branch) *Global(Branch) *SubProje2 V2.1 * *Proj1(Branch) * *SubProj1(Branch) *SubProj7(Branch) *Global(Branch) ... *Proj2 ... *3rd Party Libs * *Lib1 *Lib2 This is about the structure we are used to work with in differenc scc-systems so far and we try to unite them all to the new TFS repository. In our view this structure has several advantages: * *The team-project functionality of TFS (Work Items, Builds) is sepparated for each team in the company and the lists of i.e. builds are not too long to search through to find the specific subproject. *To map the repository to local hard drives we only have to synchronize the "Trunc" path of the repository and the "3rd party libs" path and avoid to load all branches of the last 15years to each hard disk (gigabytes of trash). The Trunc main subfolder contains only the active source-code that each of us use every day. *To bufix/recompile a certail branch we only check out the specific subfolder within the releases (i.e. /Release/Proj4/SubProj2 V4.5/*) which is only some megabytes of size. After Rebuild we can remove the mapping of this subfolder from hard disk... I looked arround in the web but it seems that TFS is too strict in its structure and that team projects only can be located in the root of the repository. Is that possible? Isn't there a way to manage the team projects in one location and handle release-branches in another? And what about self developed common libraries that are used from several team projects? In our repositories (several) whe have hundereds of projects that are grouped in different topics. I'd like to make team projects for the topics and manage the actual projects by different subfolders within the team projects using separate .sln files. But I really would like to sepparate the release branches from all the active sources... Is there a way to handle this? Thank your for your answers, I was afraid to hear what you acrually answered... We have several team projects that use the same base libraries. In a release branch we usually branch these base libraries too to have a stable stand of those libs. In TFS when I use different team projects for the applikations and a sepparate team project for the base libs, can I then make a release branch of my App1 i.e. "App1 V3.2" that has the path of my app branched an in addition the path of the used libraries? Or do I have to branch the base lib team project too whenever I make a release branch of any application? How can I then ever find the right release of App1 to the right release of my i.e. base lib3 and base lib5? Why must everything from MS be so complicated? Its a cool system at the first glance but then, when you try to use it, it turns out that you have to completely change your way of working to the worse... Can I use TFS ONLY as scc like perforce, subversion or others? Is there a way to get rid of the team-project-root-level? Or is there a way of defining sub team projects? Ok, when I decide to make ONE big team broject i.e. "Developement" and have a subfolder structure similar to my first draft, what about the items/builds? Can I put i.e. builds in groupbs that represent the actual applikation (I named it subproject in my draft)? Otherwyse we would have a list of hunderets of builds in the "Developement" team project and thousands of items that belong to completely different teams in the company... A: A team project is indeed in version control only at root level. But what you want to do is creating multiple branches. That is perfectly possible with TFS. A good read is the branching and merging guide on codeplex. To restrict what you want to download on your local machine, that is to be defined in your workspace. Hope this helps you. If not, let me know what information you need more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between this.Dispatcher.BeginInvoke() and Deployment.Current.Dispatcher.BeginInvoke() methods in Silverlight I know Dispatcher.BeginInvoke() is used to execute some piece of code in the UI thread.Recently I noticed that there is another way to get the Dispatcher instance by using 'Deployment' class. I would like to know Is there any diffrence between the invokation of this.Dispatcher.BeginInvoke() and Deployment.Current.Dispatcher.BeginInvoke() functions ?, and when should I use this.Dispatcher.BeginInvoke() and Deployment.Current.Dispatcher.BeginInvoke() ? Thanks Alex A: Short answer: They are the same in Silverlight, so use the shorter one (if available in the context of your code). this.Dispatcher.BeginInvoke() ensures it is run on the thread that the control in question is running under. Deployment.Current.Dispatcher.BeginInvoke() ensures it is run on the main UI thread. The two are always the same in Silverlight (and usually the same in WPF, unless you have created extra UI threads). Use this.Dispatcher.BeginInvoke() unless your current context does not have a dispatcher, then use the global one instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to remove special characters from NSString I am doing push notification application and i am getting device token <8c09362c 82d6b735 c82fb2d9 8070db6f f73419b3 9da15e34 72aba570 6fbf5a45>, I got that device token from NSData, have succesfully converted into NSString, however i only need to remove first and last special character < > from NSString A: There are lots of way to achieve this: One you can use the way bigkm shows. Second Empty Stack had suggest a better way too. Here is one other way: NSString *dataToken = @"<8c09362c 82d6b735 c82fb2d9 8070db6f f73419b3 9da15e34 72aba570 6fbf5a45>"; NSString *str = [dataToken stringByReplacingOccurrencesOfString:@"<" withString:@""]; str = [str stringByReplacingOccurrencesOfString:@">" withString:@""]; A: If you just want to trim certain characters from a string, you can use NSCharacterSet and stringByTrimmingCharactersInSet: method of NSString. NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"<>"]; string = [string stringByTrimmingCharactersInSet:chs]; A: simple NSString *dataToken = @"<8c09362c 82d6b735 c82fb2d9 8070db6f f73419b3 9da15e34 72aba570 6fbf5a45>"; NSString *token = [dataToken substringWithRange:NSMakeRange(1, [dataToken length]-2)];
{ "language": "en", "url": "https://stackoverflow.com/questions/7554145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Provide UIImagePicker with your own UIImage. I'm trying to get a downloaded photo that was saved on the device (not photo library), and put that UIImage in a UIImagePickerController so i can crop it (using allowsEditing), as when i would choose it from my own Photo Library. Does anyone know if this is possible in any way but building my own crop-screen ? (would really rather not do it.) Thanks in advance,Shai. A: To my knowledge, there is no way you can assign an image to UIImagePickerController and make directly open the Move and Scale view. You have to create your own view controller that acts like Move and Scale and do your cropping there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with eval() in javascript could somebody help me out in understanding this javascript piece of code : eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)));} Sorry for irritating you guys with least details. Actually I got the code from - forum.fusioncharts.com/topic/8012-fusion-charts-on-android It is abput using Fusioncharts in android using Phonegap. So Fusioncharts.js contains this code nad I am not an expert in javascript and did not get it. So asked for the help. But by looking at different answer I feel full src code is not available here. thanks sneha A: A function is defined that takes 6 parameters: function(p,a,c,k,e,r) It sets the parameter e to yet another function, that takes the initial "c" parameter as a parameter: e = function(c) The contents of that function then check if "c" is less than "a". If it is, it returns an empty string. Otherwise, it runs the same function again (e) with the integer value of the parameter c divided by the parameter a. return(c<a?'':e(parseInt(c/a))); Parameters p, k and r go unused. Since the only value that can be returned is an empty string, you shouldn't expect much happening. As to what the actual use is - Beats me. A: This looks like a generated (packed code) - a strategy that is generally used to reduce the size of the original Javascript code and/or make it harder for someone to work out what is going on. There must be some logical scripting going on here, which is obfuscated as a result of the packing. If you have the script at hand, you can use this to try unpacking it, to figure out what's going on behind it. A: Written more legibly, your code is as follows: function(p,a,c,k,e,r){ e = function(c) { return c < a ? '' : e(parseInt(c/a)); }; }(); So you're defining a function that takes 6 parameters, defines a function e() (in its local scope) that takes a single parameter and recursively calls itself so long as its parameter is greater than the second parameter to the original function (a), eventually either returning '' or recursing infinitely for any value of a that is between 0 and 1 (assuming a positive value of c that is initially greater than a). The outermost function will be invoked by the eval() statement, but the inner one (e()) will not. Since e() is scoped locally to the outermost function, that makes running this code kind of pointless, at least in isolation as it is shown here. It doesn't seem like it really does anything very useful. Especially since the eval() is not providing any value for a, so when the code executes a will be undefined, meaning that e() would not do anything useful, even if it were called and even if its intended behavior could be accurately described as "useful". Also, expect people to scold you for using eval().
{ "language": "en", "url": "https://stackoverflow.com/questions/7554149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: build error in eclipse(helios) for dynamic web project I have a simple dynamic web project in eclipse(helios). In this I have one jsp which ask for uname and password and it goes to a servlet which will just print the uname. I am using Ant to build the war and deploy. I have done below settings for path: * *ANT_HOME = C:\apache-ant-1.7.0 *JAVA_HOME = C:\java\jdk1.6 *classpath = .;%JAVA_HOME%\lib;%ANT_HOME%\lib *path = %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%\bin;%Path%;%ANT_HOME%\bin tomcat is installed at c:\tomcat I have following files in WEB-INF\lib jstl-1.1.2.jar, jstl.jar, servlet-api.jar, standard-1.0.6.jar Now, when I am trying to do the ant build it gives me compilation errors, errors are as below: package javax.servlet.http does not exist, package javax.servlet.http does not exist, package javax.servlet.http does not exist and so on can anyone help me with the problem ? Is problem with the classpath or it is not able to find the jar ? Thanks Build file <property name="build.dir" value="build" /> <property name="src.dir" value="src" /> <property name="dist.dir" value="c:\tomcat\webapps" /> <property name="jardir.dir" value="C:\tomcat\common\lib" /> <target name="clean" description="Removes temporary directories"> <delete dir="${build.dir}" /> <delete dir="bin" failonerror="false" /> <delete dir="${dist.dir}/jar" failonerror="false" /> <delete dir="${dist.dir}/FirstTestApp" failonerror="false"/> </target> <target name="init" description="Creates temporary directories"> <mkdir dir="${build.dir}/classes" /> <mkdir dir="${dist.dir}" /> </target> <target name="compile" depends="init" description="compiles files"> <javac debug="true" deprecation="true" destdir="${build.dir}/classes" srcdir="${src.dir}" verbose="true" classpath="${jardir.dir}" /> </target> <target name="war" depends="compile"> <war destfile="${dist.dir}\FirstTestApp.war" basedir="${build.dir}" webxml="web\WEB-INF\web.xml"> <lib dir="web/WEB-INF/lib" includes ="**/*.jar"/> <!--<fileset dir="web/jsp" includes="*.jsp" />--> <fileset dir="web" includes="js/**,images/**,css/**,jsp/**" /> </war> </target> A: Ant doesn't know anything about web projects. It doesn't automatically include the jars in WEB-INF/lib in the classpath. You have to explicitely include all the required jars in the classpath used by the javac task to compile your classes. Note that at least servlet-api.jar should not be in WEB-INF/lib, since it's obviously in tomcat's root classpath.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select into statement where source is other database How to copy data from one DB into another DB with the same table structure and keep the key identities? I use Sql Server 2012 "Denali" and I want to copy some data from a Sql Server 2008 DB. The tables I have are exactly the same but I want the data from the old DB into the new "Denali" DB. The databases are on different servers. So I want something like USE newDB; GO SELECT * INTO newTable FROM OldDb.oldTable WITH (KEEPIDENTITY); GO Anyone have a suggestion to make this workable ? A: Configure a linked server and reference it in your query. You may need to use IDENTITY_INSERT as well. The SSIS components built into SSMS can also load data from different sources (XML, flat file or a local/remote server). A: If your both database on same server then you can do it like this way : insert into newTable select col1,col2 from OldDB.dbo.OldTable A: Had this problem today and it didn't work :( You have to use fully qualified names of the databases if both DB's are on same server. Do not forget the .dbo schema. Select * INTO [NEW DB].dbo.Lab_Tests from [OLD DB].dbo.Lab_Tests A: There are certain limitation when copying the database from one server to another (remotely). So you have to follow the steps to completely transfer the database from one server to another with same identities and along with constraints. * *To say in short, Generate Script of database i.e. Right click database > Tasks > Generate Scripts > Select database > Mark these true: Triggers, Indexes, Primary & Foreign Keys and other if any. > Choose Object Types: Mark all true except for User (you can create users on new server later on manually). > Select all the Tables, SP, and other Objects > Script to New Window or Files (as you wish) > Finish. *Generate Script to 'Create Database' and run it on server. *Run the step 1. Script on the new server, check that the new database is selected in query window. *Disable all the constraints on new server > EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" *I think using wizard is speedy so, Use Database Export Wizard from the old database server to transfer the data from old database server to new database server. *Again, Enable all the constraints on new server > EXEC sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" PS: The version does not matter as you have to transfer the database supposing to be in current version in your case SQL Server 2008, and after copying the database you can change the version of database. Database Properties > Select a page: 'Options' > Compatibility level > select the version from drop down. A: If you want to insert explicit values into a IDENTITY field then you can use SET IDENTITY_INSERT table OFF: CREATE TABLE dbo.Destination ( Id INT IDENTITY(1,1) PRIMARY KEY ,Name NVARCHAR(100) NOT NULL ); INSERT dbo.Destination VALUES ('A'), ('B'), ('C'); GO SET IDENTITY_INSERT dbo.Destination ON; INSERT dbo.Destination(Id, Name) SELECT T.Id, T.Name FROM (VALUES (10,'D'), (11,'E')) AS T(Id, Name); --or SourceDB.Schema.SourceTable SET IDENTITY_INSERT dbo.Destination OFF; GO INSERT dbo.Destination VALUES ('????????'); GO SELECT * FROM dbo.Destination DROP TABLE Destination; A: Assume you are now in the old database instance. What you can do is: Select * Into denali.dbo.newTable FROM oldTable Its like copy oldTable (Structure and content) to newTable and export it to another database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do databases sort Chinese characters? I am currently writing a web app and will need to do some ordering on a set of Chinese characters and I want to know whether Chinese characters are sorted by databases, if so how does it get sorted? For reference I will be using PostgreSQL. A: PostgreSQL sorts text using the operating system locale facility. This is exactly the same behavior that operating system tools such as sort give you. So set your locale to something useful, such as zh_HK.utf8 when you initialize the database system. If you don't like the results of that sort, you'll have to come with a custom solution. A: The easiest and most common way to sort them is just as binary data, either as Unicode code points, or even more simple as raw binary data (which does work well for ASCII data). Unfortunately, that does not make for a very meaningful sort order. It does group things together though, so things like prefix queries should work. For meaningful sort order, there is no good algorithmic solution. You'd need to work with lookup tables (see for example this thread about mapping Chinese to pinyin, by which you could then sort).
{ "language": "en", "url": "https://stackoverflow.com/questions/7554158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: mvc2 html.textbox from model, dynamically update as marker dragged before saving I am trying to populate <%: Html.TextBoxFor(model => model.FaveRunLatLng1)%> dynamically as a user drags a marker around a map. I need to use this value as the map is initialized with the FaveRunLatLng1 value. However, when the user drags the marker, this needs to be updated so that when the Save button is hit, the most current LatLng is saved. The code for the marker is in Javascript, Google maps API v3. Should I be using something like: <div class="editor-label"> <%: Html.TextBoxFor(model => model.FaveRunLatLng1, new {@class = "coords"})%> </div> This is the google maps listener for the drag event: google.maps.event.addListener(marker, 'drag', function () { var point = marker.getPosition(); var lat = point.lat(); var lng = point.lng(); coordStr = lat.toString() + ", " + lng.toString(); document.getElementById("newCoords").value = coordStr; map.setCenter(point); }); the variable newCoords acts as a test to ensure the dragged marker is updating as it is dragged. A: Yes you should do it that way. But instead of using test newCoords, just use the element ID that got created by the HtmlHelper which is FaveRunLatLng1: document.getElementById("FaveRunLatLng1").value = coordStr; This means you'd be accessing your textbox by ID rather than CSS class. I suppose you've provided class name coords for the purpose of accessing your textbox?
{ "language": "en", "url": "https://stackoverflow.com/questions/7554159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multipage SVG with R When using layout in lattice::xyplot with trellis.device you can get several pages in a PDF: trellis.device(pdf, file="myfile.pdf") data(mtcars) xyplot(hp~mpg|gear, data=mtcars, layout=c(1, 1)) dev.off() I would like to use the same approach to get a multi-page SVG. I have tried cairo::svg, and the packages gridSVG, SVGAnnotation and RSVGTipsDevice with no success: only the last page of the trellis object is saved. Is there any solution using R code? Thanks! A: I finally decided to ask directy to Paul Murrell, the creator of grid and gridSVG. He kindly provided some good advices and code which completely solved the problem with an approach similar to the advice from @mbq. I modified his code to write this function: library(gridSVG) library(XML) animateTrellis <- function(object, file='animatedSVG.svg', duration=.1, step=2, show=TRUE){ nLayers <- dim(object) stopifnot(nLayers>1) for (i in seq_len(nLayers)){ p <- object[i] label <- p$condlevels[[1]][i] ##Create intermediate SVG files g <- grid.grabExpr(print(p, prefix=label), name=label) if (i==1){ ## First frame ga <- animateGrob(g, group=TRUE, visibility="hidden", duration=duration, begin=step) } else if (i==nLayers){ ##Last Frame gg <- garnishGrob(g, visibility='hidden') ga <- animateGrob(gg, group=TRUE, visibility="visible", duration=duration, begin=step*(i-1)) } else { ##any frame gg <- garnishGrob(g, visibility='hidden') gaV <- animateGrob(gg, group=TRUE, visibility="visible", duration=duration, begin=step*(i-1)) ga <- animateGrob(gaV, group=TRUE, visibility="hidden", duration=duration, begin=step*i) } grid.newpage() grid.draw(ga) fich <- tempfile(fileext='.svg') gridToSVG(fich) ## Combine all if (i==1) { svgTop <- xmlParse(fich) nodeTop <- getNodeSet(svgTop, "//svg:g[@id='gridSVG']", c(svg="http://www.w3.org/2000/svg"))[[1]] } else { svgChildren <- xmlParse(fich) node <- getNodeSet(svgChildren, "//svg:g[@id='gridSVG']/*", c(svg="http://www.w3.org/2000/svg")) addChildren(nodeTop, node) } unlink(fich) } saveXML(svgTop, file=file) dev.off() if (show) browseURL(file) invisible(svgTop) } Then I can produce the SVG file with animation: p <- xyplot(Sepal.Length~Petal.Length|Species, data=iris, layout=c(1, 1)) animateTrellis(p, file='iris.svg')
{ "language": "en", "url": "https://stackoverflow.com/questions/7554162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery IF and 'Radio' value question I have a code that doesn't gives you to submit the form until all the fields are filled. Now i have one field that is hidden unless the user checks the "client" option on the radio below it. I need to know how can i check if the radio value is "client" and only then to force them to fill it in. Here is the code that i came across with (the client part doesn't work while the normal fields are ok.): jQuery(function(){ var defaultVal1 = jQuery("#appName").val(); var defaultVal2 = jQuery("#appID").val(); var defaultVal3 = jQuery("#aToken").val(); var cVal = jQuery("input[name='clientCheck']").value == "client"; jQuery(".button").click(function(e){ var newVal1 = jQuery("#appName").val(); var newVal2 = jQuery("#appID").val(); var newVal3 = jQuery("#aToken").val(); if(defaultVal1 === newVal1, defaultVal2 === newVal2, defaultVal3 === newVal3) { alert("Please fill out all the fields."); e.preventDefault(); } if(cVal) { alert("You have selected a Client App - Please fill out the Client Name."); e.preventDefault(); } }); Also i would like to know if i can specify the fields that they didn't filled out on the alert message. Thanks a lot. A: jQuery(function(){ var defaultVal1 = jQuery("#appName").val(); var defaultVal2 = jQuery("#appID").val(); var defaultVal3 = jQuery("#aToken").val(); var cVal = jQuery('input:radio[name=cliencheck]:checked').val(); jQuery(".button").click(function(e){ newVal1 = jQuery("#appName").val(); newVal2 = jQuery("#appID").val(); newVal3 = jQuery("#aToken").val(); cVal = jQuery('input:radio[name=cliencheck]:checked').val(); if(!(newVal1===defaultVal1 ) || !(newVal1===defaultVal2 ) || !(newVal3===defaultVal3 )) { alert("Please fill out all the fields."); e.preventDefault(); } else if(cVal == 'client') { alert("You have selected a Client App - Please fill out the Client Name."); e.preventDefault(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7554165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Java/Android scientific number to html I'm a newbie at programming and maybe there is a solution to this problem I just don't know about. I have a TextView with values. As some of the values are really small they are shown as scientific numbers. But I don't like the 2e-02 expression I'd like to convert it to an Spannable which looks like 2*10-2. Is there an easy (already implemented way) or do I have to do a loop to count the number of decimal places (all my numbers are << 1) to create a html string? It is just a question out of curiosity because I'm unable to find anything about this neither in books nor online. I don't have problems actually writing the function itself. A: Assuming all your numbers are formatted like that, here’s how I would do it: scientific.replace(/(.*)e-0*(.*)/, "$1 &times; 10<sup>&minus;$2</sup>")
{ "language": "en", "url": "https://stackoverflow.com/questions/7554171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to suspend gif animation when the Button is deactivated and how to align center vertically the gif relative to a LWUIT Button? I put animated gif into the Resource Editor. I created a Button based on this gif Image , and the Button has also a text : r = Resources.open("/resources.res"); uploadImg = r.getImage("upload"); envoieBtn = new Button("Envoyer", uploadImg); envoieBtn.setTextPosition(Label.BOTTOM); envoieBtn.setAlignment(Label.CENTER); This Button is put in the main screen , and this Button is not enabled until the phone mobile database ( RecordStore ) is populated via the third Button ( second line first column in the captured image ) on the main screen. My problem is that even if the envoieBtn Button is disabled then the gif Image on it is animated ( the red arrow is still moving upward ) ! So how to suspend the animation of the gif image ? My second question is how to center the image within the Button because on the captured image we see that the gif is not centered like the Button text. Here is the captured image : A: You can suspend animation by overriding animate in the button and avoiding the call to super, just always return false. The GIF will no longer animate (you can do that conditionally for disabled buttons). Since alignment is determined by content you can't align a button with an image to one without an image since the location of the text is determined by the image. I suggest you create a transparent image object of the exact same size and assign it to the buttons that don't have an image on them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binding list of objects to ListView with a UserControl inside, problem I have a ListView containing a UserControl with a public property MyPublicProperty of type MyType. public MyType MyPublicProperty{ get; set; } I bind to ListView a list of items of MyType listView.DataSource = (List<MyType>) items; listView.DataBind(); In aspx my ListView is defined like this <asp:ListView ID="listView" runat="server"> <ItemTemplate> <uc1:MyControl ID="myControl" runat="server" MyPublicProperty="<%#(MyType)Container.DataItem %>" /> </ItemTemplate> </asp:ListView> Now what happens is that in MyControl MyPublicProperty is not set at the event onDataBinding, and neither after that event. Do you happen to know why, and a solution for this ?? EDIT: Looking more into the problems I observed that listView.Items[0].DataItem is null after I call listView.DataBind(), but the list datasource has more then 1 items. A: If you want to access the data after it has been bound, you should use the ItemDataBound event which will get called for each item of data: listView.ItemDataBound += new EventHandler<ListViewItemEventArgs>(listView_ItemDataBound); Then: private void listView_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { MyType data = (MyType)((ListViewDataItem)e.Item).DataItem; // Use your data... } } What is it you're trying to achieve? The way you have your code now, the data will be set in the UserControl just fine without any further work from you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FBGraph API not coming in land scape mode I am developing an iPad application in which Login is done using Facebbook graph API.My App supports landscape mode. I have integrated FBGraph API , but it is not coming in landscape mode.Please suggest me how to show my facebook login view in landscape mode. Any suggestions would be highly appreciated. A: If you use latest SDK from here, Facebook login will be opened in Safari or Faceebook app or will be fetched directly from iOS 6 Settings. It will not open login window inside our app, and there will be no orientation issue. A: use the facebook sdk instead: New facebook SDK A: Am using the following method, and its working fine. Use the following code in the view, in which you are going to use fbgraph. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) { [self leftOrienation]; } else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) { [self rightOrientation]; NSLog(@"right"); } else { } // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight); } here i have initialized FbGraph as fbGraph. -(void)leftOrienation { CGAffineTransform newTransform; newTransform = CGAffineTransformMakeRotation(M_PI * 270 / 180.0f); fbGraph.webView.transform = newTransform; [fbGraph.webView setFrame:CGRectMake(0, 0, 768, 1024)]; } -(void)rightOrientation { CGAffineTransform newTransform; newTransform = CGAffineTransformMakeRotation(M_PI * 90 / 180.0f); fbGraph.webView.transform = newTransform; [fbGraph.webView setFrame:CGRectMake(0, 0, 768, 1024)]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7554176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Still cannot bind to my android service I am quite new to Android and I am porting a C# program to android. Most of it is going fine but I have a long running problem of not being able to bind to 1 of my services. I wanted to start and bind to the service to receive sendBroadcast(intent) from the service. The intent includes the data package for displaying in the UI using sendBroadcast(intent) but that returns a nullpointer, presumably because it is not connected to the activity properly. I have followed so many different tutorials including the suggestions on this site all of which seemed fairly logical and were reported working. Such as http://developer.android.com/reference/android/app/Service.html http://devblogs.net/2011/01/04/bind-service-broadcast-receiver/ http://www.androidcompetencycenter.com/2009/01/basics-of-android-part-iii-android-services/ The error appears to be that the service is not starting properly...see the stack trace below: ActivityThread.handleCreateService(ActivityThread$CreateServiceData) line: 2943 Service is null. onCreate or onStartCommand() do not get called in the service. Unfortunately I cannot use handlers for this because the constructor of the Service class is not called from the activity. As you can see I have tried many things and done some serious reading but obviously I am still missing something. I will give you what version of code I am currently trying which produced the stack trace above. This code doesn’t buil past the activities oncreate()! BUT the bool tmp from bindservice() returns true?? The activity @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(D) Log.e(TAG, "+++ ON CREATE +++"); // Various view initializations here Intent CuIntent = new Intent(this, Curve.class); CuIntent.setAction(".Core.CURVE_SERVICE"); startService(CuIntent); Boolean tmp; tmp = bindService(CuIntent, CurveServiceConncetion, Context.BIND_AUTO_CREATE); } private ServiceConnection CurveServiceConncetion = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub CurveService = ((LocalBinder<Curve>) service).getService(); } @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub CurveService = null; } }; The activity manifest xml file with the service <application android:label="@string/app_name" android:icon="@drawable/pi_icon_t"> <activity android:label="@string/app_name" android:name=".BTUI" android:finishOnCloseSystemDialogs="true"> <intent-filter> <action android:name="android.intent.action.MAIN"></action> <category android:name="android.intent.category.LAUNCHER"></category> </intent-filter> </activity> <service android:name=".Core.Curve" /> </application> The localBinder class (a separate class)is taken from another tutorial and is public class LocalBinder<S> extends Binder { private String TAG = "LocalBinder"; private WeakReference<S> mService; public LocalBinder(S service){ mService = new WeakReference<S>(service); } public S getService() { return mService.get(); } } The service looks like this public class Curve extends Service { private IBinder mBinder = new LocalBinder<Curve>(this); @Override public void onCreate() { super.onCreate(); String balls = "balls"; Toast.makeText(this, "Curve Service created...", Toast.LENGTH_LONG).show(); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return mBinder;// } @Override public void onStart(Intent intent, int startId) { String balls = "balls"; Toast.makeText(this, "Curve Service created...", Toast.LENGTH_LONG).show(); } @Override public void onDestroy() { mBinder = null; } This really can't be that hard I hope someone can see where I am going wrong. EDIT I picked a bad name for this post. The bind returns true but it crashes immediately after leaving the onCreate() of the activity. The error text is in the intro above. A: A lot of code to look trough but I have an assumption: Try to remove that: CuIntent.setAction(".Core.CURVE_SERVICE"); And the intent filter from here: <service android:name=".Core.Curve"> <intent-filter> <action android:name=".Core.CURVE_SERVICE"></action> </intent-filter> </service>
{ "language": "en", "url": "https://stackoverflow.com/questions/7554179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Re-releasing an iOS app in other countries? I have an app that I pulled from countries outside of the US due to a major bug regarding reverse geocoding. I have fixed that bug and resubmitted for review by Apple, but I'm curious if users in other countries that already purchased the app will get the update automatically when it is released by Apple? I'm assuming that I would need to make the current (buggy) version available in those countries that I want to get the update in before the new version is released at the very least? A: I would think that enabling the version for other countries will enable them to download whatever the current version of your app is at the time. So, if you enabled them (say) the day before your update was released then people in those countries would get the current (buggy) version first, and would be updated when the new version was released. It would seem better to enable the other countries just after your update was released, to avoid negative reviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WPF ListboxItem and ContextMenu I have code like this: <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical" ContextMenuService.ShowOnDisabled="True"> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Command="Delete" Click="DeleteEvent"> </MenuItem> </ContextMenu> </StackPanel.ContextMenu> <TextBlock Text="{Binding EventName}"> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> Unfortunately It doesn't work. My context menu is disabled (it is displaying but I cannot click it because it's disabled). I've read that this problem is related to selection problem but I didn't find any solution for that. Do you have any ideas? A: You are trying to set Command and the Click event. You should set one or the other. Maybe the fact the action is disabled is because you are setting a Command with a value of CanExecute = false; Instead of writing a DataTemplate, you can try to set the ItemContainerStyle for the ListBoxItem like this: <ListBox> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem Header="Delete" Click="DeleteEvent"/> </ContextMenu> </Setter.Value> </Setter> <Setter Property="Content" Value="{Binding Path=EventName}"/> </Style> </ListBox.ItemContainerStyle> </ListBox> Here I directly set the ContextMenu of the ListBoxItem instance so it will display the menu on the right control. A: ListBox already have a MenuContext. You can try it <ListBox x:Name="MyistBox"> <ListBox.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Name}"/> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ContextMenu> <ContextMenu> <MenuItem Header="Update"/> <MenuItem Header="Delete"/> </ContextMenu> </ListBox.ContextMenu> </ListBox> A: You just need to change command to header and handle DeleteEvent <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical" ContextMenuService.ShowOnDisabled="True"> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Header="Delete" Click="DeleteEvent"> </MenuItem> </ContextMenu> </StackPanel.ContextMenu> <TextBlock Text="{Binding EventName}"> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate>
{ "language": "en", "url": "https://stackoverflow.com/questions/7554184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Scala^Z3 (Z3 Version 3.2) and parsesmtlib2string(...) not working While trying to implement a test using parsesmtlib2string I hit an error: println("Hello World!"); var smtlib2String = "" smtlib2String += "(declare-fun x () bool)" + "\n" smtlib2String += "(declare-fun y () bool)" + "\n" smtlib2String += "(assert (= x y))" + "\n" smtlib2String += "(assert (= x true))" + "\n" // smtlib2String += "(check-sat)" + "\n" // smtlib2String += "(model)" + "\n" smtlib2String += "(exit)" + "\n" val cfg = new Z3Config val z3 = new Z3Context(cfg) z3.parseSMTLIB2String(smtlib2String) When uncommenting "Check-sat" I get "unknown". When uncommenting "model" I get "unsupported". Using F# with Z3 3.2 it would just give me a Term back, but in Scala the return type is Unit. I looked through the Z3-C API but didn't find a good example on how to use ist. So, what is the best way to get a model using smtlib2string? Btw: Using Scala^Z3 and building a Z3AST works just fine and I can get a model using .checkAndGetModel(). The SMT-LIB2 Code above works fine with the F# .NET parsesmtlib2string method. Using one of "getSMTLIBFormulas, getSMTLIBAssumptions, getSMTLIBDecls, getSMTLIBSorts" yields "Error: parser (data) is not available". Using "getSMTLIBError.size" yields "0". A: The parseSMTLIB2[...] methods should indeed have returned a Z3AST, thanks for reporting the problem. This is fixed in scalaz3-3.2.b.jar. Now regarding the use of the SMT-LIB 2 parser, I'm myself new to this, so Leo should perhaps confirm, but my understanding is that you should only use it to parse formulas, not to issue commands such as (check-sat). Here is an example that works for me: import z3.scala._ val smtlib2String = """ (declare-fun x () bool) (declare-fun y () bool) (assert (= x y)) (assert (= x true))""" val ctx = new Z3Context("MODEL" -> true) val assertions = ctx.parseSMTLIB2String(smtlib2String) println(assertions) // prints "(and (= x y) (= x true))" ctx.assertCnstr(assertions) println(ctx.checkAndGetModel._1) // prints "Some(true)", i.e. SAT Now if you want to programmatically recover the model for x, my understanding is that the only way to do it is to create a symbol for x before parsing and to pass it to the parser, using the overloaded definition of the parseSMTLIB2[...] method. Here is how you do it: val ctx = new Z3Context("MODEL" -> true) val xSym = ctx.mkStringSymbol("x") // should be the same symbol as in the SMT-LIB string val assertions = ctx.parseSMTLIB2String(smtlib2String, Map(xSym -> ctx.mkBoolSort), Map.empty) ctx.assertCnstr(assertions) val model = ctx.checkAndGetModel._2 val xTree = ctx.mkConst(xSym, ctx.mkBoolSort) // need a tree to evaluate using the model println(model.evalAs[Boolean](xTree)) // prints "Some(true)" Hope this helps. (Again, there may be a simpler way to do this, but I'm not aware of it. The parsing methods are directly bound to their C equivalent and the only example I could find doesn't show much.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7554186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS and menu active state How would I go about setting the menu so that the item to the right of the selected/active menu item does not have a background image. Example with no selected state, just to show how the small 3px width separator, is added ul li { background: url(nav-seperator.gif) no-repeat right top; } Next, I need to add a selected state using a repeating background image: li.active a, li a:hover { background: url(nav-active-repeat.gif) repeat-x; } Like the example below: Although the part I want to remove is the part in red: I would like it to look like this: Ideally I would like to use only CSS and without adding the class to the next item. I have created a basic version here: http://jsfiddle.net/6nEB6/3/ EDIT: I have added the print screen of the JSfiddle and the design so you can easily compare and will notice the small image to the right of the selected menu item. A: Solution If by "item to the right" you mean the separator image, all you need to do is add a margin right or left that overlaps the image and add the missing pixels to the padding or margin So if I had an initial padding of 21px my resulting CSS for on hover could be li.active a, li a:hover { margin-left: -2px; padding-left: 23px; } Of course, there are other ways to overlap that image, but that's how I do it. In your current example, this will not work, since the separator is in a different element and overlapping it would not render above it, but below it. The example below will show you how to properly implement it. Example Here's an example using only two images: background and separator. The example also demonstrates how to use CSS classes properly, without having to add a new class for each new element. If you want to add a background specifically for the first li element, ie. a selected background with a rounded corner just add this code li.active:first-child a, li:first-child a:hover{ background: url(...); } as this has a higher specificity, it will override the previous hover instructions for that element. Suggestions I would suggest you stopped using separate images for every navigator element. You might be better off with one background image and a separator. Using image-only based navigation has several downsides, the biggest ones search engine crawlers and image quality, scaling and rendering in different browsers. A: This would be possible using the + combinator (see http://www.w3.org/TR/css3-selectors/#adjacent-sibling-combinators), but only if you switched it around so that the separator image sits to the left instead of to the right: li { background: url(nav-seperator.gif) no-repeat left top; } li.active, li:hover { background: url(nav-active-repeat.gif) repeat-x; } li:first-child { background: none; } li.active + li, li:hover + li { background: none; } The problem you get instead is now you don’t have a separator at the end. Of course, you could just add a dummy <li> to the end: li:last-child { width: 10px; } li:last-child:hover { background: none; } Be advised, however, that + does not work in Internet Explorer 6, and :last-child does not even work in Internet Explorer 7 (the latter being easily solved by using .last instead). Personally, though, I would use Javascript to solve this. It’s slightly too complex to be solved conveniently using only CSS right now. If we had universal CSS3 support, it would be a different matter. Then we could easily add the rightmost separator in any number of ways (multiple backgrounds, li:last-child::after, etc.). Of course, sometimes you can rely on good CSS3 support, such as when you’re only targeting mobile WebKit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sencha touch animation problem - after slide animation is completed it is still present on the screen Here is my animation code: Ext.Anim.run(loginform, 'slide', { out: true, direction: 'left', autoClear: false }); And here is my loginform: loginform = new Ext.form.FormPanel({ url: 'login.php', standardSubmit : false, style: 'margin-top: 60px', items: [...] And in relation to the page: myapp.cards.home = new Ext.Panel({ scroll: 'vertical', id: "home-card", layout:{ type:"vbox", align:"center" }, items: [header, loginform] }); The animation code is ran on successful submit of the form. However after loginform slides to the left it doesn't completely dissapear off the screen. Please help. A: you may need to update your sencha version with the new one !
{ "language": "en", "url": "https://stackoverflow.com/questions/7554194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using SOAP to connect to a web service, please tell me what am I doing wrong? I am trying to connect to a web service using PHP/SOAP and for some reason I can't. I think there might be a problem in these lines: $client = new soapclient('http://212.199.64.197/LeadCollector/LeadCollector.asmx'); $client->debug_flag=true; $err = $soapclient->getError(); $return = $client->call('InsertCollaboratorMoreLeadDetails', $webservice); This is the error code I am getting: : Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://212.199.64.197/LeadCollector/LeadCollector.asmx' : Premature end of data in tag html line 3 in /home/uboopco1/public_html/llcproject.org/wp-content/plugins/fire-form/test.php:8 Stack trace: #0 /home/uboopco1/public_html/llcproject.org/wp-content/plugins/fire-form/test.php(8): SoapClient->SoapClient('http://212.199....') #1 {main} thrown in Do you have an idea what the problem is? Thanks! A: Sometimes you need to add ?wsdl at the end of the URL. Like this : $client = new soapclient('http://212.199.64.197/LeadCollector/LeadCollector.asmx?wsdl');
{ "language": "en", "url": "https://stackoverflow.com/questions/7554201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I optimise this mysql query? SELECT MAX( CAST( auction_price.Auctionprice AS SIGNED ) ) AS `max_auction_price` FROM auction_detail LEFT JOIN auction_price ON auction_detail.auction_id = auction_price.auction_id WHERE auction_detail.season = '2011' AND auction_detail.sale_no = '26' AND auction_detail.area LIKE '%Mumbai%' AND auction_detail.broker_code LIKE '%PAP%' AND auction_detail.category LIKE '%CTC%' AND auction_detail.tea_type LIKE '%BEST%' The above query takes about 49secs to run, so I really need to optimize it for performance. Any suggestions? A: run the command in mysql prefixed with explain, it will show you what indexes are being used in the query, it'll take a bit to learn how to read the output but it's not too hard. EXPLAIN SELECT MAX( CAST( auction_price.Auctionprice AS SIGNED ) ) AS `max_auction_price` FROM auction_detail LEFT JOIN auction_price ON auction_detail.auction_id = auction_price.auction_id WHERE auction_detail.season = '2011' AND auction_detail.sale_no = '26' AND auction_detail.area LIKE '%Mumbai%' AND auction_detail.broker_code LIKE '%PAP%' AND auction_detail.category LIKE '%CTC%' AND auction_detail.tea_type LIKE '%BEST%' A: Are the LIKE keywords words that always stand on their own (as opposed to parts of strings)? (Mumbai, PAP, CTC, BEST) If so, give full-text search a try. A properly indexed full-text search might be faster than LIKEs. A: Create indexes. for example * *on auction_detail.sale_no and on auction_price.auction_id. OR * *on auction_detail.area and on auction_price.auction_id and query like 'Mumbai%' (that is, without %) A: * *There is no point to use LEFT join in this particular case. Use INNER join; *Create a composite index (sale_no, season).
{ "language": "en", "url": "https://stackoverflow.com/questions/7554206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Listen to page save event in a Chrome extension and Firefox addon I am in the process of developing a plug-in which needs to be notified when a web page is saved. I have been browsing the chrome extension API for a long time now and cannot seem to find a solution to this. Does such an event exist and is it possible to listen to it? If not, is this possible with Firefox addons? A: I don't think that it is possible with Chrome add-ons. As to Firefox - sure, there is a <command> element with ID Browser:SavePage in the main browser window (browser.xul), defined in one of the include files. You could add a listener for the command event on this element for example: document.getElementById('Browser:SavePage').addEventListener('command', function(e) { console.log('doing command', 'id:', e.target.id, 'e:', e); }, false);
{ "language": "en", "url": "https://stackoverflow.com/questions/7554207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Glazed Lists EventTableModel class stroked in NetBeans I try to use Glazed List to create dinamically changed TableModel. All works fine, but class name EventTableModel is written strikethrough text (I use NetBeans IDE). I watch class implementation - no @Deprecated annotation here. Has anyone encountered this problem? What does this mean? I downloaded latest binary .jar from here: download page A: You probably didn't chack the right implementation, I just downloaded the source from the link you provided, I can see the following, excerpted from EventTableModel javadoc: * @deprecated Use {@link DefaultEventTableModel} instead. This class will be removed in the GL * 2.0 release. The wrapping of the source list with an EDT safe list has been * determined to be undesirable (it is better for the user to provide their own EDT * safe list). so you just have to follow the indication there and use DefaultEventTableModel instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to confine a UIWebView to a specific facebook user page I'm creating a UIWebView to load a facebook page of a specific: NSString *urlAddress = [NSString stringWithFormat:@"http://www.facebook.com/%@",self.userID]; //Create a URL object. NSURL *url = [NSURL URLWithString:urlAddress]; //URL Requst Object NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView. [webView loadRequest:requestObj]; What I need to know is how to intercept the navigation of a UIWebView such that it only loads the url's of that specific user page. For instance, it would allow navigation in the Wall page, Info page and Photos page of that user ID. I tried using the delegate method shouldStartLoadWithRequest:. It works well when the user clicks external links like Youtube or whatever, but this method is never called in case, say, the user clicks the facebook home button, which redirects to the home page of the logged in user who is not the corresponding user of the userID passed to the url. Any help? Thanks very much! A: You should be able to use an NSURLProtocol to intercept the requests and filter only those that met the criteria for browsing. http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLProtocol_Class/Reference/Reference.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7554215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why does Qt use qint64 for data lengths and offsets instead of quint64? QIODevice and the related classes use qint64 for positions and sizes which is a signed datatype. Is there a need to express negative values? Because otherwise the 8 bytes of such a type could be used to express greater sizes, couldn't they? A: An error value of -1 is returned for several functions in QIODevice. Qt often uses a C style of error handing using return values to avoid the need for a compiler or platform that supports the use of C++ exceptions. It is important to check for these error codes. From the manual: * *QIODevice::write and QIODevice::writeData Returns the number of bytes that were actually written, or -1 if an error occurred. *QIODevice::read(char*,qint64) If an error occurs, ... this function returns -1. *QIODevice::readData(char*,qint64) ... and returns the number of bytes read or -1 if an error occurred. *QIODevice::peek(char*,qint64) If an error occurs, ... this function returns -1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: HTML table, clicked row's number Is there any way to find out row number where I recently clicked, in HTML table? I need this behavior to find out whether use clicked on top and bottom of the currently selected row. I suppose the algorithm will be: * *select one row *select another row in same table *find out if the row selected at (2) has higher or lower index than row selected at (1) A: As you've tagged the question with jQuery, I'll give you a jQuery answer. You can get the index of the clicked row using jQuery's index method: $("tr").click(function() { console.log($(this).index()); }); Inside the click event handler, you would be able to use the index method again to get the index of the currently selected row and compare them or do whatever you're trying to do. A: Maybe you can take a look at this question, which is somewhat similar: table row and columns number in jQuery. Of course, I can give you a hint: var rowIndex = $("#myrow").index(); A: Adding this answer because versions of IE don't understand some index operations; and because a reader might find it convenient to use pure JS rather than jQuery in this case: Each <tr> is a children[children_index] of <tbody>. You can look in the DOM to find it and its zero-based index.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I attach a SOAP Header to my C# client? I have my web service set up to recieve a soap header of name "TestHeader" with param "Name" How do i create a soap header in my client AND send it to the service? So far I have created it in my client. public class TestHeader : SoapHeader { public String Name; } Initialised my service, Test.TestServicesClient SOAP = new Test.TestServicesClient(); Initialised my header. TestHeader header = new TestHeader(); set variable in header header.Name = "BoB"; Now what? Ive tried following MSDN, and other tutorials but not got anywhere. TestService.cs using System; using System.Web.Services; using System.Web.Services.Protocols; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Data; using System.Data.SqlClient; using System.IO; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.ServiceModel.Dispatcher; using System.ServiceModel.Channels; namespace Test { // Define a SOAP header by deriving from the SoapHeader class. public class TestHeader : SoapHeader { public String Name; } public class TestService : ITestServices { public TestHeader TestInHeader; [WebMethod] [SoapHeader("TestInHeader", Direction = SoapHeaderDirection.In)] public List<ServiceDetails> GetServiceDetails(Int32 CostCentreNo, Int32 ServiceCode, Boolean Recurring) { throw new System.Exception(TestInHeader.ToString()); } } } A: I guess I'm a little late, but here's the answer: Test.TestHeader header = new Test.TestHeader(); header.Name = "BoB"; Test.TestService SOAP = new Test.TestService(); SOAP.TestHeaderValue = header; SOAP.GetServiceDetails(0,0,False); Here's a LINK that clarifies the subject: "...Visual Studio will create a property in web service proxy called 'UserCredentialsValue' which will map the 'consumer' public property [which inherits from SoapHeader] in the web service." A: Since the information you provide is not detailed enough only some general pointers: * *How to add a custom HTTP header to every WCF call? *SoapHeader Class (System.Web.Services.Protocols) | Microsoft Docs The above links contains solutions including sample code for WCF (first link) and SOAP (second link)... EDIT - as per comments: This article (archived) gives you a complete walkthrough on implementing custom SOAP headers and setting them before calling the respective service. Bascially you need to extend the Test.TestServicesClient class with the TestHeader you defined and then you can just set its value before calling a method of the web service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Django URLs regex I need you help to validate a regular expression link in Python. Here's how should the link look like: http://www.example.com?utm_source=something&utm_medium=somethingelse And I've tried something like: r'^\?utm_source\=(?P<utm_source>[-\w]+)&utm_medium\=(?P<utm_medium>[-\w]+)/$' But this doesn't work. Can you please help me? Which (other) characters should be escaped? A: This is a classic XY problem. Tim's answer, gives you the solution you asked for. I'd suggest that you do not need regular expressions here at all if all you want to do is validate a query string. Take a look at urlparse... >>> a_url = 'http://www.example.com?utm_source=something&utm_medium=somethingelse' >>> parser = urlparse.urlparse(a_url) >>> qs = urlparse.parse_qs(parser.query) >>> 'utm_medium' in qs True >>> len(qs['utm_medium']) == 1 True >>> qs['utm_medium'][0].isalpha() True >>> 'utm_source' in qs True >>> len(qs['utm_source']) == 1 True >>> qs['utm_source'][0].isalpha() True >>> 'utm_zone' in qs False A: You don't need all those escapes: r'^\?utm_source=(?P<utm_source>[-\w]+)&utm_medium=(?P<utm_medium>[-\w]+)/$' Then, your regex only matches a complete string; it won't find a sub-match, so perhaps you need to remove the anchors? r'\?utm_source=(?P<utm_source>[-\w]+)&utm_medium=(?P<utm_medium>[-\w]+)/' Finally, the slash at the end is required in the regex but missing from your example string. So how about r'\?utm_source=(?P<utm_source>[-\w]+)&utm_medium=(?P<utm_medium>[-\w]+)/?'
{ "language": "en", "url": "https://stackoverflow.com/questions/7554223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setting up apache behind a forward proxy I have an Internet connection which is behind a forward proxy.I have to use the proxy server ip address & port No. to connect to the internet.I have installed apache web server in my machine.The apache is configured to use ProxyPass (meaning - it has to fetch documents from an external site).But the forward proxy blocks any such request.How do I set up apache to use the forward proxy server's ip address & port No to access external urls. A: If you wanted to proxy say a site from your machine through the corporate proxy, like I recently had to do for a Centos installation, you would use this in your apache config: ProxyPass /centos1/ http://ftp.riken.jp/ ProxyPassReverse /centos1/ http://ftp.riken.jp/ ProxyRemote http://ftp.riken.jp/ http://{corporate proxy here}:{corporate proxy port}
{ "language": "en", "url": "https://stackoverflow.com/questions/7554225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Haskell - Merge Sort, sorting words and numbers I've written a merge sort in Haskell, it works when using numbers but not with words, and I thought it would. I just get "Not in scope" when using words and letters. What am I doing wrong? Here's my code: merge :: Ord a => [a] -> [a] -> [a] merge [] ys = ys merge xs [] = xs merge (x:xs) (y:ys) | x <= y = x : merge xs (y:ys) | otherwise = y : merge (x:xs) ys mergeSort :: Ord a => [a] -> [a] mergeSort [] = [] mergeSort [x] = [x] mergeSort xs = merge (mergeSort top) (mergeSort bottom) where (top, bottom) = splitAt (length xs `div` 2) xs A: Are you entering your words like this? [this,is,an,example,sentence] The syntax is not correct. If you want to input a literal string, you have to encapsulte it in double quotes ("): ["this","is","an","example","sentence"] If that is not your error, feel free to ignore this answer. A: Your code works fine. However I'd suggest to split the list in one pass, without using length. Of course, the order isn't important here, just that we have two lists of about the same size. You could do it that way: splitList [] = ([],[]) splitList [x] = ([x],[]) splitList (x:y:zs) = let (xs,ys) = splitList zs in (x:xs, y:ys) ... or tail recursive ... splitList zs = go zs [] [] where go [] xs ys = (xs, ys) go [x] xs ys = (x:xs, ys) go (x:y:zs) xs ys = go zs (x:xs) (y:ys) ... or using indexes ... splitList xs = (go even, go odd) where go f = map snd $ filter (f.fst) $ indexed indexed = zip [0..] xs ... or using a fold ... import Data.List splitList zs = snd $ foldl' go (True,([],[])) zs where go (True,(xs,ys)) x = (False,(x:xs,ys)) go (False,(xs,ys)) x = (True,(xs,x:ys))
{ "language": "en", "url": "https://stackoverflow.com/questions/7554226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ShellExecuteEx returning 42 in hInstApp when expecting a 31 (No file association) When using ShellExecuteEx in Delphi 7 to open a file using a verb, I always seem to be getting 42 back as a result in hInstApp, even though I'm expecting to get a failure and a 31 result, as there is no file association. I am moving from ShellExecute, to ShellExecuteEx so that I can use WaitForInputIdle with the process handle. ShellExecute returns a 31 as expected when I try to open an XLS file when I dont have Excel installed, but ShellExecuteEx appears to succeed and return 42, even though it has actually failed and popped up the default Windows file association dialog. Am i doing something wrong? Using Delphi 7 on WinXP and Win7. Sample code below. Using Delphi 7 on a Win XP 32 bit OS, but also getting the same results on Win 7 64 bit. Just doing a showmessage on the hInstApp value returns 42 when I would expect to get 31 as I don't have Excel installed. var ExecInfo: TShellExecuteInfo; begin ZeroMemory(ExecInfo, sizeof(ExecInfo)); with ExecInfo do begin cbSize := sizeOf(ExecInfo); fMask := SEE_MASK_NOCLOSEPROCESS; lpVerb := PChar('open'); lpFile := PChar('c:\windows\temp\test.xls'); nShow := 1; end; ShellExecuteEx(@ExecInfo); if ExecInfo.hInstApp<32 then WaitForInputIdle(ExecInfo.hProcess, 10000); end; A: ShelLExecuteEx return values are not the same as ShelLExecute. Read the documentation here: http://msdn.microsoft.com/en-us/library/bb762154%28v=VS.85%29.aspx. Also check you have set the proper flags in SHELLEXECUTEINFO for the proper behaviour when an error occurs. A: The function ZeroMemory should be called with a pointer as parameter: ZeroMemory(@ExecInfo, sizeof(ExecInfo)); Then i would use the result of Shell ExecuteEx to proceed: if (ShellExecuteEx(@ExecInfo)) then As far as i know you should close the handle in the end: CloseHandle(ExecInfo.hProcess); Calling the function with the verb set to nil, will tell Windows to use the standard verb, it is a bit more generic than 'open'. I made an example to wait on an application to end, but you could easily replace WaitForSingleObject with WaitForInputIdle. A: Nehpets: "it plainly hasn't succeeded". Actually, it has: it successfully ran RunDll32.Exe. Make sure the fMask member contains SEE_MASK_FLAG_DDEWAIT. If it doesn't. you may see the "Open With" dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with custom delegates This is one of my first times trying to write my own delegates. I am using iOS5 Beta 7 and writing my delegate function. What it should do is that a table (MyTableController) loads a list of TV Channels. This is a dictionary containing the key "logotype", which is a URL to the logotype of the image. I created my class called "Channel" and my delegate called "ChannelDelegate". Now, when my table does cellForRowAtIndexPath it initiates my Channel class and calls the function getChannelImageForChannelId:externalRefference:indexPath. So far so good, now my channel class check if the file exists locally, if not it will download it (using ASIHttpRequest). Also, so far so good. Now when ASIHttpRequest returns on requestDidFinish it dies after a few results. I notice that the file did get downloaded because after a few tries it works like a charm, hence my delegate seems to work. This is my code: The CellForRowAtIndexPath: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CurrentChannelInfoCell"; CurrentChannelInfoCell *cell = (CurrentChannelInfoCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil){ NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:nil options:nil]; for(id currentObject in topLevelObjects) { if([currentObject isKindOfClass:[CurrentChannelInfoCell class]]) { cell = (CurrentChannelInfoCell *)currentObject; break; } } } NSArray *keys = [self.content allKeys]; id channelId = [keys objectAtIndex:indexPath.row]; NSDictionary *channel = [self.content objectForKey:channelId]; int cId = [(NSString*)channelId intValue]; [cell.textLabel setText:[channel objectForKey:@"name"]]; [cell.channelImage setHidden:YES]; Channel *theChannel = [[Channel alloc] init]; [theChannel setDelegate:self]; [theChannel getChannelImageForChannelId:cId externalRefference:[channel objectForKey:@"logotype"] indexPath:indexPath]; return cell; } - (void)didRecieveImageForChannel:(NSString*)imagePath indexPath:(NSIndexPath*)indexPath { NSLog(@"Did recieve the it.!"); } My Delegate, ChannelDelegate.h: #import <Foundation/Foundation.h> @class Channel; @protocol ChannelDelegate <NSObject> @optional - (void)didRecieveImageForChannel:(NSString*)imagePath indexPath:(NSIndexPath*)indexPath; @end Channel.h: #import <Foundation/Foundation.h> #import "ChannelDelegate.h" #import "Reachability.h" #import "ASIHTTPRequest.h" #import "ASINetworkQueue.h" #import "ASIFormDataRequest.h" @interface Channel : NSOperation <NSObject, ASIHTTPRequestDelegate> { ASINetworkQueue *networkQueue; // Called on the delegate (if implemented) when the request completes successfully. id <ChannelDelegate> delegate; SEL didRecieveImageForChannelSelector; } @property (strong, nonatomic) id delegate; @property (assign) SEL didRecieveImageForChannelSelector; - (void)getChannelImageForChannelId:(int)channelId externalRefference:(NSString*)url indexPath:(NSIndexPath*)indexPath; - (id)delegate; @end Channel.m: #import "Channel.h" #import <objc/runtime.h> @implementation Channel static char kAssociationKey; @synthesize didRecieveImageForChannelSelector; @synthesize delegate; - (void)getChannelImageForChannelId:(int)channelId externalRefference:(NSString*)url indexPath:(NSIndexPath*)indexPath { [self setDidRecieveImageForChannelSelector:@selector(didRecieveImageForChannel:indexPath:)]; NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *imagePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.gif", channelId]]; BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath]; if (fileExists) { NSLog(@"Downloaded image!"); [[self delegate] performSelector:[self didRecieveImageForChannelSelector] withObject:imagePath withObject:indexPath]; } else { NSLog(@"Need to fetch it.!"); NSURL *theUrl = [NSURL URLWithString:url]; ASINetworkQueue *newQueue = [[ASINetworkQueue alloc] init]; [newQueue setRequestDidFinishSelector:@selector(channelImageFetched:)]; [newQueue setRequestDidFailSelector:@selector(processFailed:)]; [newQueue setDelegate:self]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theUrl]; [request setTimeOutSeconds:60]; [request setDownloadDestinationPath:imagePath]; [newQueue addOperation:request]; objc_setAssociatedObject(request, &kAssociationKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC); [newQueue go]; } } - (id)delegate { id d = delegate; return d; } - (void)setDelegate:(id)newDelegate { delegate = newDelegate; } // Handle process two - (void)channelImageFetched:(ASIHTTPRequest *)request { NSLog(@"channelImageFetched!"); NSIndexPath *indexPath = objc_getAssociatedObject(request, &kAssociationKey); NSString *imagePath = request.downloadDestinationPath; [[self delegate] performSelector:[self didRecieveImageForChannelSelector] withObject:imagePath withObject:indexPath]; NSLog(@"File downloaded!"); } - (void) processFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; UIAlertView *errorView; errorView = [[UIAlertView alloc] initWithTitle: NSLocalizedString(@"Whoops!", @"Errors") // message: NSLocalizedString(@"An error occured while preforming the request. Please try again.", @"Network error") message: [error localizedDescription] delegate: self cancelButtonTitle: NSLocalizedString(@"Close", @"Errors") otherButtonTitles: nil]; [errorView show]; /* NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: [request error], @"Error", [request url], @"URL", [[NSDate alloc] init], @"timestamp", nil]; [FlurryAPI logEvent:@"APNS-Could not fetch data." withParameters:dictionary timed:YES]; */ } @end The error I recieve seems to differ from time to time, however these seem the errors I got: 2011-09-26 13:11:57.605 TVSports[4541:ef03] Done! 2011-09-26 13:11:57.609 TVSports[4541:ef03] Downloaded image! 2011-09-26 13:11:57.610 TVSports[4541:ef03] Did recieve the it! 2011-09-26 13:11:57.613 TVSports[4541:ef03] Need to fetch if.! 2011-09-26 13:11:57.616 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.618 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.621 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.624 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.629 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.633 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.663 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.669 TVSports[4541:ef03] Need to fetch the it.! 2011-09-26 13:11:57.846 TVSports[4541:ef03] -[UIDeviceWhiteColor channelImageFetched:]: unrecognized selector sent to instance 0x65a1e30 2011-09-26 13:11:57.847 TVSports[4541:ef03] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIDeviceWhiteColor channelImageFetched:]: unrecognized selector sent to instance 0x65a1e30' * First throw call stack: (0x15da272 0x1769ce6 0x15dbf0d 0x1540e2f 0x1540c12 0x15dc092 0x3adf8 0x15dc092 0x24c43 0x15dc092 0xef9fac 0x15aec0f 0x15118c3 0x15111a4 0x1510b04 0x1510a1b 0x1ce6f67 0x1ce702c 0x608cf2 0x2718 0x2675 0x1) terminate called throwing an exception(gdb) Or I get an EXC_BAD_ACCESS on a row in ASIHTTPRequest (which I can't reproduce the last 10 tries.) Can anybody seem what I am doing wrong? Where is my code all screwed up? A: [UIDeviceWhiteColor channelImageFetched:]: unrecognized selector sent to instance 0x65a1e30 -- What this is telling you is that the "channelImageFetched" "message" was "sent" to an object of type UIDeviceWhiteController. (Ie, UIIDeviceWhiteController ->channelImageFetched" was called.) And UIDeviceWhiteController has no method named "channelImageFetched". While this could be a problem where you're getting your pointers mixed up, more likely the object (your object) that DOES implement "channelImageFetched" was over-released and deallocated (you can confirm this by placing an NSLog in your dealloc routine.) So your problem is most likely a common storage management bug. Understanding storage management with delegates is a hair tricky. Generally, when an object is handed a delegate object it should retain it and keep it retained until all possible delegate methods have been called, at which point that first object should release the delegate object. But of course its your responsibility to keep the delegate object retained before setting it as a delegate and, if needed, after all delegate methods have been invoked. [BTW, while a bit of good humor in comments and diagnostic messages is always welcome, it's rather unprofessional to use "motherf..." in any code that you might expose to others.] A: Well, I still don't know what happened.. but it seems that I have found a work around. In mu Channel.m file I changed the content slightly. Instead of using the NetworkQueue I am now just doing a startAsynchronous on the request object. The end result: [...] if (fileExists) { NSLog(@"Downloaded image!"); [[self delegate] performSelector:[self didRecieveImageForChannelSelector] withObject:imagePath withObject:indexPath]; } else { NSLog(@"Need to fetch the image!"); NSURL *theUrl = [NSURL URLWithString:url]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theUrl]; [request setDidFinishSelector:@selector(channelImageFetched:)]; [request setDidFailSelector:@selector(processFailed:)]; [request setTimeOutSeconds:60]; [request setDownloadDestinationPath:imagePath]; objc_setAssociatedObject(request, &kAssociationKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC); [request startAsynchronous]; } [...]
{ "language": "en", "url": "https://stackoverflow.com/questions/7554230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: string "==" in java check the reference, why this code return true? Possible Duplicate: If == compares references in Java, why does it evaluate to true with these Strings? String comparision with logical operator in Java public static void main(String[] args) { String a = "ab"; final String bb = "b"; String b = "a" + bb; System.out.println(a == b); } why it print true?? but, public static void main(String[] args) { String a = "ab"; String bb = "b"; String b = "a" + bb; System.out.println(a==b); } it print false. A: You're seeing the result of two things working in combination: * *The compiler is processing the "a" + bb at compile-time rather than runtime, because the bb is final and so it knows it can do that. (There are other times it knows that, too.) *All strings generated by the compiler are interned. For more about interning, see this answer to another StackOverflow question about == in Java. So the result is that a and b point to the same string instance, and so == returns true. A: Compiler computes string at compile time as it is final and will never change. final String bb = "b"; String b = "a" + bb; "a" + bb is evaluated at compile time A: Java will intern string constants (final strings) and literals (create one instance of each string in an internal pool) and thus you might get the same instance, even if it is "created" by concatenation. And as the others already stated, compiler optimization would actually turn the concatenation into one literal ("ab"). You can never fully rely on the == semantics of String, that's why you should always use equals(..). Edit: to clarify the above sentence: With objects == always means that the references are compared and it will always return true if both references are the same. However, you can't always rely on getting the same reference of an object (like in your example where a simple final changes behavior or in frameworks like Hibernate etc.) - that's why you generally should use equals(...) instead. Of course you can use == if you need physical equality (the very same object) instead of logical equality (the same value). Another example where == would have different results, although from a locical point of view both should be true: Integer l1 = 0; Integer l2 = 0; l1 == l2; //most often true, since Integer objects up to 127 are cached Integer l1 = 1000; Integer l2 = 1000; l1 == l2; //most often false, since those are not cached anymore Note that with "most often" I mean that this could change between Java versions (if not different JVMs), although that's not very likely. A: The JLS specifies this in the section about String Literals: Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern. Thus, the test program consisting of the compilation unit (§7.3): package testPackage; class Test { public static void main(String[] args) { String hello = "Hello", lo = "lo"; System.out.print((hello == "Hello") + " "); System.out.print((Other.hello == hello) + " "); System.out.print((other.Other.hello == hello) + " "); System.out.print((hello == ("Hel"+"lo")) + " "); System.out.print((hello == ("Hel"+lo)) + " "); System.out.println(hello == ("Hel"+lo).intern()); } } class Other { static String hello = "Hello"; } and the compilation unit: package other; public class Other { static String hello = "Hello"; } produces the output: true true true true false true BTW: OMM (jdk1.6.0_21, Ubuntu), the above code doesn't compile until I make other.Other.hello public and then it outputs: true true true true true true Update: nope, my fault. My IDE automatically added final to the local variable declaration. If I remove that, I get: true true true true false true
{ "language": "en", "url": "https://stackoverflow.com/questions/7554233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to read data from bluetooth barcode scanner to android device using bluetooth ? In my project i have to read barcodes using barcode scanner through bluetooth. i.e; i have to establish a connection between android device and barcode scanner through bluetooth. Can any one tell me how to read values from barcode reader and how to setup for communication ? Thanking you, Srinivas A: One solution is to use TEC-IT's BluePiano Bluetooth Wedge. This is a replacement soft keyboard that can pair with a bluetooth scanner and dump the scan into the currently focused field. The major negative of this solution, in my opinion, is that it's necessary to replace whatever soft keyboard you're used to using with the BluePiano one. A: you can also try serialmagic gears. Can get a demo from app store I found this to be better that Blue Piano ($50 for license)
{ "language": "en", "url": "https://stackoverflow.com/questions/7554239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: floating point number Possible Duplicate: extracting mantissa and exponent from double in c# How do you separate the fraction and the exponent in a floating point number? In C++, I was able to use a "union", but unions are not allowed in C#. union {fix lc; long double cv;} ldblun; A: BitConverter.DoubleToInt64Bits() Then just shift and mask.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: static img filename link in database-text, or "replace" function in database / asp.net.( together with urlrewrite) A site I am currently working with allows users to upload images onto a page together with some text they write. like a blog or logbook. I use tinymce to let them edit the text and add images. due to the urlrewriting module I work on I have to change the img src for each of the images that is added to the page. from "/images/images_1/....jpg" to http://user1.mydomain.com/images/images_1/ "_1" is the id of the user account. and each user has their own subdomain. and each page is later viewed from a rewrited url like: user1.mydomain.com/2011/09/pagename.aspx so, the problem when using url rewrite the path for images is not working. That's why I have to change the path inside each text document. As I see it, I have 3 alternatives: 1: I replace the img src string when the text is saved, used with asp.net c#. this is easy BUT! If the user wants to change their subdomain nmame I have to update each and every one of the pages for that user inside the database. and replace the img src. 2: I use replace function in mySQL for each page visit and replace the code more dynamically. 3: I use replace function in asp.net for each page visit. alt. 2 & 3 is not good, a because it is possible to view a lot of pages at the same page. (like a blog, a whole month on one page, lot of page entries) and I think that the replace function eats hardware? So, what do you think about this? what should I choose? A: I solved this by adding another subdomain. images.mydomain.com no need for change if user changes his username :D
{ "language": "en", "url": "https://stackoverflow.com/questions/7554244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a FxCop (Code Analysis) custom ruleset by combining existing rules Please let me know , how can I develop a FxCop (Code Analysis) custom rules assembly by combining existing rules such as that custom rules assembly will include rules from "Microsoft Basic Correctness Rules" and "Microsoft Security Rules" If you can provide reference link or code sample, that would be great. Thanks Lasantha A: "Microsoft Basic Correctness Rules" and "Microsoft Security Rules" are rule sets, not rule assemblies. Each of these rule sets actually includes rules from more than one assembly. If your intent is to create a custom rules set that combines the two, this can be done quite easily: * *Create a new rule set file in Visual Studio. *Open the file in the rule set editor (assuming it's not already open). *Click the "Add or remove child rule sets..." button in the rule set editor toolbar (it's usually the second to last button). *Check the rule sets you want to include then click OK to close the "Add or Remove Rule Sets" dialog. *Save your new rule set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Developing a CMS from scratch or using Zend Framework? I want to ask if it is better to develop a CMS from scratch, making a good CMS core framework, or should I develop my CMS with the Zend Framework. I have experience in working with Zend Framework, but feel like it will not have a good success because of the large library that Zend has. A: I will try to answer what I think can objectively be answered. ZF is a general purpose component library. It doesnt offer components related to the CMS problem domain, e.g. no documents, no workflows, versioning, etc. So even if you use ZF, you will have to implement the CMS specific parts, e.g. your domain model and all the business logic (your CMS core), from scratch. ZF can solve some of the general problems of an application like authentication, caching, db access, stuff like that. So for those aspects, ZF might be useful for you. As for the size of the library: that is not an issue. You do not have to use components you do not need. Just pick those that are useful for you. As an alternative to ZF check out Apache Zeta components. It offers workflows and documents in addition to many components ZF offers as well - unfortunately, development on that has stalled lately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Server.MapPath in jQuery JavaScript when deploying on Hosting Server I am using WebMethod on my ASPXpage and I call it from jQuery on the same page like this: $.ajax({ type: "POST", url: "Mypage.aspx/GetSomeData", contentType: "application/json; charset=utf-8", data: parameters, dataType: "json", success: AjaxSucceeded, error: AjaxFailed }); This works fine in my debug environment, but when I deploy on the hosting site it does not. The problem seems to be in the URL because on the server the path would be different. So I used Server.MapPath in various ways but none of them worked. E.g url: '<%= Server.MapPath("MyPage.aspx/GetSomeData")%>', When I use the above code snippet it does not work on my machine. MyPage is in the root directory. A: You probably just need a tilde to start at the root of the app: url: '<%= Server.MapPath("~/MyPage.aspx/GetSomeData")%>' EDIT Try using: <%= ResolveUrl("~/MyPage.aspx") %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7554252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework (4.0) - Adding new records with Foreign Key We have a table "Issues" with a foreign fey to the "Contacts" table". Ideally when a new Issue is added the user should select the Contact from a drop down. However, in some cases the contact may not already exist, so the user can add minimal new contact details to get the issue into the database. (This is a Support Desk app, and speed is of the essence to the operators). The contact data is cleaned up at a later date. So in the code we detect a new contact and create a new one in the database using Entity Framework: _context.AddToContacts(_contact);. We then need to retrieve the new id for updating on the issue - so a read from the contacts table to get last record added. This works fine. Then we build the Issues record, including the new foreign key using ContactsReference.EntityKey. When we Save the Issue SaveChanges we get the Issue record okay (with the correct foreign key back to Contacts) but we get another Contacts record added to the database. Are we doing too much work here? Or should Entity Framework be able to handle both adds and manage the data link correctly between the tables? A: You can do both of these in a single transaction. var contact = new Contact(){/*initialize properties*/}; var issue = new Issue(){/*initialize properties*/}; issue.Contact = contact; _context.AddToIssues(issue); _context.SaveChanges(); EF will detect the new Contact and will add it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Cocos2d Xoom Image Pixelation Issue I am working with Android Cocos2d Ref. (http://code.google.com/p/cocos2d-android-1). All the things working fine with Standard Device, Samsung Tablet with (1024*600 Resolution). Problem starts with Motorola Xoom (1280*800). Is the Cocos2d not supporting Image Resolution higher that 1024? Let me know If there is any other alternate Cocos2d source. I have attached 3 Images.. rainbow.jpg - Original Image cocos_github_issue.png - Image that is rendering on device by using (http://code.google.com/p/cocos2d-android) cocos_lib_issue.png - Image that is rendering on device by using (http://github.com/ZhouWeikuan/cocos2d) A: Is the Cocos2d not supporting Image Resolution higher that 1024? That's likely correct. On ios it's not upto 2048 on most devices, but older devices are still limited to 1024 max size. I think this is an OpenGL limitation rather than Cocos2d. OpenGL 1.1 and lower are, I believe, limited to 1024 * 1024 textures. If you can call opengl calls directly, try the Java equivalent of this: glGetIntegerv(GL_MAX_TEXTURE_SIZE, &result);
{ "language": "en", "url": "https://stackoverflow.com/questions/7554265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inject into before serialization wcf I want to use IDispatchMessageInspector and BeforeSendReply method to change replay before return to client but it is too late cause message are serialized then. It is another wcf interface or other way to change data returned by service but not serialized yet? I want to use data return by service to generate new data and do my own serialization when accept type is text/html A: The component which converts between the return object and the outgoing message is the IDispatchMessageFormatter. Content negotiation (changing the response format depending on the incoming Accept header) is doable in the "classic" WCF, but you'll need to write your own formatter to deal with it - on incoming requests it would check what's the accept header and store it somewhere (such as the operation context), and on outgoing responses it would get the value of that header and decide how to format the outgoing response. With the WCF Web APIs, however, content negotiation is a lot easier, and there are indeed many samples that do exactly that. Check it out at http://wcf.codeplex.com - the Content Manager sample has some content negotiation capabilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing in Symfony I have two links: http://www.mypage.com/phone/show/id/1 and: http://www.mypage.com/phone/show/id/2 I would like makes links for this http://www.mypage.com/linksone and http://www.mypage.com/linkstwo Is it possible to do that with Symfony routing system? linksone: url: /linksone param: { module: phone, action: show} linkstwo: url: /linkstwo param: { module: phone, action: show} Where I can add ID? A: I believe this should do it: linksone: url: /linksone param: { module: phone, action: show, id: 1} linkstwo: url: /linkstwo param: { module: phone, action: show, id: 2} A: If you want to do this in Symfony 2+ you need to do the following routing, hopefully someone will find this useful. This is just an example and not using your names/routes. home_route: path: /home defaults: { _controller: DemoCoreBundle:StaticPageController:home } about_route: path: /about defaults: { _controller: DemoCoreBundle:StaticPageController:about } team_route: path: /team/{member_id} defaults: { _controller: DemoCoreBundle:StaticPageController:team, member_id:null } requirements: member_id: \d+
{ "language": "en", "url": "https://stackoverflow.com/questions/7554270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is ajax faster than targetting in iframe I have used both ajax as well as targetting in iframe. Can anycody tell me which is faster. A: From this ajax plugin: malsup form, you can try both ajax form, then decide which one better suits you and iframe for the same form, here is an example: $("#your-form-id").ajaxForm({ //iframe: true //this goes with iframe success: function (responseText, statusText, req, $form) { $("#target-div-id").html(responseText); } }); Ajax is used unless you have to file upload then you can use iframe, that imitates ajax form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Connect open the Facebook App i am trying to implement the facebook connect on my iphone App. after the first confirm the app stay in the facebook app and dont return to my app. i call the dialog methood from the view controller with a button but i want to post a message about the app when the user logs in how can i do it? - (void)viewDidLoad{ [super viewDidLoad]; facebook = [[Facebook alloc]initWithAppId:@"" andDelegate:self]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBEpirationDateKey"]) { facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"]; facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"]; } if (![facebook isSessionValid]) { [facebook authorize:nil ]; } } -(void)fbDidLogin{ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"]; [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"]; [defaults synchronize]; } -(IBAction)dialog:(id)sender{ [facebook dialog:@"feed" andDelegate:self]; } TNX! A: To disable this behavior modify Facebook.m line 275 and set both options to NO. - (void)authorize:(NSArray *)permissions { self.permissions = permissions; // with both options NO, authorization always happens in-app [self authorizeWithFBAppAuth:NO safariAuth:NO]; } A: In your app delegate you need to implement (make sure you keep a reference to the facebook class instance somewhere where it can be accessed by your app delegate): - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [facebook handleOpenURL:url]; } A: you should Modify the app property list file
{ "language": "en", "url": "https://stackoverflow.com/questions/7554275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stop double automatic conversion on overflow? I have a code in which i am extracting strings from environment using getenv, parsing them into numbers using strtod. If user enters, 213.123. Then 213 and 123 will be individually fed to a long type. long a1 = 213; long a2 = 123 The problem i am facing is, if user enters a very long number like: 123456789123.45678, it is automatically getting rounded off, which i don't want and instead throw an error, however ERANGE isn't working. 9 static volatile int flag; /* flag variable to indicate when the measurement should start */ 10 static time_t ef_errtrack_start_sec; /* error track start time in seconds */ 11 static long ef_errtrack_start_nsec; /* error track start time in nanoseconds */ 12 static time_t ef_errtrack_end_sec; /* error track end time in seconds */ 13 static long ef_errtrack_end_nsec; /* error track end time in nanoseconds */ 21 int main(int argc, char **argv) 22 { 23 extractTime(1); /* Extracting start time */ 24 extractTime(0); /* Extracting end time */ 25 26 printf("start: %12d, %12d\n", ef_errtrack_start_sec, ef_errtrack_start_nsec); 27 printf("end: %12d, %12d\n", ef_errtrack_end_sec, ef_errtrack_end_nsec); 28 29 return 0; 30 } 35 void extractTime(int extractStartTime) 36 { 37 char * charPtr, * numberFormatErr; 38 regex_t re; 39 40 ( extractStartTime == 1 ) ? ( charPtr = getenv("EF_ERRTRACK_START") ) : 41 ( charPtr = getenv("EF_ERRTRACK_END") ); 42 43 if ( charPtr == NULL ) 44 return; 45 46 double envVal = strtod(charPtr, &numberFormatErr); 47 48 if ( (numberFormatErr == charPtr) || (*numberFormatErr != '\0') ) { 49 ( extractStartTime == 1 ) ? printf("eFence exited: EF_ERRTRACK_START is not a number\n") : 50 printf("eFence exited: EF_ERRTRACK_END is not a number\n"); 51 exit(1); 52 } 53 if ( errno == ERANGE ) 54 { 55 ( extractStartTime == 1 ) ? EF_Print("eFence exited: EF_ERRTRACK_START is out of range\n") : 56 EF_Print("eFence exited: EF_ERRTRACK_END is out of range\n"); 57 exit(1); 58 } 59 else if ( envVal < 0 ) { 60 ( extractStartTime == 1 ) ? printf("eFence exited: EF_ERRTRACK_START a negative number\n") : 61 printf("eFence exited: EF_ERRTRACK_END is a negative number\n"); 62 exit(1); 63 } 64 65 if ( extractStartTime ) { 66 ef_errtrack_start_sec = envVal; 67 double nsec = (envVal) - (double)(ef_errtrack_start_sec); 68 ef_errtrack_start_nsec = (long)(nsec * 1000000000); 69 } 70 else { 71 ef_errtrack_end_sec = envVal; 72 double nsec = (envVal) - (double)(ef_errtrack_end_sec); 73 ef_errtrack_end_nsec = (long) (nsec * 1000000000); 74 } 75 } Here is the output: Output: /tmp # export EF_ERRTRACK_START=1234567891234.123456789123 /tmp # export EF_ERRTRACK_END=10e2 /tmp/time_related # ./a.out start: 2147483647, 2147483647 end: 1000, 0 A: "Outside the range of representable values" means bigger than DBL_MAX. Your input is in range, it just isn't exactly representable as a double. For that matter, 0.1 is also in range, and also isn't exactly representable. Should that also be an error, and if not, what's the difference? I'm not sure what to advise you to do, because I'm not sure why you consider your case an error. One option would be that once you have your double, convert it back to string with snprintf and compare to the original input, see whether they are equal at least as far as the decimal point. That ignores scientific notation, though, so there may be more work required to identify the numbers you don't like. Edit: ah, initially I didn't really assimilate this: "If user enters, 213.123. Then 213 and 123 will be individually fed to a long type." Sounds like what you are reading is not a double value, it's two integer values separated by a period character. So don't use strtod, find the . and then call strtol on each side of it. A: I think you have to parse the input, identify the possible types (and errors) and act accordingly (no double necessary) if input has no '.' and no 'e' then secs = input; nano = 0; if input has '.' and no 'e' then secs = firstpart; nano = secondpart (scaled appropriately) if input has no '.' but has 'e' then convert into the 1st or 2nd format above if input has '.' and 'e' then convert into the 1st or 2nd format above if input has '.' after 'e' then give error if input has 2 or more '.' then give error if input has 2 or more 'e' then give error ... something else I didn't think about
{ "language": "en", "url": "https://stackoverflow.com/questions/7554276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JUnit assertions : make the assertion between floats I need to compare two values : one a string and the other is float so I convert the string to float then try to call assertEquals(val1,val2) but this is not authorized , I guess that the assertEquals doesn't accept float as arguments. What is the solution for me in this case ? A: A delta-value of 0.0f also works, so for old fashioned "==" compares (use with care!), you can write Assert.assertEquals(expected, actual, 0.0f); instead of Assert.assertEquals(expected, actual); // Deprecated Assert.assertTrue(expected == actual); // Not JUnit I like the way JUnit ensures that you really thought about the "delta" which should only be 0.0f in really trivial cases. A: You have to provide a delta to the assertion for Floats: Assert.assertEquals(expected, actual, delta) While delta is the maximum difference (delta) between expected and actual for which both numbers are still considered equal. Assert.assertEquals(0.0012f, 0.0014f, 0.0002); // true Assert.assertEquals(0.0012f, 0.0014f, 0.0001); //false
{ "language": "en", "url": "https://stackoverflow.com/questions/7554281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: FormsAuthentication with enabled slidingExpiration is not returning a cookie in each request. I have a web application with FormsAuthentication and with slidingExpiration="true" in my web.config is not returning a cookie in each request, but when I see the HTTP transactions, I cannot see the webserver returning the AUTH cookie in each request. Checking the docs, it should. slidingExpiration Optional attribute. Specifies whether sliding expiration is enabled. Sliding expiration resets the active authentication time for a cookie to expire upon each request during a single session. This attribute can be one of the following values. Value Description True Specifies that sliding expiration is enabled. The authentication cookie is refreshed and the time to expiration is reset on subsequent requests during a single session. False Specifies that sliding expiration is not enabled and the cookie expires at a set interval from the time the cookie was originally issued. The default is True. Does anyone know why it is not working as expected? Cheers. A: I have read this: http://www.dotnetmonster.com/Uwe/Forum.aspx/asp-net-security/2316/problem-with-slidingExpiration In other words, if the elapsed time since ticket creation is greater then half the ticket timeout (in your scenario would be 1 minute) the the ticket won't be renewed. Otherwise a new ticket will be granted with a fresh timeout (2 mins in your case). Summarizing, if you hit your page after 1 minute, it won't extend your Forms session lifetime regardless your slidingExpiration setting. It makes sense, but I cannot find any official source. So I will test it my self when I have some spare time. Cheers. A: New Cookies will issue only when half of the time is elapsed from cookies creation and that is happening in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Simple if statement question for record not found I've got the following statement: @all_comments = Comment.find(@task.id) The problem is, if there are no comments it throws a record not found error. How can I get this to fail silently, so it just returns nothing? A: what you are trying to do can never work. The line find(@task.id) will look for comments that have the same id as the task which is normally not how you set up relations. Normally you would have a task, and a comments table, and the comments table would have a column called task_id. If that is the case, you could write your models as follows: class Task has_many :comments end class Comment belongs_to :task end and then you can simply write: @all_comments = @task.comments A: I don't use AR, but I believe just: @all_comments = Comment.find(:first, @task.id) will return nil if there is no record found, unlike #find without any modifiers. EDIT | There's a shortcut too: @all_comments = Comment.first(@task.id) A: I think that your failure is a different one you expect. Your query asks for a Comment with the ID @task.id (which is the ID of the Task). Your query should go like that: @all_comments = Comment.where(:task_id => @task.id) or even better @task.comments This should work if you have declared your relations accordingly, and allows some more options (adding comments, ...). Have a look at the "Rails Guides", and there the "Active Record Query Interface". A: The rails throws RecordNotfound exception for find calls. Use find_by calls to avoid this. If you are trying to get a list of tasks by task_id then user the find_all_by method: # returns an empty array when no tasks are found @comments = Comment.find_all_by_task_id(@task.id) Otherwise use find_by # returns nil when no task is found @comment = Comment.find_by_task_id(@task.id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7554284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web Content-Management System ... Typo3, Joomla, ... isn't there any better solution out there? I tried many Content-Management Systems ... still being frustrated. I guess this topic comes up every once in a while. Here is it again. Typo3 is too complex, Joomla is only based on articles and doesn't support complex templates, Openengine is not any longer supported, user interfaces are complex. None of them have good support for modern designs, ... Which system are you using, which would you recommend? needs: * *Simple user interface *Usable for authors without any knowledge. *Inline Editing *ContentTemplates for front pages that the author can fill them. *LayoutTemplate, Professional look and feel *Modern Design. Sliders,etc. *Simple to learn and develop *ajax support *simple extensible modules *extranet *Asset pool A: Questions like these are so ridiculous. You want an open source thing that fits you needs, that's created in such a way you can understand it, that it has feature X that you need.. Why don't you start working on your own then? Open source CMS solutions are made like a shoe that fits on every foot. If you want to customize your site, you WILL have to input some effort. Nothing is easy, and there's nothing that will let you press a few buttons in a wizard of some sort that creates the thing you want to see. I suggest either hiring someone to do what you want or simply man up and start doing it yourself. On the other hand, Wordpress is extremely modular and easy to understand code-wise even by PHP beginners. A: How about Plone http://plone.org/ It seems to have most of the features you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How do I generate unique usernames on a shared database concurrently? I need to generate account names automatically. They will be used in user software that will access my service, so they are not necessarily pretty looking. I guess any alphanumeric string long enough will do. Assume I already have an algorithm that produces good enough alphanumeric string. There're two major requirements: they must be unique and they will be generated concurrently. Specifically my service will run on multiple machines and all copies will access the same shared database. I need to generate those usernames in such way that no two nodes ever generate identical usernames. How do I do this? Do I just leave this idea and use GUIDs? Is there a prettier way that GUIDs for this scenario? A: One of: * *Use GUIDs (uniqueidentifier data type) but not as a clustered index *Use an IDENTITY column If SQL Server replication is used over multiple nodes (Edit: was thinking too much before) * *Use IDENTITY columns with ranges set per node (eg -1 to -1000000, 1 to 100000 etc) *IDENTITY column and a NodeID column to separate the IDENTITY values All are concurrency safe A: CREATE TABLE dbo.CommonName ( CommonNameID INT IDENTITY(0,1) PRIMARY KEY ,Name NVARCHAR(50) NOT NULL ,LastID INT NOT NULL DEFAULT 0 ); INSERT dbo.CommonName(Name) VALUES ('JAMES') ,('JOHN') ,('ROBERT') ,('MICHAEL') ,('WILLIAM') ,('DAVID') ,('RICHARD') ,('CHARLES') ,('JOSEPH') ,('THOMAS'); GO --Test CREATE TABLE [User](Id INT IDENTITY(1,1) PRIMARY KEY, UserName NVARCHAR(60)); GO UPDATE dbo.CommonName WITH(ROWLOCK) SET LastID = LastID + 1 OUTPUT inserted.Name+CAST(inserted.LastID AS NVARCHAR(10)) INTO [User](UserName) WHERE CommonNameID = ABS(CHECKSUM(NEWID())) % 10 GO 20 --We need 20 new users SELECT * FROM [User] u ORDER BY u.Id; --End of test GO DROP TABLE dbo.CommonName; DROP TABLE dbo.[User]; Sample output: Batch execution completed 20 times. Id UserName ----------- ------------------------------------------------------------ 1 RICHARD1 2 MICHAEL1 3 ROBERT1 4 WILLIAM1 5 ROBERT2 6 JAMES1 7 CHARLES1 8 RICHARD2 9 JOSEPH1 10 THOMAS1 11 ROBERT3 12 MICHAEL2 13 WILLIAM2 14 MICHAEL3 15 THOMAS2 16 THOMAS3 17 WILLIAM3 18 RICHARD3 19 JAMES2 20 RICHARD4 (20 row(s) affected) If you want to test this code for concurrency issues you can run UPDATE ...; GO 100000 and UPDATE ...; GO 100 in SSMS in two separated windows/queries and, at the end, you can run this query SELECT UserName, COUNT(*) Num FROM dbo.[User] ORDER BY COUNT(*) DESC to see if you can find duplicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Have problem with multi-line string in javascript This works: alert('foo\ bar' ) But this is causing syntax error: t='test'; alert('<tr><td><b>' + t + '</b></td>\ <td></td><td>') error is: SyntaxError: unterminated string literal They two should be the same thing, why the first one works, while the second fails? A: You have a trailing space after your backslash in the second example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Implementing multifile upload from stratch I want to implement a multi file upload function for my website. When I googled for tutorials on it, I found many plugins but nothing which can guide me about how to develop it from scratch. The project I am working on is for my learning purpose so I don't want to use any plug in. I can use I frames but flash is again not a choice for me. Can anyone help. I want some brief steps of it. Thankx. PS. I know how to develop its back end. I want to implement its front end. A: * *Start with a single <input type="file" name="file" /> field. *Then, to make it multiple, add a javascript function, which dynamically creates fields and add them into the page. *Than, to make upload without reloading page, put it all in the iframe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML5 Boilerplate Build script - HTML in subfolders and relative links to CSS/JS problem My project is using HTML5Boilerplate and contains subdirectories with HTML files that reference /js and css/ in the main root folders. Example: /article/xxx/index.html /article/yyy/index.html These .html files have relative path href/src to the css/js files in the root folder. <link rel="stylesheet" href="../../css/style.css" /> <script src="../../js/plugins.js"></script> <script src="../../js/script.js"></script> I'm trying to have the build script recognise these files in the subdirectories and replace the paths accordingly to the concatenated/minified JS and CSS files and I tried adding this to the file.pages property on project.properties file.pages = index.html, article/xxx/*.html, article/xxx/*.html But no dice, the CSS/JS paths get replaced as if the files are in the root folder, like so: <link rel=stylesheet href='css/7d3586f292b65c896ef495e2e8ef042901d7c2e2.css'> Which doesn't work evidently. Would be really grateful if anyone knows a workaround/modification for this or if this might just plain be a no-go? Thanks in advance to any help :D A: Maybe you could try to use file.pages = index.html, article/**/*.html the glob pattern may comply better with the build script. I just tested this on an empty project, with index.html files under article/fold1/ and article/fold2/, both with the same relative path than yours I get <link rel=stylesheet href='../../css/b218ab4.css'> also, it might save you some headache to update html files under your articles folder, the **/*.html pattern will catch up any html files within these directories. A: You need to edit the build.xml script. Around line 630 a regex is used to replace the js and css references to the concatenated versions but it does not take account of subdirectories. I changed the lines there to: <echo message="Update the HTML to reference our concatenated script file: ${scripts.js}"/> <!-- style.css replacement handled as a replacetoken above --> <replaceregexp match="&lt;!-- scripts concatenated [\d\w\s\W]*?src=&quot;([\d\w\s\W]*?)js/[\d\w\s\W]*?!-- end ((scripts)|(concatenated and minified scripts))--&gt;" replace="&lt;script defer src='\1${scripts.js}\'&gt;&lt;/script&gt;" flags="m"> <fileset dir="${dir.intermediate}" includes="${page-files}"/> </replaceregexp> <!--[! use comments like this one to avoid having them get minified --> <echo message="Updating the HTML with the new css filename: ${style.css}"/> <replaceregexp match="&lt;!-- CSS concatenated [\d\w\s\W]*?href=&quot;([\d\w\s\W]*?)css/[\d\w\s\W]*?!-- end CSS--&gt;" replace="&lt;link rel='stylesheet' href='\1${style.css}'&gt;" flags="m"> <fileset dir="${dir.intermediate}" includes="${page-files}"/> </replaceregexp> I imagine the regex can be more efficient. Simon
{ "language": "en", "url": "https://stackoverflow.com/questions/7554309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embed thirdparty JAR using BND I have an OSGi bundle that is built using ANT and the classic BND tool. My bundle uses a library (JAR) internally, which is not available as a bundle within my OSGi container (Apache Felix). So, I am trying to embed it within my bundle, for access at runtime. How can I embed such a library/JAR using ANT+BND? (Note : I cannot use MAVEN, using which this could have been a lot easier) A: You need two instructions in your bnd descriptor. First use Include-Resource to include the target JAR into your bundle: Include-Resource: foo.jar Then you need to specify that foo.jar needs to be on the bundle classpath. I assume that the bundle contents itself also needs to be part of the bundle classpath, so we need to include it as well with a dot: Bundle-ClassPath: ., foo.jar Note that @seh's answer about slurping the JAR's packages into your bundle with Private-Package is also correct (in that case the JAR would need to be visible on the build-time classpath). I would never use Export-Package for this though, because I think bundles should keep tight control over how much they export. A: There is a BND-supplied Ant task called "bndwrap". It is not well documented. When I've tried to use it, I had to read the Java code to see what it was doing. (See the bnd#doWrap() method here as well.) I recall that it's also possible to "embed" a depended-upon Jar file another way: not directly as a Jar-within-a-Jar, but by slurping all of its classes into your bundle, simply by declaring in your Private-Package BND directive that the packages provided by the other Jar should be included in yours. Alternately, you can mention those packages in an Export-Package directive to get them both included and exported.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Aria-selected attribute for row selection in a grid aria-selected attribute is used to indicate that a row in a grid is selected, When I use the jaws keys to navigate to selected row in the grid, its not being read as selected. Any clue/suggestion to make this work right? I am using the latest FF and Jaws 12 A: According to this link Jaws should support this. See the table in the "ARIA States" section. Its possible Firefox may not support the selected attribute, have you tested with the latest version of Internet Explorer? Unfortunately I have not found an exhaustive comparison of what Aria features are supported across all browsers so I would recommend testing with both Firefox and Internet explorer. You may also want to give NVDA a try as a screen reader since it may support some ARIA features Jaws won't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to release CGImageRef correctly? My Code like this: CGImageRef ImageCreateWithFile(NSString *filePath) { if(NULL == filePath) return NULL; NSData *data = [[NSData alloc] initWithContentsOfFile:filePath]; if(NULL == data) return NULL; CGImageSourceRef isrc = CGImageSourceCreateWithData((CFDataRef)data, NULL); // [data release]; CGImageRef image = CGImageSourceCreateImageAtIndex(isrc, 0, NULL); CFRelease(isrc); isrc = nil; [data release]; data = nil; return image; } - (IBAction)addClick:(id)sender { CGImageRef image = ImageCreateWithFile(@"/Users/user/t.jpg"); if(NULL != image) _imageList.push_back(image); } - (IBAction)removeClick:(id)sender { if(_imageList.size() > 0) { CGImageRef image = _imageList[0]; CGImageRelease(image); image = nil; _imageList.erase(_imageList.begin()); } } The imageList declared like: std::vector<CGImageRef> _imageList; This program is wrote for testing the method of releasing CGImageRef. When I add some images, I see the memory usage of the program rises regularly in the Activity Monitor,but after I remove one or more images by the remove method, the memory never descend. I don't know why the release method not work? Any help? Thanks!!! A: If you look at the documentation of CGImageSourceCreateImageAtIndex, you'll see that the last argument is a dictionary of options. One of these options is called kCGImageSourceShouldCache. You could try to pass a dictionary, setting this option to false. The snippet below is from the Image I/O Guide here CFStringRef myKeys[1]; CFTypeRef myValues[1]; CFDictionaryRef myOptions; myKeys[0] = kCGImageSourceShouldCache; myValues[0] = (CFTypeRef)kCFBooleanFalse; myOptions = CFDictionaryCreate(NULL, (const void **) myKeys, (const void **) myValues, 1, &kCFTypeDictionaryKeyCallBacks, & kCFTypeDictionaryValueCallBacks); CGImageRef image = CGImageSourceCreateImageAtIndex(isrc, 0, myOptions);
{ "language": "en", "url": "https://stackoverflow.com/questions/7554319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Django-Admin.py not displaying models 'Each object given an Admin declaration shows up on the main index page' This line refers to the fact that a simple class Admin: pass declaration in a django model automatically generates the change and add interface to the Django admin homepage...is this functionality still available? My Urls .py is correct, i have added my application to the installed apps, and my database settings are correct, yet i dont see the objects on my admin page. Its frustrating because no error is thrown. I have run syncdb many times..even tested sync db by adding new fields and new objects to my DB but still no change. Help. Please. Here are my settings .py, models.py URLs.py class Publisher(models.Model): name=models.CharField(max_length=30) address=models.CharField(max_length=50) city=models.CharField(max_length=60) state_province=models.CharField(max_length=30) country=models.CharField(max_length=50) websites=models.URLField() def __str__(self): return self.name class Admin : pass class Author(models.Model): salutation=models.CharField(max_length=10) first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) email=models.EmailField() headshot=models.ImageField(upload_to='/tmp') def __str__(self): return '%s %s' % (self.first_name,self.last_name) class Admin : pass class Book (models.Model): title=models.CharField(max_length=100) authors=models.ManyToManyField(Author) publisher=models.ForeignKey(Publisher) publication_date=models.DateField() no_of_books_produced=models.CharField(max_length=100) def __str__(self): return self.title class Admin: pass URLS.py from django.conf.urls.defaults import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'ModelsDemo.views.home', name='home'), # url(r'^ModelsDemo/', include('ModelsDemo.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ) settings.py # Django settings for ModelsDemo project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ModelsDemo', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD': 'root', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'qst#zi4rauz09!(g*77yy8lrbwij*6y4#n$+i5t#&vai8wlh6x' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'ModelsDemo.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', 'ModelsDemo.Books', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } A: Unless things have radically changed lately you still need an admin.py where you define the admin class, and then register it. Have you tried that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7554322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to make `fill-paragraph` stop at the end of a sentence? It is sometimes desirable to start each sentence in a paragraph on a separate line. For instance, this makes it easier to diff large text documents, because a change in one sentence will not affect the entire paragraph. Some markup systems (e.g. *roff) also require each sentence to start on a new line. Is there a way, e.g. by judicious redefinition of paragraph-separate and paragraph-start, to make fill-paragraph stop between sentences? (note: I use Emacs 23.3.1) Update: sample mdoc (*roff) markup: The .Nm utility makes a series of passes with increasing block sizes. In each pass, it either reads or writes (or both) a number of non-consecutive blocks at increasing offsets relative to the ideal alignment, which is assumed to be multiples of the block size. The results are presented in terms of time elapsed, transactions per second and kB per second. This is a single paragraph with three sentences, each of which starts on a separate line even though there is room for the first word(s) on the previous line. Currently, fill-paragraph will transform this into The .Nm utility makes a series of passes with increasing block sizes. In each pass, it either reads or writes (or both) a number of non-consecutive blocks at increasing offsets relative to the ideal alignment, which is assumed to be multiples of the block size. The results are presented in terms of time elapsed, transactions per second and kB per second. which is what I want to avoid. Update: in re sentences and paragraphs I see that my question is a bit unclear, because I used the term "paragraph" to refer both to what Emacs calls a paragraph and to what ends up as a continuous block of text in the output of whatever processor I use (groff, latex etc.). To clarify, * *I need to keep the sentences together without any blank lines between them; groff doesn't like blank lines, while latex sees them as paragraph separators. *I need fill-paragraph to operate on individual sentences, i.e. I want to redefine a paragraph as something that starts after either a blank line or the end of the previous paragraph, and ends with a period followed by either a newline character or at least two whitespace characters. *I would love to have fill-paragraph break a block of text apart into individual sentences, but I don't think it can be done easily. For instance, if I type the following: The .Nm utility makes a series of passes with increasing block sizes. In each pass, it either reads or writes (or both) a number of non-consecutive blocks at increasing offsets relative to the ideal alignment, which is assumed to be multiples of the block size. The results are presented in terms of time elapsed, transactions per second and kB per second. then move the point to the line that starts with "In each pass" and press M-q, I should get the following: The .Nm utility makes a series of passes with increasing block sizes. In each pass, it either reads or writes (or both) a number of non-consecutive blocks at increasing offsets relative to the ideal alignment, which is assumed to be multiples of the block size. The results are presented in terms of time elapsed, transactions per second and kB per second. Note that the last sentence is untouched. A: How about telling paragraph-start to look for any line that starts with a capital letter: "\f\\|[ ]*$\\|^[A-Z]" Note that the new part is \\^[A-Z] That should work for most cases, you'd only have to watch for the rare cases where you have a capital mid-sentence, and that sentence happens to be long enough to break just before that mid-sentence word. EDIT: you probably want to account for indentation too: "\f\\|[ ]*$\\|^[ ]*[A-Z]" The space between the square brackets contains a space and a tab. EDIT: you need to turn off case-fold-search for this to work, otherwise capitals and lower case letters are not distinguished in the match! EDIT: if you want to turn off case-fold-search for just this function, bind the following to M-q (which you can do locally or globally, as you see fit). (defun my-fill-paragraph () (interactive) (let ((case-fold-search nil)) (fill-paragraph))) A: Does this DTRT? (defun separate-sentences (&optional beg end) "ensure each sentence ends with a new line. When no region specified, use current paragraph." (interactive (when (use-region-p) (list (region-beginning) (region-end)))) (unless (and beg end) (save-excursion (forward-paragraph -1) (setq beg (point)) (forward-paragraph 1) (setq end (point)))) (setq end (if (markerp end) end (set-marker (make-marker) end))) (save-excursion (goto-char beg) (while (re-search-forward (sentence-end) end t) (unless (or (looking-at-p "[ \t]*$") (looking-back "^[ \t]*")) (insert "\n"))))) (defun fill-paragraph-sentence-groups (justify) "Groups of sentences filled together. A sentence ending with newline marks end of group." (save-excursion (save-restriction (narrow-to-region (progn (forward-paragraph -1) (point)) (progn (forward-paragraph 1) (point))) (goto-char (point-min)) (skip-chars-forward " \t\n") (while (not (or (looking-at-p paragraph-separate) (eobp))) (fill-region (point) (progn (loop do (forward-sentence 1) until (looking-at "[ \t]*$")) (point)) justify) (unless (looking-back "^[ \t]*") (forward-line 1))) t))) (defun fill-paragraph-sentence-individual (justify) "Each sentence in paragraph is put on new line." (save-excursion (separate-sentences) (fill-paragraph-sentence-groups justify))) ;; deployment option 1: add to major-mode hook (add-hook 'text-mode-hook (lambda () (set (make-local-variable fill-paragraph-function) 'fill-paragraph-sentence-individual))) ;; deployment option 2: call my-fill-paragraph any where (defun my-fill-paragraph (arg) (interactive "*P") (let ((fill-paragraph-function 'fill-paragraph-sentence-individual)) (fill-paragraph arg))) Two paragraph filling functions are presented above. One grouping sentences that don't end on new line together. Another breaking every sentence into a new line. I only show how to deploy the individual one because that's what the OP wants. Follow the model to deploy the groups version if you wish. A: You can use fill-region which, unsurprisingly, only fills the current region. Based on that you could define a fill-sentence function. I guess a simplistic way to detect such sentences is to say: * *If the line ends with a ., ?, or !, it's an end-of-sentence line. *A line starts a sentence if its predecessor line is either empty or an end-of-sentence line. It's rather tricky to get it to work correctly in all cases, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to add mysql JDBC driver to Eclipse so it can be used by SQL Explorer? I would like where am I supposed to install MySQL JDBC driver in Eclipse so it can be detected and used by SQL Explorer. Just to be clear, if possible, I would like to copy the MySQL J connector to somewhere inside Eclipse. Also a solution with an Eclipse install repository would also be good. A: Check this Driver Preferences A: you can use this tutorial : http://www.od2dev.be/configuring-aptana-to-connect-mysql-databases/ and it work even without the part of changing the port used by mysql A: Just click the Edit button, and specify the correct location of the jar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7554325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Default initialisation creating an Array of struct vs class objects I understand that struct is value type and class is reference type in .Net. I would like to know if there is any better solution here. Example, public struct Holder { public double Value { get; set; } public Holder() { this.Value = 0.0; } } Usage of this struct: void SomeFunction(int n) { Holder[] valueHolders = new Holder[n]; ... valueHolders[0].Value = someValue; } This works perfectly fine. Now just changing Holder to class. It throws an null object reference because valueHolders contails all values as null. Now I have changed my code to valueHolders[0] = new Holder(); valueHolders[0].Value = someValue; It works fine. Is there any way to create all elements in valueHolders at once like it was doing when it was a struct type. A: C# requires a reference type to be initialized explicitly. This can be done quite easily within a loop: Holder[] valueHolders = new Holder[n]; for (int i = 0; i < n; i++) { valueHolders[i] = new Holder(); } You can take this a bit further and expose a static method on your class like this: public class Holder { static public Holder[] InitArray(ulong length) { Holder[] holders = new Holder[length]; for (ulong i = 0; i < length; i++) { holders[i] = new Holder; } return holders; } } ... var valueHolders = Holder.InitArray(n); You can take it even further with a generic extension method: public static class ArrayInitializer { public static T[] Init<T>(this T[] array) where T : new() { for(int i = 0; i < array.Length; i++) { array[i] = new T(); } return array; } } ... var valueHolders = new Holder[n].Init();
{ "language": "en", "url": "https://stackoverflow.com/questions/7554328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }