text
stringlengths
8
267k
meta
dict
Q: What is difference between new and new[1]? What is difference between new and new[1]? Can I use delete with new[1]? Edit Well well well, I should've provided the background, sorry for that. I was evaluating BoundsChecker at work with VS 2010 and it complained about a memory leak when I used delete[] on new[1]. So in theory I know how the new and delete pair should be used but this particular situation confused me about the things under the hood. Any idea whats happening? A: new[] is an operator to allocate and initialize an array of objects and return a pointer to the first element. This differs from the new operator which has the same behavior but for one allocation, not an array. For deallocation and object destruction, new should be used with delete and new[] with delete[]. // operator new[] and new example // create array of 5 integers int * p1 = new int[5]; delete[] p1; // regular allocation of one int int * p1 = new int; delete p1; (see here for more details) A: Ed and aix are right, but there is much more going on underneath the hood. If you use new, then delete, the delete call will execute one destructor. If you use new[], you must use delete[], but how can delete[] know how much destructors to call? There might be an array of 2 instances, or one of 2000 instances? What some (possibly most or all) compilers do, is to store the number of instances right before the memory it returns to you. So if you call new[5], then new will allocate memory like this: +---+-----------+-----------+-----------+-----------+-----------+ | 5 | instance1 | instance2 | instance3 | instance4 | instance5 | +---+-----------+-----------+-----------+-----------+-----------+ And you get a pointer back to instance1. If you later call delete[], delete[] will use the number (in this case 5) to see how many destructors it needs to call before freeing the memory. Notice that if you mix new with delete[], or new[] with delete, it can go horribly wrong, because the number might be missing, or the number might be incorrect. If mixing new[1] with delete works, you might be just lucky, but don't rely on it. A: new creates an instance, whereas new[1] creates a single-element array. new[1] will almost certainly incur (small) memory overhead compared to new to store the size of the array. You can't use non-default constructors with new[]. new must be used with delete. new[] must be used with delete[]. A: 'new[1]' creates an array of one item. Need to use delete[] to free the memory. new just creates an object. Use delete with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: C# linq map composite dictionary with list I have one composite dictionary and one list Dictionary<Point, List<int>> GroupedIndex List<double> TobeMatched Now I want to create new dictionary with same key but with Values mapped by corresponding index from the GroupedIndex int values with TobeMatched index Example: GroupedIndex: [0] -> Key [X=1;Y=1]; Values [0] -> 5, [1] -> 10 TobeMatched: [0] 0.23 [5] 0.345 [10] 1.23 Result expected: New dictionary: [0] -> Key[X=1;Y=1]; Values [0] -> 0.345, [1] -> 1.23 is it possible to linq to achieve the result efficiently. For loop is very inefficient. A: GroupedIndex.ToDictionary(x => x.Key, x => x.Value.Select(y=>TobeMatched[y]).ToList()); That's how you do this with LINQ. But I doubt it will be faster compared to regular loops.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Print Monitor - Error whil installing I have written a virtual printer driver that includes print monitor dll as well infs. Only problem is that when i try to run the install it with command below, I get "the specified port is unknown, error 0x0000704. rundll32 printui.dll,PrintUIEntry /if /b "aPrinter" /f aprinter.inf /r "aPrinter Port" /m "aPrinter" Its kinda strange , cause i can see the aPrinter Port in registry at following place HKEY_LOCAL_MACHINE "SYSTEM\CurrentControlSet\Control\Print\Monitors\aPrinter Port with following string entries "Driver" "aport.dll" "name" "aPrinter Port" Any idea , what i am missing here? Thanks A: When I manually install a printer port, I set it on registry under the print monitor I want to use with a printer. SYSTEM\CurrentControlSet\Control\Print\Monitors\your_monitor_name\aPrinter Port
{ "language": "en", "url": "https://stackoverflow.com/questions/7510607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to clear session of external website using PHP, JavaScript I am loading an external website using iframe in my site. In iframe src URL, I am passing the username and password to login directly to the external website to show the registered content. Now if I logout in my site, I need to clear the session of the external website too. I have the logout URL of the external website. Without knowing my site user (in background), I need to call this logout URL. Anyone please help me on this. A: you can't, think of the security implications if you could. (ps. iframes suck) A: If the other site doesn't have CSRF protection you can do a bit of magic to make the request. s = document.createElement('script'); s.type = 'text/javascript'; s.src = 'http://url.to.other.site/logout?or=whatever'; document.head.appendChild(s); Unless the response is valid javascript it will produce an error, but the request will be made in any case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nowrap / Don't break the line after a input If i have several input (radio or option) followed by their label, all on the same line. How i make it so it don't break the line after the radio, but break if needed after the label. <input type="radio" id="i1"/><label for="i1">First radio</label> <input type="radio" id="i2"/><label for="i2">Second radio</label> <input type="radio" id="i3"/><label for="i3">Third radio</label> I can think of wrapping both input and label in a span with nowrap, but wonder if there's another way. A: This should do the trick: #MyDiv {width: 250px;} <div id="MyDiv"> <nobr><input type="radio" id="i1"/><label for="i1">First radio</label></nobr> <nobr><input type="radio" id="i2"/><label for="i2">Second radio</label></nobr> <nobr><input type="radio" id="i3"/><label for="i3">Third radio</label></nobr> </div> The <nobr> tag will ensure the break won't happen between the button and label. CSS way is also possible, wrapping it with another <span> and using white-space: nowrap; should work fine. A: I think this is what you're looking for: http://jsfiddle.net/catalinred/kNUaz/ A: Nothing worked for me (or at least I thought so, until I fixed it)... My dirty solution therefore was to use the tables, 1 row, multiple columns. You may need to adjust the padding/spacing. Edit: Warning this is a bad way of doing things, but if nothing works it might help. <table border="0" > <tbody> <tr> <td><input name="gender" type="radio" value="male" checked> Male </td> <td><input name="gender" type="radio" value="female"> Female </td> </tr> </tbody> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/7510612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: IOError: 13, 'Permission denied' when writing to /etc/hosts via Python I have a Python app that I'm working on that needs to access the hosts file to append a few lines. Everything worked on my test file, but when I told the program to actually modify my hosts file in /etc/hosts I get IOError 13. From what I understand, my app doesn't have root privileges. My question is, how can I circumnavigate this issue? Is there a way to prompt the user for their password? Would the process be any different if I was running the app on a Windows machine? Here's the code in question: f = open("/etc/hosts", "a") f.write("Hello Hosts File!") Also, I plan on using py2app and py2exe for the final product. Would they handle the root privilege issue for me? A: The easiest way to handle this is to write out your changes to a temp file, then run a program to overwrite the protected file. Like so: with open('/etc/hosts', 'rt') as f: s = f.read() + '\n' + '127.0.0.1\t\t\thome_sweet_home\n' with open('/tmp/etc_hosts.tmp', 'wt') as outf: outf.write(s) os.system('sudo mv /tmp/etc_hosts.tmp /etc/hosts') When your Python program runs sudo, the sudo program will prompt the user for his/her password. If you want this to be GUI based you can run a GUI sudo, such as "gksu". On Windows, the hosts file is buried a couple subdirectories under \Windows. You can use the same general trick, but Windows doesn't have the sudo command. Here is a discussion of equivalents: https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows A: If you are on the sudoers list, you can start your progamm with sudo: sudo python append_to_host.py sudo runs your python interpreter with root privileges. The first time you do it, you will be asked for your password, later calls will not ask you if your last sudo call is not to long ago. Being on the sudoers list (in most cases /etc/sudoers) says that the admin trusts you. If you call sudo you are not asked for the root password, but yours. You have to prove that the right user sits at the terminal. More about sudo on http://en.wikipedia.org/wiki/Sudo If you want to remote controll this you can use the -S command line switch or use http://www.noah.org/wiki/pexpect
{ "language": "en", "url": "https://stackoverflow.com/questions/7510617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java compatible English Dictionary API? I am trying to mimic a simple news reader, a desktop application developed on swings. As a part of this I am looking at including a dictionary lookup for a word from within the tool. I am looking at trying to display the meaning for word as a tool tip that appears upon a double click on JTextpane's content(one single word). So is there an exposed API for dictionary look-up? Also considering the fact that I am using java swings, the speed with which the API performs dictionary look up is also a key concern in my case.. A: The main thing you need to a table of words and meanings. Once you have that the rest should be straight forward. For a dictionary loop, you could use a Dictionary class, but I would use LinkedHashMap<String, String> to store words and meanings. This will take less than one micro-second to do the lookup get(), which should be fast enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I there a good ruby book for learning sockets programming? Is there a good book for ruby sockets programming or we have to rely on Unix C books for theory and source ?. A: If the goal is to learn socket programming I would recommend using C and reading through some Unix system programming books. The books will probably be much better and go into more detail than a sockets book that is Ruby specific (mainly because C, Unix and sockets have been around much longer than Ruby and my quick Googling didn't find a Ruby specific book). Books I would recommend: * *Unix Systems Programming *Unix Network Programming Volume 1 After getting a handle on the sockets in general (even if you don't write any C) the Ruby API for sockets will make much more sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validate and get data from Facebook cookie using OAUTH 2.0 I have a web page made in GWT. There I use all the login facebook stuff with a manipulated gwtfb library, all works fine. After migrating to oauth 2.0 now the cookie sent to the server has changed to a encrypted one. I want to get a java example code that implements in the server the same than the old one: * *I need to validate the call like I did before using the cookie md5 trick to know if the call has been made by my client page. *Get data from that cookie: I need the facebook user. If possible not calling FB, just using the cookie data. Thanks in advance. A: Well, although I have a few good answers I answer myself with what I have written in my blog: http://pablocastilla.wordpress.com/2011/09/25/how-to-implement-oauth-f/ Now the cookie has changed a lot: it is encrypted, doesn't have the accesstoken and its content format has changed a lot. Here you have a few links talking about it: http://developers.facebook.com/docs/authentication/signed_request/ http://developers.facebook.com/docs/authentication/ http://blog.sociablelabs.com/2011/09/19/server-side-changes-facebook-oauth-2-0-upgrade/ So to validate the cookie, get the user from it and get the access token you could use this code: public class FaceBookSecurity { // return the fb user in the cookie. public static String getFBUserFromCookie(HttpServletRequest request) throws Exception { Cookie fbCookie = getFBCookie(request); if (fbCookie == null) return null; // gets cookie value String fbCookieValue = fbCookie.getValue(); // splits it. String[] stringArgs = fbCookieValue.split("\\."); String encodedPayload = stringArgs[1]; String payload = base64UrlDecode(encodedPayload); // gets the js object from the cookie JsonObject data = new JsonObject(payload); return data.getString("user_id"); } public static boolean ValidateFBCookie(HttpServletRequest request) throws Exception { Cookie fbCookie = getFBCookie(request); if (fbCookie == null) throw new NotLoggedInFacebookException(); // gets cookie information String fbCookieValue = fbCookie.getValue(); String[] stringArgs = fbCookieValue.split("\\."); String encodedSignature = stringArgs[0]; String encodedPayload = stringArgs[1]; //decode String sig = base64UrlDecode(encodedSignature); String payload = base64UrlDecode(encodedPayload); // gets the js object from the cookie JsonObject data = new JsonObject(payload); if (!data.getString("algorithm").Equals("HMAC-SHA256")) { return false; } SecretKey key = new SecretKeySpec( ApplicationServerConstants.FacebookSecretKey.getBytes(), "hmacSHA256"); Mac hmacSha256 = Mac.getInstance("hmacSHA256"); hmacSha256.init(key); // decode the info. byte[] mac = hmacSha256.doFinal(encodedPayload.getBytes()); String expectedSig = new String(mac); // compare if the spected sig is the same than in the cookie. return expectedSig.equals(sig); } public static String getFBAccessToken(HttpServletRequest request) throws Exception { Cookie fbCookie = getFBCookie(request); String fbCookieValue = fbCookie.getValue(); String[] stringArgs = fbCookieValue.split("\\."); String encodedPayload = stringArgs[1]; String payload = base64UrlDecode(encodedPayload); // gets the js object from the cookie JsonObject data = new JsonObject(payload); String authUrl = getAuthURL(data.getString("code")); URL url = new URL(authUrl); URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null); String result = readURL(uri.toURL()); String[] resultSplited = result.split("&"); return resultSplited[0].split("=")[1]; } // creates the url for calling to oauth. public static String getAuthURL(String authCode) { String url = "https://graph.facebook.com/oauth/access_token?client_id=" + ApplicationConstants.FacebookApiKey + "&redirect_uri=&client_secret=" + ApplicationServerConstants.FacebookSecretKey + "&code=" + authCode; return url; } // reads the url. private static String readURL(URL url) throws IOException { InputStream is = url.openStream(); InputStreamReader inStreamReader = new InputStreamReader(is); BufferedReader reader = new BufferedReader(inStreamReader); String s = ""; int r; while ((r = is.read()) != -1) { s = reader.readLine(); } reader.close(); return s; } private static String base64UrlDecode(String input) { String result = null; Base64 decoder = new Base64(true); byte[] decodedBytes = decoder.decode(input); result = new String(decodedBytes); return result; } private static Cookie getFBCookie(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (cookies == null) return null; Cookie fbCookie = null; for (Cookie c : cookies) { if (c.getName().equals( "fbsr_" + ApplicationServerConstants.FacebookApiKey)) { fbCookie = c; } } return fbCookie; } } A: I just added this to a new release (2.1.1) of BatchFB: http://code.google.com/p/batchfb/ To get the user id: FacebookCookie data = FacebookCookie.decode(cookie, YOURAPPSECRET); System.out.println("Facebook user id is " + data.getFbId()); You can see the code here, which uses Jackson to parse the JSON and javax.crypto.Mac to verify the signature: http://code.google.com/p/batchfb/source/browse/trunk/src/com/googlecode/batchfb/FacebookCookie.java Unfortunately getting the access token is considerably more complicated. The data that comes in the fbsr_ cookie includes a "code" which you can then use to make a graph api fetch to get a real access token... which you would have to store in a cookie or session somewhere. This is incredibly lame. An better solution is to set your own access token cookie from javascript. Every time you call FB.getLoginStatus(), have it set (or remove) your own cookie. You don't need to worry about signing the access token since it's unguessable. A: I think the cookie data is in an arbitary format - because you shouldn't be interpreting it yourself? Surely the SDK should be validating the cookie for you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7510622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: rspec mocking "undefined method `stub_model' for # (NoMethodError)" I'm using Rails 3.1 and I wanted to add some stubs and mocks to my specs but I get a NoMethodError: undefined method `stub_model' for #<Class:0x007ff9c339bd80> (NoMethodError) Here is an excerpt of my GemFile: gem 'rspec' gem 'rspec-rails' I ran bundle install and rails g rspec:install And here is the code that tries to create a stub_model 0 @flight = stub_model(Flight) 1 Flight.stub! (:all).and_return([@flight]) And here is spec_helper.rb: 0 # This file is copied to spec/ when you run 'rails generate rspec:install' 1 ENV["RAILS_ENV"] ||= 'test' 2 require File.expand_path("../../config/environment", __FILE__) 3 require 'rspec/rails' 4 5 # Requires supporting ruby files with custom matchers and macros, etc, 6 # in spec/support/ and its subdirectories. 7 Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} 8 9 RSpec.configure do |config| 10 # == Mock Framework 11 # 12 # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: 13 # 14 # config.mock_with :mocha 15 # config.mock_with :flexmock 16 # config.mock_with :rr 17 config.mock_with :rspec 18 19 # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures 20 config.fixture_path = "#{::Rails.root}/spec/fixtures" 21 22 # If you're not using ActiveRecord, or you'd prefer not to run each of your 23 # examples within a transaction, remove the following line or assign false 24 # instead of true. 25 config.use_transactional_fixtures = true 26 end I'm calling "rspec ./spec" and "bundle exec rspec ./spec" (tried both, no difference) Everything I'm doing seems to be textbook (in fact, I'm following The Rails 3 Way). What am I missing? A: Chances are that your original code was being run outside of a spec example. This will give the error you describe: class Foo; end describe Foo do @foo = stub_model(Foo) Foo.stub!(:all).and_return([@foo]) end but this will work: class Foo; end describe Foo do before do @foo = stub_model(Foo) Foo.stub!(:all).and_return([@foo]) end end A: See comment in original question. Like a bad knot in my neck, it seems to have worked itself out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: can i format the HTML alert box into my colors and style with css? i want to show an alert when someone click on Paypal button and the alert should say you will be directed to Paypal website but the basic html alert ox is awful in style , is there a way to improve its styling ? or i have to design a div and code its functionality too? A: No. However, you can create a DIV tag which will be positioned absolute to look like an alert box or use jQuery UI to easily create dialog boxes, here http://jqueryui.com/demos/dialog/
{ "language": "en", "url": "https://stackoverflow.com/questions/7510632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: QTP Frame work design that can scale along with the AUT Hi I am comfortable with the basics on QTP and DP. I am planning to build a framework with QTP for our web portal application , which consists of a very rich GUI and lot of features. Please explain me the basic things I should care about while designing the frame work and the main components the frame work should be having . A: When ever you are building a new framework there are lot many things that you would like to remember... * *How are you goint to share the code between multiple people working. There are different ways this can be done, either through using a reusable actions or by using a function library. *How are you going to share the object repository. Even before that, you have to think whether you are going to build a shared object repository or do you want to do descriptive programming. *How are you going to give the data to the qtp scripts? Are you going to use excel or some other methodology? *Look at some existing frameworks, most of the cases you will have to go with a hybrid framework. Don't write everything in the script, create modular scripts, that will help you to survive in the constantly changing world. you haven't mentioned what kind of GUI it is, see whether qtp supports that technology or not. Except to do mistakes and allow good buffer time. If you don't have much time, don't think too much about automating it. You have to see how many cycles you will have to run the test cases that are to be automated. Building a fresh framework is very tough challenge, if you don't do it right, you will have to waste all the money you spend on it. Take some expert help. Your question covers very broad range of topics. It cannot be answered in this small answer... check this link for better understanding... A Tutorial on QTP Automation Frameworks Check the answers for this question Another Question that has useful information for you
{ "language": "en", "url": "https://stackoverflow.com/questions/7510633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting image to anchor tag not working I want to set image to anchor tag but it is not working. Can anybody tell me what is wrong? <a href="#" style="width:200px;height:100px;background:url('@Url.Content("~/Content/Images/facebook.png")');"></a> Note: Don't pay attention to background. It is Asp.Net MVC syntax. But rest assured the image is loaded correctly. Can anybody tell me what am I doing wrong? If I type something in anchor tag it works fine. But I don't want to type anything. A: You need to either set the display property to block or inline-block for the link <a href="#" style="display:block; width:200px;height:100px; ... Links are inline by default. A: Because a link is an inline element, it can't have width and height. Set this attribute on it: display: inline-block;
{ "language": "en", "url": "https://stackoverflow.com/questions/7510640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tips for writing good EBNF grammars I'm writing some Extended Backus–Naur Form grammars for document parsing. There are lots of excellent guides for the syntax of these definitions, but very little online about how to design and structure them. Can anyone suggest good articles (or general tips) about how you like to approach writing these as there does seem to be an element of style even if the final parse trees can be equivalent. e.g. things like: * *Deciding if you should explicitly tag newlines, or just treat it as whitespace? *Naming schemes for your nonterminals *Handing optional whitespace in long definitions *When to use bad syntax checks vs just letting those not match Thanks, A: You should work in the direction that you are most comfortable with - either bottom-up, top-down, or "sandwich" (do a little of both, meet somewhere in the middle). Any "group" that can be derived and has a meaning of its own, should start from it's own non-terminal. So for example, I would use a non-terminal for all newline-related whitespaces, one for all the other whitespaces, and one for all whitespaces (which is basically the union of the former 2). Naming conventions in grammars in general are that non-terminals are, or start with, a capital letter, and terminals start with non-capitals (but this of course depends on the language you're designing). Regarding bad syntax checks, I'm not familiar with the concept. What I know of EBNFs are that you just write everything your language accepts, and only that. Generally, just look around at some EBNFs of different languages from different websites, get a feeling of how they look, and then do what feels right to you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android New Intent Problem ; startActivity(); Anyone have any idea why this don't works ? the startActivity(i); Not Working public class UiHelper { /** * About Dialog */ public static void showAboutDialog(Activity activity) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.about_title); // build view from layout LayoutInflater factory = LayoutInflater.from(activity); final View dialogView = factory.inflate(R.layout.about_dialog, null); TextView versionText = (TextView) dialogView.findViewById(R.id.about_version); versionText.setText(activity.getString(R.string.about_version) + " " + getVersion(activity)); builder.setView(dialogView); builder.setIcon(android.R.drawable.ic_dialog_info); /** builder.setNeutralButton(activity.getString(R.string.button_close), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } });**/ builder.setPositiveButton("Facebook", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String url = "http://www.facebook.com/page/"; final Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); /** <<-- Error <<--**/ } }); builder.setNegativeButton("Website", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String url = "http://www.website.com/"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); AlertDialog question = builder.create(); question.show(); } but i try this will works Working AlertDialog.Builder alert = new AlertDialog.Builder(PTRmainActivity.this); alert.setTitle("About"); alert.setMessage("Version 1.0.0"); alert.setIcon(R.drawable.icon); alert.setPositiveButton("Facebook", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String url = "http://www.facebook.com/page/"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); alert.setNegativeButton("Website", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String url = "http://www.website.com/"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); alert.show(); A: if you above code is on different class means not in main activity's class then try this one in your not working code.. activity.startActivity(i); A: Make the function take in a final argument: public static void showAboutDialog(final Activity activity) { and then use that argument to start the Activity (static functions don't have access to any non-static instance methods: builder.setPositiveButton("Facebook", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String url = "http://www.facebook.com/page/"; final Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); activity.startActivity(i); /** <<-- Error <<--**/ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Local Push Notification Settings and notification section in device settings I am using local push notifications in my app. I need the users to have an option in the push notification section of the device settings page. Currently my app is not listed under the notification section. Is there a way so that apps with local push notifications would also be listed in this section. Or, the notification section only shows apps with Apple Push Notification Service.(Remote APNS) A: The answer is already here. You can't be listed on settings->notifications, you handle it on your own in your app. But you can also (as mentioned in the previous answer) make your own Settings bundle (Apple documentation here).
{ "language": "en", "url": "https://stackoverflow.com/questions/7510645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LIKE vs CONTAINS on SQL Server Which one of the following queries is faster (LIKE vs CONTAINS)? SELECT * FROM table WHERE Column LIKE '%test%'; or SELECT * FROM table WHERE Contains(Column, "test"); A: I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com. The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results. A: Also try changing from this: SELECT * FROM table WHERE Contains(Column, "test") > 0; To this: SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0; The former will find records with values like "this is a test" and "a test-case is the plan". The latter will also find records with values like "i am testing this" and "this is the greatest". A: The second (assuming you means CONTAINS, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available. The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan. The CONTAINS query should be: SELECT * FROM table WHERE CONTAINS(Column, 'test'); A: Having run both queries on a SQL Server 2012 instance, I can confirm the first query was fastest in my case. The query with the LIKE keyword showed a clustered index scan. The CONTAINS also had a clustered index scan with additional operators for the full text match and a merge join. A: I didn't understand actually what is going on with "Contains" keyword. I set a full text index on a column. I run some queries on the table. Like returns 450.518 rows but contains not and like's result is correct SELECT COL FROM TBL WHERE COL LIKE '%41%' --450.518 rows SELECT COL FROM TBL WHERE CONTAINS(COL,N'41') ---40 rows SELECT COL FROM TBL WHERE CONTAINS(COL,N'"*41*"') -- 220.364 rows
{ "language": "en", "url": "https://stackoverflow.com/questions/7510646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "272" }
Q: todo tags not working on eclipse and pydev I'm using eclipse 3.7.0 on fedora and pydev 2.2.2 I tried to use the todo tags but it doesnt work. the todo tags on window > preferences looks fine. i can add a using left click beside the line. please advice A: Comments with #TODO will only generate tasks if: * *The code is in a source folder (i.e.: in the PYTHONPATH) *You have the builders turned on (or run the build manually from time to time). Reference: http://pydev.org/manual_adv_tasks.html The getting started guide ( http://pydev.org/manual_101_root.html ) has instructions on how to config PyDev properly so that things like todo tasks work properly A: Make sure you are writing: #TODO: This is my todo. Otherwise, it won't work. Note the colon after the 'O'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is this an example of an iOS UITableView? I need to do something like this : . Is it a UITableView? Or how should I do this? Any idea is welcome. Code: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.section == 0) { if (indexPath.row == 0) return cell1; } else if (indexPath.section == 1) { if (indexPath.row == 0) return cell2; } else if (indexPath.section == 2) { if (indexPath.row == 0) return cell3; } } A: Most likely its a UITableView. May be its not (it can be a UIScrollView with views added like sections in a table view). But if you want to create something like in the image, I'd suggest you to use UITableView with customized cells. Because implementing table view, in this case, is simpler as you have to just concern about the delegate and the dateSource of the table view, rather than worrying about aligning the views in order. Use sectioned table view with the translucent, gray-bordered, black-background-view as the backgroundView of the cells. Add the labels and arrow as the subviews of cell. You can add arrow as the accessoryView but that would become vertically centered, but in the image the arrow is displayed slightly on top of the cell. There should be only one cell in each section. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } There can be any number of sections (3 here). - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 3; // Can be any number } A: Yes, that's most likely a styled table view. See this guide or this nice tutorial. A: You can do this using tableView in - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { //here place return your array contents } A: why you worry about this one? Its simple man.... its nothing ,if you have hands over UITableView. Yeah, You must know about : 1: Set background image on view,exact as table size. 2: Set table view onto them and make background transparent. 3: Make customize table cell and add to table' row. Thats it.....enjoy this work..its a creativity. And you can do it guy.... A: I cannot tell exactly what is used from the picture, however I suggest using the UITableView especially if you have variable data coming from a structured object. Some tutorials which I found very useful are the following: Creating customized UITableViewCell from XIB http://www.bdunagan.com/2009/06/28/custom-uitableviewcell-from-a-xib-in-interface-builder/ UIViewTable anti-patterns - A very good MVC pattern to build UIViewTable http://www.slideshare.net/nullobject/uitableviewcontroller-antipatterns And of course Apple's docs: http:/developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html One important fact to remember is that you should always reuse cached table cells through the datasource method tableView:didSelectRowAtIndexPath: Note: Since you want lots of transparencies there might be some performance issue especially on older devices. Hope this helps and goodluck with your project. A: There is not need to its scrollview or tableview... both are perform same.. Just change the Background Color of Tableview as clear color..... check this code... put this line to viewDidLoad : [tableView setBackgroundColor:[UIColor clearColor]]; and * *(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ ..... // Your label buttons etc........ ...... ...... ..... [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; [cell setClipsToBounds:YES]; [[cell layer] setBorderColor:[[UIColor blackColor] CGColor]]; [[cell layer] setCornerRadius:10]; } A: We can accomplish the similar as shown in image above by Table View and scroll view both.If you don't want to use table view then you can take a scroll view or a simple view and can add several buttons along with the image in background with different frames.It means button background will have the same image.then you can use different labels to show all the texts in different labels according to the requirement. OR you can use table view.For this you need to return number of sections 3(in this image) in the delegate method - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView.and then everything as the default tableview style.And then change the cell style to detailed. A: yes this is a tableView with custom UITableViewCell.you can do that by creating a empty xib file and then add a UITableViewCell and do your customizing ...then in cellForRowAtIndexPath method use: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:edentifier]; if (cell == nil) { cell = [[[NSBundle mainBundle]loadNibNamed:@"yourCellName" owner:self options:nil]objectAtIndex:0]; this is from my application. A: Yes, it is a groupedtableview with clearcolor as backgroundcolor. Cell background color also needs to be changed to clearcolor. A: I suggest using div or list, don't use table, its very hard to control if the contents are too long.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call javascript function with parameter in jquery event handler? I am stuck. Searched and tried for hours. EDIT: I still can't make it work. Okay, I'll just put the source code to make it clear what I want to accomplish. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> <script type="text/javascript"> var date_fmt="yyyy-mm-dd"; var time_fmt="HH:MM"; var date_field="#id_start_0, #id_end_0"; //id refering to html input type='text' var time_field="#id_start_1, #id_end_1"; //id refereing to html input type='text' function clearFmt(fmt_type) { if($(this).val() == fmt_type) { $(this).val(""); } } function putFmt(fmt_type) { if($(this).val() == "") { $(this).val(fmt_type); } } $(document).ready(function() { $(date_field).attr("title",date_fmt); $(time_field).attr("title",time_fmt); $(date_field).click(function() { clearFmt(date_fmt); }); $(date_field).blur(function(){ putFmt(date_fmt); }); $(time_field).click(function(){ clearFmt(time_fmt); }); $(time_field).blur(function(){ putFmt(time_fmt); }); }); </script> Help ? A: The following should work as seen in this live demo: function myfunc(bar) { alert(bar); } $(function() { $("#foo").click( function() { myfunc("value"); }); }); A: Use the jquery bind method: function myfunc(param) { alert(param.data.key); } $(document).ready( function() { $("#foo").bind('click', { key: 'value' }, myfunc); }); Also see my jsfiddle. === UPDATE === since jquery 1.4.3 you also can use: function myfunc(param) { alert(param.data.key); } $(document).ready( function() { $("#foo").click({ key: 'value' }, myfunc); }); Also see my second jsfiddle. === UPDATE 2 === Each function has his own this. After calling clearFmt in this function this is no longer the clicked element. I have two similar solutions: In your functions add a parameter called e.g. element and replace $(this) with element. function clearFmt(element, fmt_type) { if (element.val() == fmt_type) { element.val(""); } } Calling the function you have to add the parameter $(this). $(date_field).click(function() { clearFmt($(this), date_fmt); }); Also see my third jsfiddle. -=- An alternative: function clearFmt(o) { if ($(o.currentTarget).val() == o.data.fmt_type) { $(o.currentTarget).val(""); } } $(date_field).click({fmt_type: date_fmt}, clearFmt); Also see my fourth jsfiddle. A: anyFunctionName = (function() { function yourFunctionName1() { //your code here } function yourFunctionName2(parameter1, param2) { //your code here } return { yourFunctionName1:yourFunctionName1, yourFunctionName2:yourFunctionName2 } })(); $document.ready(function() { anyFunctionName.yourFunctionName1(); anyFunctionName.yourFunctionName2(); }); Note: if you don't use 'anyFuctionName' to declare any function then no need return method. just write your function simply like, yourFunctionName1(). in $document.ready section parameter is not issue. you just put your function name here. if you use 'anyFuctionName' function then you have to follow above format. A: function myfunc(e) { alert(e.data.bar); //this is set to "value" } $("#foo").click({bar: "value"}, myfunc); A: People are making this complicated, simply call directly as you would in Javascript myfunc("value");
{ "language": "en", "url": "https://stackoverflow.com/questions/7510654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: how can I use multiple ModelMetaDataProvider's w/asp.net-mvc3 I have a custom ModelMetadataProvider which takes care of everything so far. But I have a couple of new classes where I am going to let users customize the metadata in the database and store settings like display name, sql query for combo's and some other stuff like that. Well I am happy with my current ModelMetadataProvider, so I do not want to inject new functionality into it, I'd rather have a new ModelMetadataProvider for this, and a way of telling the !dependency resolver! to pick the right data provider for a given class? Is this possible, and if so how? Thanks in advance...
{ "language": "en", "url": "https://stackoverflow.com/questions/7510661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Pop gives error when trying to Center in application Hello I am having this error when trying to center my popUp. If I remove the centerPopUp code line, the popUp appears but of course is not centered. The Error is as such: TypeError: Error #1009: Cannot access a property or method of a null object reference. at mx.managers::PopUpManagerImpl/centerPopUp()[E:\dev\4.5.1\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:494] My Code: var helpWindow:TitleWindow= PopUpManager.createPopUp(this, screen_Name, true) as TitleWindow; PopUpManager.centerPopUp(helpWindow); Can someone address this issue? A: You should be passing the FlexGlobals.topLevelApplication as an argument to createpopup if you want to center your panel/titleWindow later on. So, here it will be var helpWindow:TitleWindow= PopUpManager.createPopUp(this,FlexGlobals.topLevelApplication , true) as TitleWindow; PopUpManager.centerPopUp(helpWindow); Im sure this will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NetBeans: How to select JLabel that resides inside JFrame? I developed a small desktop application in Java. At some position in my UI I drag and drop a JLabel from Palette to JFrame. Later-on i remove its text by right click -> Edit Text. I did this because i am populating this label dynamically using setText() method. Now i need to reposition this Label, for this i first have to select that label and then drag n drop it to new location. But i am unable to do so because there is no text in that label and hence its not visible :( Is there any way through which i select this label? A: The easiest way is add a few spaces to a label instead of an empty string. You may also put a label inside a panel with layout like Flow or Grid (where you can set margin) and drag the panel instead. If you're using layout like Free Design, Absolute or Null, you may also manually rescale the label (selecting it through Inspector view).
{ "language": "en", "url": "https://stackoverflow.com/questions/7510666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to get a Scala HashMap to automatically initialize values?' I thought it could be done as follows val hash = new HashMap[String, ListBuffer[Int]].withDefaultValue(ListBuffer()) hash("A").append(1) hash("B").append(2) println(hash("B").head) However the above prints the unintuitive value of 1. I would like hash("B").append(2) To do something like the following behind the scenes if (!hash.contains("B")) hash.put("B", ListBuffer()) A: withDefaultValue uses exactly the same value each time. In your case, it's the same empty ListBuffer that gets shared by everyone. If you use withDefault instead, you could generate a new ListBuffer every time, but it wouldn't get stored. So what you'd really like is a method that would know to add the default value. You can create such a method inside a wrapper class and then write an implicit conversion: class InstantiateDefaults[A,B](h: collection.mutable.Map[A,B]) { def retrieve(a: A) = h.getOrElseUpdate(a, h(a)) } implicit def hash_can_instantiate[A,B](h: collection.mutable.Map[A,B]) = { new InstantiateDefaults(h) } Now your code works as desired (except for the extra method name, which you could pick to be shorter if you wanted): val hash = new collection.mutable.HashMap[ String, collection.mutable.ListBuffer[Int] ].withDefault(_ => collection.mutable.ListBuffer()) scala> hash.retrieve("A").append(1) scala> hash.retrieve("B").append(2) scala> hash("B").head res28: Int = 2 Note that the solution (with the implicit) doesn't need to know the default value itself at all, so you can do this once and then default-with-addition to your heart's content. A: Use getOrElseUpdate to provide the default value at the point of access: scala> import collection.mutable._ import collection.mutable._ scala> def defaultValue = ListBuffer[Int]() defaultValue: scala.collection.mutable.ListBuffer[Int] scala> val hash = new HashMap[String, ListBuffer[Int]] hash: scala.collection.mutable.HashMap[String,scala.collection.mutable.ListBuffer[Int]] = Map() scala> hash.getOrElseUpdate("A", defaultValue).append(1) scala> hash.getOrElseUpdate("B", defaultValue).append(2) scala> println(hash("B").head) 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7510671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: copying oracle tables to DB2 I want to access oracle tables in DB2(something like DBlink from DB2 to oracle).Any help is appreciated. A: You can use db2 federation. One link is here. A: Oracle has a feature called Heterogeneous Services which allows us to build links between Oracle databases and non-Oracle databases, including DB2. Find out more. A: import com.ibm.db2.jcc.am.gc; import com.ibm.db2.jcc.t2zos.s; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import static org.omg.IOP.ENCODING_CDR_ENCAPS.value; public class automateExport { static String value; public static void main(String[] args) throws SQLException, ClassNotFoundException { // ResultSet rs = null; String table_name; Integer temp = 0; Integer temp1 = 0; Integer temp2 = 1; String column_name = null; String tableName = null; String columnType = null; int precision = 0; Class.forName("oracle.jdbc.driver.OracleDriver"); Connection codal = DriverManager.getConnection("jdbc:oracle:thin:@192.168.01.53:1521:orcl", "NAVID", "oracle"); StringBuilder sb = new StringBuilder(1024); Connection DB2 = getConnection(); String sql = "SELECT TABSCHEMA,TABNAME,COLNAME,TYPENAME,LENGTH FROM SYSCAT.COLUMNS WHERE TABSCHEMA NOT LIKE 'SYS%' "; PreparedStatement mainStmt = DB2.prepareStatement(sql); ResultSet rs = mainStmt.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); String str1 = "ADMIN2"; while (rs.next()) { table_name = rs.getString(2); if (table_name.equalsIgnoreCase(str1)) { if (temp1 == 0) { sb.append("create table").append(" "); sb.append(table_name).append("( "); if (temp2 == 0) { sb.append(" ").append(column_name).append(" ").append(columnType); if (precision != 0) { sb.append("( ").append(precision).append(" )"); sb.append(", "); } } temp1 = 1; temp = 1; } if (temp == 0) { sb.append(table_name).append("("); temp = 1; } column_name = rs.getString(3); columnType = rs.getString(4); sb.append(" ").append(column_name).append(" ").append(columnType); precision = rs.getInt(5); if (precision != 0) { sb.append("( ").append(precision).append(" )"); sb.append(", "); } } else { temp2 = 0; sb.replace(sb.length() - 2, sb.length(), ""); sb.append(" )"); temp1 = 0; str1 = str1.replaceAll(str1, table_name); column_name = rs.getString(3); columnType = rs.getString(4); precision = rs.getInt(5); String sql2 = sb.toString(); PreparedStatement m = codal.prepareStatement(sql2); m.executeUpdate(); sb.delete(0, sb.length()); } } codal.close(); DB2.close(); /* } private static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("COM.ibm.db2os390.sqlj.jdbc.DB2SQLJDriver"); Connection connection = DriverManager.getConnection("jdbc:db2://localhost:50000/navid", "navid", "oracle"); return connection; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use Castle.Windsor in an assembly loaded using reflection Let's say I have a library Lib.dll, which uses Castle.Windsor to initialize its services. I have a main application App.exe, which loads Lib.dll on runtime using reflection. App.exe does not know the location of Lib.dll beforehand, it is only known at runtime. In this case, when App.exe loads Lib.dll and Lib.dll initialize its services, a System.TypeInitializationException exception is thrown, because Castle.Windsor cannot find the service type. Castle.MicroKernel.SubSystems.Conversion.ConverterException: Could not convert from 'Lib.TheServiceClass' to System.Type - Maybe type could not be found at Castle.MicroKernel.SubSystems.Conversion.TypeNameConverter.PerformConversion(String value, Type targetType) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\SubSystems\Conversion\TypeNameConverter.cs:line 91 at Castle.MicroKernel.SubSystems.Conversion.DefaultConversionManager.PerformConversion(String value, Type targetType) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\SubSystems\Conversion\DefaultConversionManager.cs:line 134 at Castle.MicroKernel.SubSystems.Conversion.DefaultConversionManager.PerformConversion[TTarget](String value) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\SubSystems\Conversion\DefaultConversionManager.cs:line 162 at Castle.Windsor.Installer.DefaultComponentInstaller.SetUpComponents(IConfiguration[] configurations, IWindsorContainer container, IConversionManager converter) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\Installer\DefaultComponentInstaller.cs:line 196 at Castle.Windsor.Installer.DefaultComponentInstaller.SetUp(IWindsorContainer container, IConfigurationStore store) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\Installer\DefaultComponentInstaller.cs:line 52 at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\WindsorContainer.cs:line 327 at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\WindsorContainer.cs:line 674 Apparently Castle cannot find my service class because it is in Lib.dll that is not located in App.exe's directory. When I copy Lib.dll to App.exe directory, the problem goes away, but having to copy this is not something we want. So how can my code in Lib.dll tell Castle.Windsor to load the class in the correct location? (in Lib.dll location instead of in App.exe location) A: You can try to load the unresolved assemblies within your code by AssemblyResolve event AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { string typeToLoad = args.Name; string myPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; return Assembly.LoadFile(...); //or return Assembly.GetExecutingAssembly() etc. }; A: You probably will consider loading the plugin in a separate AppDomain, with a different private path, look at AppDomainSetup. Of course there is a drawback that you neeed a separate app domain for your plugin, but sometimes this is considered a good practice. A: You probably can't do it in easy and elegant way if App.exe doesn't provide you Castle Windsor's container instance to configure your services. If it is not exposed directly, maybe you can access it using Service Locator? Or find it on your own using reflection on App.exe assembly? The best solution will be if code in App.exe calls specific method in your library (i.e. it can look for particular interface implementation, like IModuleInitializer or something, create an instance of it and call some kind of Initialize method passing container instance to your code). You could also think about extensibility frameworks like MEF, but that can be a bit overkill and make big influence on App.exe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Design Pattern in Java Software Development I am going to make a web application. It is based of RESTful API in java. I want to implement Manager Pattern and DAO Pattern in that. Can anybody suggest a good book/reference which leads me to develop a good web application using that patterns? A: I would recommend the books of Adam Bien. http://press.adam-bien.com/ A: J2EE design patterns By William Crawford, Jonathan Kaplan. This book is good for J2EE applications. Please have a look at it. A: RESTful Web Services ,pub by o'reilly. Book Description: "Every developer working with the Web needs to read this book."-- David Heinemeier Hansson, creator of the Rails framework "RESTful Web Services finally provides a practical roadmap for constructing services that embrace the Web, instead of trying to route around it."-- Adam Trachtenberg, PHP author and EBay Web Services Evangelist You've built web sites that can be used by humans. But can you also build web sites that are usable by machines? That's where the future lies, and that's what RESTful Web Services shows you how to do. The World Wide Web is the most popular distributed application in history, and Web services and mashups have turned it into a powerful distributed computing platform. But today's web service technologies have lost sight of the simplicity that made the Web successful. They don't work like the Web, and they're missing out on its advantages. This book puts the "Web" back into web services. It shows how you can connect to the programmable web with the technologies you already use every day. The key is REST, the architectural style that drives the Web. This book: * Emphasizes the power of basic Web technologies -- the HTTP application protocol, the URI naming standard, and the XML markup language * Introduces the Resource-Oriented Architecture (ROA), a common-sense set of rules for designing RESTful web services * Shows how a RESTful design is simpler, more versatile, and more scalable than a design based on Remote Procedure Calls (RPC) * Includes real-world examples of RESTful web services, like Amazon's Simple Storage Service and the Atom Publishing Protocol * Discusses web service clients for popular programming languages * Shows how to implement RESTful services in three popular frameworks -- Ruby on Rails, Restlet (for Java), and Django (for Python) * Focuses on practical issues: how to design and implement RESTful web services and clients This is the first book that applies the REST design philosophy to real web services. It sets down the best practices you need to make your design a success, and the techniques you need to turn your design into working code. You can harness the power of the Web for programmable applications: you just have to work with the Web instead of against it. This book shows you how.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Opening native map application from url in iPhone, Android, Blackberry I was trying to open the native map application to show direction from Current Location to the given location. Understandably, the url should work on all the smart phones, not just iPhone. The most common url that can be used for all the phones can be maps.google.com. For iPhone I have used http://maps.google.com/maps?saddr=Current%20Location&daddr=lat,lon. It works perfectly fine, iPhone opens the map with my Current Location and the destination location and draws direction. But it doesn't work on other devices. Any suggestion ? Thanks. A: I've written a blog post addressing this topic and how open native map apps, not just the google site. Check it out here : http://habaneroconsulting.com/insights/Opening-native-map-apps-from-the-mobile-browser.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7510708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: problem in retriving multiple checkbox values I am unable to access the values of checkboxes i select. Here is my code which i tried. <input type="checkbox" id="<%= "gname_" + in.intValue() %>" name="chkBox" onclick='chkboxSelect(localArrGroupNames[<%=in.intValue() %>],<%= "gname_" + in.intValue() %>)'> JS code: function chkboxSelect( chkBoxValue, id){ var i=0; if(id.checked) { var selected; alert("id: " + chkBoxValue + i); selected[i] = chkBoxValue; i++; } } I get only one value in my alert though I select more than one value. For example if i select red, blue, green, After I select each, I get only one in my alert. Please help me . Thanks in advance. A: If all checkboxes have the same name chkBox <!DOCTYPE HTML> <html> <head> <title>Title of the document</title> <script> function getValues(){ var cbs = document.getElementsByName('chkBox'); var result = ''; for(var i=0; i<cbs.length; i++) { if(cbs[i].checked ) result += (result.length > 0 ? "," : "") + cbs[i].value; } alert(result); return result; } </script> </head> <body> <input type="checkbox" id="gname_1" name="chkBox" onclick='getValues();' value='red'>Red<br> <input type="checkbox" id="gname_2" name="chkBox" onclick='getValues();' value='green'>Green<br> <input type="checkbox" id="gname_3" name="chkBox" onclick='getValues();' value='blue'>Blue<br> </body> </html> A: If you use multiple checkboxes with the same name, your code shoud be like this: <input type="checkbox" name="chkBox[]" value="red"> <input type="checkbox" name="chkBox[]" value="green"> <input type="checkbox" name="chkBox[]" value="blue"> if you submit the form, you will get an array... ($_POST['chkBox'][0])
{ "language": "en", "url": "https://stackoverflow.com/questions/7510713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android - java.net.SocketException: Transport endpoint is not connected What is the meaning of the following exception? when does it occur?. Here is the exception log - 09-22 12:19:08.329: WARN/LogFilter(8361): Unable to shutdown server socket 09-22 12:19:08.329: WARN/LogFilter(8361): java.net.SocketException: Transport endpoint is not connected 09-22 12:19:08.329: WARN/LogFilter(8361): at org.apache.harmony.luni.platform.OSNetworkSystem.shutdownInputImpl(Native Method) 09-22 12:19:08.329: WARN/LogFilter(8361): at org.apache.harmony.luni.platform.OSNetworkSystem.shutdownInput(OSNetworkSystem.java:637) 09-22 12:19:08.329: WARN/LogFilter(8361): at org.apache.harmony.luni.net.PlainSocketImpl.shutdownInput(PlainSocketImpl.java:442) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.net.Socket.shutdownInput(Socket.java:819) 09-22 12:19:08.329: WARN/LogFilter(8361): at org.restlet.engine.http.StreamServerCall.complete(StreamServerCall.java:108) 09-22 12:19:08.329: WARN/LogFilter(8361): at org.restlet.engine.http.HttpServerAdapter.commit(HttpServerAdapter.java:477) 09-22 12:19:08.329: WARN/LogFilter(8361): at org.restlet.engine.http.HttpServerHelper.handle(HttpServerHelper.java:150) 09-22 12:19:08.329: WARN/LogFilter(8361): at org.restlet.engine.http.StreamServerHelper$ConnectionHandler.run(StreamServerHelper.java:90) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 09-22 12:19:08.329: WARN/LogFilter(8361): at java.lang.Thread.run(Thread.java:1102) thanks A: Maybe you are missing the permission: <uses-permission android:name="android.permission.INTERNET" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7510714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Application crashes at [[NSBundle mainBundle] pathForResource My Application is crashes in the device at this point, [[NSBundle mainBundle] pathForResource I am giving the path for the pdf here . but at the execution time it is showing that it is not getting path there . and that may be the reason for crashing. however it is running perfectly on simulator . i am not able to figure out why is this happening here is that code NSString *path = [[NSBundle mainBundle] pathForResource:[myArray objectAtIndex:0] ofType:[myArray objectAtIndex:1]]; NSLog(@"array elemt :%@", [myArray objectAtIndex:0]); NSLog(@"array elemt 1 :%@", [myArray objectAtIndex:1]); NSLog(@"path is :%@",path); NSLog(@"responds to selector mainBundle=%@",[NSBundle respondsToSelector:@selector(mainBundle)]?@"YES""NO"); NSURL *targetURL = [NSURL fileURLWithPath:path]; in this log of the path - when i use device it is showing me nil and when i use simulator it is showing me the path . and it is showing me that is is crashing on NSURL line A: I've found that when something like this works on the simulator, but not on the device, it's likely a problem with the case of the string. Your device is case sensitive but not your computer. Check your string of the file name or the type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Memory error in C program, The name disappears? Im trying to make a simple game, http://pastebin.com/BxEBB7Z6, in c. The goal is to beat the computer by getting as close to 21 as possible by getting random numbers. For each round the players name and sum is presented, but for some reasons it only works that first time? Something like this: Player John has sum 0. Player has sum 9. Player has sum 11. And so on. Why does the the player's name get showed once, but not any other prints after that? I dont do a reassign somewhere :-) I use the function void PrintPlayerSum(struct Player *p) to print it out, it works the first time, but only that. #include <stdio.h> #include <stdlib.h> #include <time.h> struct Player { char name[256]; int sum; }; void PrintPlayerSum(struct Player *p) { printf("Player %s has sum %d\n", p->name, p->sum); } void wait ( int seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } int main() { struct Player *player = malloc(sizeof(*player)); strcpy( player->name, "John"); player->sum = 0; while(1) { PrintPlayerSum(player); printf("Do you want another number? (y/n, q for quit) "); char ch; scanf("%s", &ch); if( ch == 'q' ) break; if( ch == 'y' ) { srand(time(NULL)); int rnd = rand() % 13 + 1; player->sum += rnd; printf("Player got %d\n", rnd); } if( ch == 'n' || player->sum > 21) { if( player->sum > 21 ) { printf("\n*** You lost the game, please try again... ***"); } else { printf("\nCPU's turn\n"); int cpusum = 0; while( 1 ) { if( cpusum > 21 ) { printf("\n*** CPU lost the game with the score %d, you win! ***", cpusum); break; } if( cpusum > player->sum ) { printf("\n*** CPU won the game with the score %d, please try again ***", cpusum); break; } wait(1); srand(time(NULL)); int rnd = rand() % 13 + 1; cpusum += rnd; printf("CPU got %d, sum is %d\n", rnd, cpusum); } } break; } printf("\n\n"); } /* Cleanup ******************/ free(player); /****************************/ printf("\n\n\n"); system("PAUSE"); return 0; } A: I suspect the problem is your use of scanf. You say you want to read a zero-terminated string, but you stuff it into a single char. The way the variables are laid out on the stack causes the terminating zero-byte to end up as the first char in player->name. Try typing "buffer overflow" instead of "y", and you should get "player uffer overflow go ...". If you want to stick with scanf, you want to make sure you pass it a proper string and set a limit on the size of the target buffer. For reading one char, try fgetc. Edit: The above is of course not quite right... It is a buffer overflow, but it is the pointer of the player struct that is being overwritten. By lucky coincidence you get to a valid address that points to a zero-byte. By typing more, you will most likely get a crash instead. A: Your scanf call is likely the problem: scanf("%s", &ch); You seem to want a single character, but you're reading a string. It'll put the first character in ch, but keep going from there and overwrite whatever's next on the stack. You should probably just use fgetc(stdin) or another function that reads a single character, if a single character is what you want. A: shouldn't it be struct Player *player = malloc(sizeof(struct Player)); A: Weird thing like that are usually caused by writing to unallocated memory. (Usually writing beyond the end of an array.) I didn't look at your code, but search for things like that. Then run your program under valgrind. A: At a first glance i can see you have done: scanf("%s", &ch); Which will use the address of ch to input a string, and therefore result in a buffer overflow. You need to do ch = getchar (); scanf ("%c", &ch); etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Action as a param, why isn't it possible here? What can I do solve this issue? Using Action as a param, why isn't it possible here? What can I do solve this issue? static void Main(string[] args) { while (true) { int eventsNum = 1000; var evt = new CountdownEvent(eventsNum); Stopwatch sw = new Stopwatch(); Action<Action> rawThreadTest = o => { new Thread(() => { o(); }).Start(); }; Action<Action> threadPoolTest = o => { new Thread(() => { o(); }).Start(); }; //Here I get ct error "The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly." CallTestMethod(eventsNum, "raw thread", evt, sw, rawThreadTest); CallTestMethod(eventsNum, "thread pool", evt, sw, threadPoolTest); Console.ReadKey(); } } private static void CallTestMethod<T>(int eventsNum, string threadType, CountdownEvent evt, Stopwatch sw, Action<Action> proc) { sw.Restart(); evt.Reset(); for (int i = 0; i < eventsNum; i++) { proc(() => { Thread.Sleep(100); evt.Signal(); }); } evt.Wait(); sw.Stop(); Console.WriteLine("Total for a {0} : {1}", threadType, sw.Elapsed); Console.WriteLine("Avg for a {0} : {1}", threadType, sw.ElapsedMilliseconds / eventsNum); } } A: CallTestMethod has a generic parameter T which you are not supplying a type argument for when you call it. However, it does not seem to be getting used anyway. A: You're going to feel foolish, but your CallTestMethod method signature has an unnecessary generic parameter - <T>. Take it out and you're good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get the images of epub book in android i was trying to read the epub book into my android application and succeed withe getting text into my app but not able to load images of epub book. actually what happen when we read the epub book using epub library (it extract/read the epub book and store somewhere in temporary the contents if it store than where the images of epub book is located ?). When i was try to read the image of book it give an error. when i read the content of book it return me HTML page containing the text and image path, but image path is relative like <img src='images/cover.jpg'> so where i get the images. Thanks in advance A: The path should be relative to the xhtml file within the archive. That is, if your xhtml file has an image <img src='image/cover.jpg'>, then your image file should be located in a subdirectory relative to the xhtml file called "image". The .opf file in the .epub is a manifest that should contain a reference to each file within the archive -- including any images. If the image is not referenced there, you might have an invalid epub. The idpf guys maintain an epub validation tool that you can download here: Google code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to combine these two javascript/jquery scripts I have an id #navigation li a and a class .menu-description . I want to change text color of the class .menu-description when hovered on #navigation li a My jquery so far: <script> $(document).ready(function() { $('#navigation li a').mouseover(function() { //Check if element with class exists, if so change it to new if ($('div.menu-description').length != 0) $('div.menu-description').removeClass('menu-description').addClass('menu-descriptionnew'); //Check if element with class 'menu-descriptionnew' exists, if so change it to 'menu-description' else if ($('div.menu-descriptionnew').length != 0) $('div.menu-descriptionnew').removeClass('menu-descriptionnew').addClass('menu-description'); }); }); </script> second script: <script> $(document).ready(function() { $('.menu-description').hover( function(){ $(this).css('color', '#EEEEEE'); }, function(){ $(this).css('color', '#000000'); }); }); </script> How to combine these to in order to reach for my wanted result? A: Why not just: $(document).ready(function() { $('#navigation li a').mouseover(function() { //Check if element with class exists, if so change it to new if ($('div.menu-description').length != 0) $('div.menu-description').removeClass('menu-description').addClass('menu-descriptionnew'); //Check if element with class 'menu-descriptionnew' exists, if so change it to 'menu-description' else if ($('div.menu-descriptionnew').length != 0) $('div.menu-descriptionnew').removeClass('menu-descriptionnew').addClass('menu-description'); }); $('.menu-description').hover( function(){ $(this).css('color', '#EEEEEE'); }, function(){ $(this).css('color', '#000000'); }); }); A: <script> $(document).ready(function() { $('#navigation li a').mouseover(function() { //Check if element with class exists, if so change it to new if ($('div.menu-description').length != 0) colorA(); //Check if element with class 'menu-descriptionnew' exists, if so change it to 'menu-description' else if ($('div.menu-descriptionnew').length != 0) $colorB(); }); }); function colorA() { $(this).css('color', '#EEEEEE'); } function colorB(){ $(this).css('color', '#000000'); } $('.menu-description').hover(colorA,colorB); );
{ "language": "en", "url": "https://stackoverflow.com/questions/7510724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL and Java driven application I am looking to make a Java based application that also uses an external MySQL database. Does anyone know of some good resources that I could read up on? I am very interested to give this a shot! Thanks in advance! A: MySQL provides a JDBC driver, so you can use pretty much any Java database tutorial to learn how to do it. You can also use all of the usual candidates for mapping DB resources to Java objects (Hibernate, EclipseLink, ...). A: The standard API to use databases from Java is JDBC. See the JDBC Tutorial to learn how to use it. You'll need a JDBC driver to connect to MySQL. You can get that at the MySQL website: Connector/J download.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling a php function with the help of a button or a click I have created a class named as "member" and inside the class I have a function named update(). Now I want to call this function when the user clicks 'UPDATE' button. I know I can do this by simply creating an "UPDATE.php" file. MY QUESTION IS :- Can I call the "update() function" directly without creating an extra file? I have already created an object of the same class. I just want to call the update function when the user clicks on update button. A: an action.php example: <? if (isset($_GET[update])){ $id=new myClass; $id::update($params); exit;} //rest of your code here ?> A: Your button is in your view. Your method is in your class . You need a controller sitting in the middle routing the requests. Whether you use 1 file or many files for your requests is up to you. But you'll need a PHP file sitting in the middle to capture the button click (a POST) and then call the method. A: As far as I know you can't do this without reloading your page, checking if some set parameters exist which indicate the button is clicked and than execute the button. If this is what you are looking for... yes it is possible on page reload. No as far as I know it is not possible directly because your php-function has to parse the results again. Remember that a Model-View-Controller way is better and that this will allow you to ajax (or regular) requests to the controller-class. A: You do it on the same page and have an if statement which checks for the button submission (not completely event driven) like so if (isset($_POST['btn_update'])) { update(); } <input type="submit" name="btn_update" value="Update" /> That will have to be wrapped in a form. Or you could do it with AJAX so that a full page refresh isn't necessary. Check out the jQuery website for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting Proxy Username & password using Objective-C - iPhone I'm testing an application in iPhone simulator where it actually makes an HTTP request using dataWithContentsOfURL: method of NSData. My mac has proxy settings protected with username & password. By default the simulator is not considering the proxy settings provided in my Mac. I'm getting the following response. Is there a way where we can programmatically provide the proxy username, password so that the simulator can read the values and allow the request to take place. Response: <HTML><HEAD> <TITLE>Access Denied</TITLE> </HEAD> <BODY> <FONT face="Helvetica"> <big><strong></strong></big><BR> </FONT> <blockquote> <TABLE border=0 cellPadding=1 width="80%"> <TR><TD> <FONT face="Helvetica"> <big>Access Denied (authentication_failed)</big> <BR> <BR> </FONT> </TD></TR> <TR><TD> <FONT face="Helvetica"> Your credentials could not be authenticated: "Credentials are missing.". You will not be permitted access until your credentials can be verified. </FONT> </TD></TR> <TR><TD> <FONT face="Helvetica"> This is typically caused by an incorrect username and/or password, but could also be caused by network problems. </FONT> </TD></TR> <TR><TD> <FONT face="Helvetica" SIZE=2> <BR> For assistance, contact your network support team. </FONT> </TD></TR> </TABLE> </blockquote> </FONT> </BODY></HTML> Thanks Sudheer A: -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ if ([challenge previousFailureCount] == 0) { NSURLCredential *newCredential; newCredential=[NSURLCredential credentialWithUser:@"ABC" password:@"ABC" persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; // inform the user that the user name and password // in the preferences are incorrect } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CRM 2011 outlook client: Some entities are not available after changing the user language Error: cannot load crm when trying to view crm records for contact/accounts in outlook 2010 EDIT: I found out that this problem occurred because of the selected language by the user. Now i still have to find out how to solve this problem so that the user can keep his language. Original question: A customer of our company recent did the migration from CRM 4.0 to CRM 2011. First everything worked perfect but after a few days, one of the crm users could not see the records for accounts and contacts in his outlook client. A few days later, another user noticed the same error. When they try to view the records for certain entities. No records are shown in de window. Only a message: "CRM cannot be loaded" (translated from dutch, i don't know the exact message in english). Other entity records are shown perfect. They tried already reinstalling the outlook client en reconfigureing there organisation in outlook. When i open their organistation in my outlook, everything works just fine. They are using outlook 2010 and me too. Any help would be very appreciated. Thanks! EDIT: When i login in outlook crm with his user, i have the same problem. So it's user specific problem. Both users have the system administrator role. A: Maybe there is some issues with the language used by the specific user? I earlier had a similar problem with an installation where English was used as base language - and the Norwegian language pack added later. Try to switch to English for the user who experiences these problems. If it helps you have a little translating to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails geocoder gem issues I am using the geocoder gem and I need to code a start and end address for a model, however I am not sure if I can accomplish this using this gem and if I can whether I am doing it correctly. If this cannot be done with the gem, is there another resource that will allow me to geocode two locations on the same form? This is an example of what I am trying to do, but it just passes the second address to be geocoded. geocoded_by :start_address before_validation :geocode geocoded_by :delivery_address, :latitude => :end_latitude, :longitude => :end_longitude before_validation :geocode A: If you look at the source it looks as though there's an options hash that would get overwritten active_record.rb and base.rb. I figure there are two options: move your addresses into an included (joined) model (like Address or something), or fork geocoder to have multiple options by key. The first one is easier, and solves the problem. The second one is cooler (might play with that myself as a kata). A: So what's going on is just simple ruby... if you do this: class Question def ask "what would you like?" end def ask "oh hai" end end Question.new.ask => "oh hai" The last method definition wins... so when you declare two geocoded_by methods, the 2nd is the one that counts. I think you're going to have to manually geocode, using the gem before_validation :custom_geocoding def custom_geocoding start_result = Geocoder.search(start_address) end_result = Geocoder.search(delivery_address) # manually assign lat/lng for each result end
{ "language": "en", "url": "https://stackoverflow.com/questions/7510734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I give parameters to a WIX setup from the setup's download link I'm trying to do the following : * *Suppose a user with username "annie" is connected to the foo.example.com website *On the website I give a link to download a msi setup (developped with WIX 3.5) *The setup installs a small program that will ask logon information upon first launch (server name : foo.example.com, username : annie, password). Since annie is already connected to the foo.example.com, it would be great if the server name and user name were alreay pre-filled. I know that for some remote-control software (NetViewer for example), you can send a mail invite to the person whose computer you want to control. In the mail you have a link containing the session number (for example : https://get.netviewer.com/support/join.php?sinr=502436783&sipw=nv64) wich prompts a download for the client software that upon launch will automatically have the session number automatically filled. I don't know how they do it, but I suppose you can easily append a few bytes (session number) at the end of the exe file, and then have the executable look for the extra trailing bytes, the difference here is that it's not an exe that I control completely but an MSI file developped with WIX. Do you have any pointers on how to do that ? A: A solution is a script which uses the Windows Installer database API to modify some custom properties in your MSI Property table. These properties can then be used by controls on a custom installation dialog. After modifying the MSI your script can serve it as a download link to the user. If your package uses a digital signature, your script will also need to resign the package after modification. There is no built-in support for this, so you will need to configure the package and write the script yourself. A: This is another way to do it, if you do not want your private key to lie on a download webserver : * *The link to download the msi file is dynamic (and aspx page for example) *This page creates a line in a central database that links "servername" + "username" to a unique identifier, say "connectid" *the page then Transmit the msi file but changes the name to something like "ourprocuct_connectid.msi" *The wix setup then stores the OriginalDatabase property in a registry value *Upon first launch the program check that registry value, if it exists, extracts the connectid, connects to a uniquer server that accesses the central database, and returns username and servername from the connectid Phew !
{ "language": "en", "url": "https://stackoverflow.com/questions/7510735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Colouring a hierarchical XamDataGrid I'm using a XamDataGrid (Infragistics-control) to display some hierarchical data. The objects that I can have up to 10 levels and I need to be able to give each level a specific background-color. I use the AssigningFieldLayoutToItem-event to get the "level" of the item and it would be best to assign the background/style here as well, I suppose. I have tried specifying a DataRecordCellArea-style and even a CellValuePresenter-style but I can't get any of these to work with the FieldLayouts. Another solution is to write a FieldLayout for each level, but this would create a lot of unnecessary XAML-code. Any suggestions as to what I should do? A: If you have a different FieldLayout for each level, you could use a single style targeting the DataRecordPresenter with a converter to set the background. XAML: <local:BackgroundConverter x:Key="BackgroundConverter"/> <Style TargetType="{x:Type igDP:DataRecordPresenter}"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=FieldLayout.Key, Converter={StaticResource BackgroundConverter}}"/> </Style> Converter: public class BackgroundConverter:IValueConverter { public BackgroundConverter() { this.Brushes = new Dictionary<string, Brush>(); } public Dictionary<string, Brush> Brushes {get;set;} public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is string) { string key = value.ToString(); if (this.Brushes.ContainsKey(key)) return this.Brushes[value.ToString()]; } return Binding.DoNothing; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } The following will set the colors to use for fields with Key1 and Key2: BackgroundConverter backgroundConverter = this.Resources["BackgroundConverter"] as BackgroundConverter; backgroundConverter.Brushes.Add("Key1", Brushes.Green); backgroundConverter.Brushes.Add("Key2", Brushes.Yellow); If you are reusing the same FieldLayout for multiple fields, then you could use the InitializeRecord event and change the style to bind to the Tag of the DataRecord like this: XAML: <Style TargetType="{x:Type igDP:DataRecordPresenter}"> <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Path=Record.Tag}"/> </Style> C#: void XamDataGrid1_InitializeRecord(object sender, Infragistics.Windows.DataPresenter.Events.InitializeRecordEventArgs e) { if (!e.ReInitialize) { // Set the tag to the desired brush. e.Record.Tag = Brushes.Blue; } } Note that I didn't add the conditional logic for determining the brush to use and that still needs to be done for different levels to have different backgrounds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using SWI-Prolog with Eclipse and Java (and JUNG): Should I use ProDT, PDT, or both? I want to use SWI-Prolog, Eclipse, and Java together and I have two interrelated related issues: * *I don't know if I should use ProDT, PDT or both in combination. *PDT says that it includes a "subsystem that enables Java code to interact with SWI-Prolog". I don't know if this is sufficient on its own, or if I should use InterProlog, JPL or some combination of the three. Background I want to interact with an existing java code base which uses JUNG for its datatypes, so a tidy fit to the java object heirarchy could be useful. (I want to apply constraints with JUNG objects such as trees and graphs as my domain--although I am willing to do this in a roundabout way if needed, i.e. by mapping the JUNG objects to data types more managable with SWI's available constraint modes.) I want to deploy to PC and MAC, and also want to try out the CHRrp package for SWI. A: I use jpl, it's quite easy to set up and use. But internet lot of trash tut so we may be confused. If you want that. here my note: Set enviroment variable: system variables ->add new ->JAVA_HOME (for jdk) add new -> SWI_HOME_DIR (installation prolog folder path) add this to Path: %SWI_HOME_DIR%\bin;%JAVA_HOME%; add jpl.jar to referenced in project Java eclipse
{ "language": "en", "url": "https://stackoverflow.com/questions/7510744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Stuck up with MessageList in Blackberry I am try to do MessageList in blackberry using midlet, but whatever I do some expection comes up. Right now am getting NullPointerException. Here is the code EncodedImage indicatorIcon = EncodedImage.getEncodedImageResource("img/indicator.png"); ApplicationIcon applicationIcon = new ApplicationIcon(indicatorIcon); ApplicationIndicatorRegistry.getInstance().register(applicationIcon, false, false); ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance(); MessageListStore messageStore = MessageListStore.getInstance(); if(reg.getApplicationFolder(INBOX_FOLDER_ID) == null) { ApplicationDescriptor daemonDescr = ApplicationDescriptor.currentApplicationDescriptor(); String APPLICATION_NAME = "TestAPP"; ApplicationDescriptor mainDescr = new ApplicationDescriptor(daemonDescr, APPLICATION_NAME, new String[] {}); ApplicationFolderIntegrationConfig inboxIntegration = new ApplicationFolderIntegrationConfig(true, true, mainDescr); ApplicationFolderIntegrationConfig deletedIntegration = new ApplicationFolderIntegrationConfig(false); ApplicationMessageFolder inbox = reg.registerFolder(MyApp.INBOX_FOLDER_ID, "Inbox", messageStore.getInboxMessages(), inboxIntegration); ApplicationMessageFolder deleted = reg.registerFolder(MyApp.DELETED_FOLDER_ID, "Deleted Messages", messageStore.getDeletedMessages(), deletedIntegration); messageStore.setFolders(inbox, deleted); } DemoMessage message = new DemoMessage(); String name = "John"; message.setSender(name); message.setSubject("Hello from " + name); message.setMessage("Hello Chris. This is " + name + ". How are you? Hope to see you at the conference!"); message.setReceivedTime(System.currentTimeMillis()); messageStore.addInboxMessage(message); messageStore.getInboxFolder().fireElementAdded(message); Can someone suggest me a simple MessageList sample for midlet to just show a String in MessageList and custom ApplicationIndicator value. If possible OnClick of message bring back the midlet from background. A: use the following code: static class OpenContextMenu extends ApplicationMenuItem { public OpenContextMenu( int order ) { super( order ); } public Object run( Object context ) { if( context instanceof NewMessage ) { try { NewMessage message = (NewMessage) context; if( message.isNew() ) { message.markRead(); ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance(); ApplicationMessageFolder folder = reg.getApplicationFolder( Mes sageList.INBOX_FOLDER_ID ); folder.fireElementUpdated( message, message ); //changeIndicator(-1); } Inbox inbox = message.getInbox(); Template template = inbox.getTemplate(); //Launch the mainscreen UiApplication.getUiApplication().requestForeground(); } catch (Exception ex) { Dialog.alert(); } } return context; } public String toString() { return "Name of the menu item"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby, deploying an exe with ocra that contains the TK GUI Ocra is unable to handle applications that require 'tk' require 'tk' puts 'nope' Packing this code with ocra http://github.com/larsch/ocra doesn't work (like mentioned in one of the issues at the link) Issue: https://github.com/larsch/ocra/issues/29 (Ocra is the 'new' rubyscript2exe for 1.9, essentially it's for deploying a rb script as an executable) The only problem seems to be the missing DLL files for tcl I don't think it's an issue AFAIK the problem are the missing DLL files for tk If they are known they can be included when executing ocra Is there a way to know the DLL dependecies required for tk to work? A: I didn't look on the issue tracker today... it is solved already (some hours ago), sorry. ocra rubyfile.rb --windows C:\Ruby192\lib\tcltk\ --no-autoload --add-all-core (--add-all-core is optional, don't include it if the exe works without it) --> https://github.com/larsch/ocra/issues/29
{ "language": "en", "url": "https://stackoverflow.com/questions/7510748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: tr:hover not working I'm trying to highlight (change background color) of the entire row when the mouse is hovering on a table row. I searched through the Net and it should be working, but it doesn't. I'm displaying it on Chrome. <table class="list1"> <tr> <td>1</td><td>a</td> </tr> <tr> <td>2</td><td>b</td> </tr> <tr> <td>3</td><td>c</td> </tr> </table> my css: .list1 tr:hover{ background-color:#fefefe; } The correct css should be: .list1 tr:hover td{ background-color:#fefefe; } //--this css for the td keeps overriding the one i showed earlier .list1 td{ background-color:#ccc000; } Thanks for the feedback guys! A: You need to use <!DOCTYPE html> for :hover to work with anything other than the <a> tag. Try adding that to the top of your HTML. A: try .list1 tr:hover td{ background-color:#fefefe; } A: tr:hover doesn't work in old browsers. You can use jQuery for this: .tr-hover { background-color:#fefefe; } $('.list1 tr').hover(function() { $(this).addClass('tr-hover'); },function() { $(this).removeClass('tr-hover'); }); A: Your best bet is to use table.YourClass tr:hover td { background-color: #FEFEFE; } Rows aren't fully support for background color but cells are, using the combination of :hover and the child element will yield the results you need. A: Works fine for me... The tr:hover should work. Probably it won't work because: * *The background color you have set is very light. You don't happen to use this on a white background, do you? *Your <td> tags are not closed properly. Please note that hovering a <tr> will not work in older browsers. A: Like @wesley says, you have not closed your first <td>. You opened it two times. <table class="list1"> <tr> <td>1</td><td>a</td> </tr> <tr> <td>2</td><td>b</td> </tr> <tr> <td>3</td><td>c</td> </tr> </table> CSS: .list1 tr:hover{ background-color:#fefefe; } There is no JavaScript needed, just complete your HTML code A: You can simply use background CSS property as follows: tr:hover{ background: #F1F1F2; } Working example A: Try it: css code: .list1 tr:hover td { background-color:#fefefe; } A: Use !important: .list1 tr:hover{ background:#fefefe !important; } A: Recently I had a similar problem, the problem was I was using background-color, use background: {anyColor} example: tr::hover td {background: red;} This works like charm! A: I had the same problem. I found that if I use a DOCTYPE like: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> it didn't work. But if I use: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> it did work. A: Also try thistr:hover td {color: aqua;} ` A: Also, it matters in which order the tags in your CSS file are styled. Make sure that your tr:nth-child and tr:hover td are described before table's td and th. Like so: #tblServers { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #tblServers tr:nth-child(even){background-color: #f2f2f2;} #tblServers tr:hover td{background-color: #c1c4c8;} #tblServers td, #tblServers th { border: 1px solid #ddd; padding: 8px; } #tblServers th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #4a536e; color: white; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "59" }
Q: How do Formtastic and simple_form compare? How do Formtastic and simple_form compare? What are the pros and cons of each? A: At the moment, simple_form with Twitter Bootstrap 3 is a pain. But it works very well with BS2. Formtastic and BS3 work very well through the formtastic-bootstrap gem: gem 'bootstrap-sass', '~> 3.0.3.0' gem 'formtastic-bootstrap', git: 'https://github.com/mjbellantoni/formtastic-bootstrap.git', branch: :bootstrap3_and_rails4 Unfortunately, Formtastic does not handle rails g scaffold; simple_form does. A: Formtastic and simple_form are very similar, the usage is also very similar. The main difference is that the markup of formtastic is fixed. Mind you: if you don't mind, it is fantastic. It is really awesome to get started with. Also it comes with a default css, so your forms will look good straight out of the box. The advantage of simple_form over formtastic is that you can modify the markup to your needs. This can be handy if your designer likes your fields to be grouped inside div instead of li. The downside of simple_form is that it doesn't come with any standard layout (css). That makes formtastic much easier to start off with. Because the API is nearly identical, if needed, you can very easily switch to simple_form if needed. [UPDATE 22-6-2015] Actually, currently simple-form supports bootstrap out of the box, so for me personally I always prefer simple-form now. [UPDATE 29-07-2014] simple_form added an option of being compatible with ZURB Foundation forms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: how to store image and its path in sql server 2005 using vb2010? we are doing a mini project on creating a photo viewer.we are using vb2010 as front end and microsoft sql server 2005 as backend;we were stuck up with reading and storing the picture and its path into the database! A: Download and Upload images from SQL Server via ASP.Net MVC
{ "language": "en", "url": "https://stackoverflow.com/questions/7510761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Downloading and playing videos in iphone through phonegap Is there any way to write an app in which we can download and play a video in our iphone using PhoneGap ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7510767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP regexp: matching everything until a word appears In PHP I'm looking to match everything until a certain word appears: $text = "String1 . testtesthephepString2 Here"; $faultyregexp = "#String1(.+)String2 Here#"; preg_match($text, $faultyregexp, $result); Now I want to match everything between String1 and String2, but for some reason this doesn't work. I'm thinking you could do something like #String1(^String2 here+)String2 here# if you know what I mean :) ? A: The issue is that by default . does not include newline characters. If you want . to match all character, you need to specify the s modifier (PCRE_DOTALL): /String1(.+)String2 Here/s
{ "language": "en", "url": "https://stackoverflow.com/questions/7510774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 2 ways to get the latest row from db I have a struts2 app with spring transactions and JPA2 over hibernate. The problem is that I have some rows in the database that are changed by an external source (some mysql triggers) and in my front app I have an ajax script that checks this values every 2 seconds. I always need to get the latest value, and not a cached one, and for this I found 2 solutions : String sql = "FROM MyEntity WHERE xId=:id AND connect!=0 AND complete=0 AND (error=NULL OR error=0)"; Query q = this.em.createQuery(sql).setHint("org.hibernate.cacheable", false).setParameter("agId", agentId); rs = q.getResultList(); if(rs.size() == 1){ intermedObj = (Intermed) rs.get(0); } and the other: String sql = "FROM MyEntity WHERE xxId=:id AND connect!=0 AND complete=0 AND (error=NULL OR error=0)"; Query q = this.em.createQuery(sql).setParameter("agId", agentId); rs = q.getResultList(); if(rs.size() == 1){ intermedObj = (Intermed) rs.get(0); //get latest object from DB em.refresh(intermedObj); } em is a instance of EntityManager which is managed by spring. So, the question is: which is the best approach from these 2? Or maybe there is a better one ? So you are right, I used hql there, I still have to learn a lot about hibernate an jpa, and java in general. So I guess that the correct way to write that cod in JPQL would be: String sql = "SELECT m FROM MyEntity m WHERE m.xxId=:id AND m.connect!=0 AND m.complete=0 AND (m.error!=1)"; Query q = this.em.createQuery(sql).setParameter("agId", agentId); rs = q.getResultList(); if(rs.size() == 1){ intermedObj = (Intermed) rs.get(0); //get latest object from DB em.refresh(intermedObj); } So the question would be, is this the proper way to make sure that I got the latest row from DB and not a cached record? As regarding leve2 cache question I do not know if this is activated. How do I check that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7510776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cakephp: login link not taking me to login page instead it is taking me to loginRedirect page My login link on register page is not taking me to login page. Instead it is taking me to report_card page which is the loginRedirect page. In beforeFilter i've set autoRedirect to false coz' i'm setting cookies in login function and then i'm setting $this->redirect($this->Auth->redirect()); Can someone please help me? thanks in advance. my code: register.ctp <?php echo $this->Html->link('Sign Up','/merry_parents/signup',array()).' for new user |'.$this->Html->link('Login','/merry_parents/login',array()).' for existing user'; ?> app_controller.php class AppController extends Controller { var $components=array('Auth','Session','Cookie'); function beforeFilter(){ if (isset($this->Auth)){ $this->Auth->userModel='MerryParent'; $this->Auth->loginAction=array('controller'=>'merry_parents','action'=>'login'); //var_dump($this->data); $this->Auth->loginRedirect=array('controller'=>'merry_parents','action'=>'report_card'); $this->Auth->allow('signup','login','logout','display'); $this->Auth->authorize='controller'; } else $this->Session->setFlash('Auth has not been set'); } function isAuthorized(){ return true; } merry_parents_controller.php <?php class MerryParentsController extends AppController{ var $name='MerryParents'; var $helpers=array('Html','Form'); function beforeFilter(){ $this->Auth->autoRedirect=false; parent::beforeFilter(); } function report_card(){ } function register(){ } function login(){ if ($this->Auth->user()){ if (!empty($this->data)){ $this->MerryParent->id=$this->MerryParent->field('id',array( 'MerryParent.username'=>$this->data['MerryParent']['username'], 'MerryParent.password'=>$this->data['MerryParent']['password'] ) ); echo 'id: '.$this->MerryParent->id; $this->Cookie->write('MerryParent.id',$this->MerryParent->id,false,0); $this->set('id',$this->Cookie->read('MerryParent.id')); } $this->redirect($this->Auth->redirect()); } } report_card.ctp <?php var_dump($this->data); echo 'HALLO'; if (isset($id)) echo $id; else echo 'id has not been set'; ?> A: Actually the problem was when I clicked on login link for the first time, login link displays fine. But, the next time i click on login link again, login page doesn't display, instead report_card page (ie. the login redirect page) displays. The reason is, i didn't have a logout button anywhere on my webpage, so the user was logged on all the time. Thanks. in register function of merry_parents_controller.php function register(){ $this->set('id',$this->Session->read('Auth.MerryParent.id')); } in register.ctp <?php if (isset($id)){ echo $this->Html->link('Logout', array('controller'=>'merry_parents','action'=>'logout'),array()); } else{ echo $this->Html->link('Sign Up','/merry_parents/signup',array()).' for new user |'. $this->Html->link('Login','/merry_parents/login',array()).' for existing user'; } ?> now, login and logout works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QR Code reader for android i am making a qr code reader, i came across zxing lib. i was able to successfully incorporate it on my project. however, when using the app i noticed that it requires another application (i.e qr droid app) before i can use it, otherwise the application crashes. is there a way that it won't require another app? or is there other lib that i can use? thanks in advance. in my code i just called the intent: Intent qr = new Intent("com.google.zxing.client.android.SCAN"); qr.putExtra("SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(qr, 0); A: First, it really requires the Barcode Scanner application. Not sure if that answers your question. Second your app crashes because you are not catching ActivityNotFoundException. In Barcode Scanners open source project ZXing, you will find a module android-integration which has complete correct source code for this integration. And you will find compete source for Barcode Scanner which you could use to build scanning into your own app. Otherwise you really do want to integrate with Barcode Scanner by Intent. It is much easier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use .NET Regex to express positive numbers with decimal How can use regular express to express the positive amount with most 20 digits in integral and 6 decimals, such as 0.25, 1234566789.123456? Thank you. A: var regexStr = @"^\d{1,20}(\.\d{1,6})?$"; var r = Regex.Match("15", regexStr); // match 15 r = Regex.Match("15.158", regexStr); // match 15.158 r = Regex.Match("-22.9", regexStr); // fail, negative r = Regex.Match("123456789012345678901.1234567", regexStr); // fail, too long r = Regex.Match("-123456789012345601.123456", regexStr); // fail, negative r = Regex.Match("123456789012345601.123456", regexStr); // match 123456789012345601.123456 A: try this: ^\d{1,20}(.\d{1,6})?$ A: Try this: (?<![-\d\.]) \d{1,20} (\.\d{1,6})? \b Test cases: 0.25, 1234566789.123456, 5.66, -12345678901234567890.1, 12345678901234567890.1, 5 A: There you go : @"^[0-9]{1,20}(\.[0-9]{1,6})?$"
{ "language": "en", "url": "https://stackoverflow.com/questions/7510795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Download Images from FTP in asp.net I have a list of images along with full path of FTP stored in my SQL SERVER. Now I want to download that images from the web page, Suppose I have search criteria after that 50 images shows in my grid then once i hit the download images all the images download into my local computer. Waiting for your valuable answers thanx A: You could perhaps use the FTPWebRquest library in the .NET framework Simple implementation can be found here A: General downloading code using the WebClient Class using System.Net; using (WebClient client = new WebClient()) { client.DownloadData("FTP_URL"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to build offline web applications in IE8? Is it really true that there is no way to support an offline web application using IE8? I wonder how people/companies are getting around this problem (no IE8 support for HTML5 offline features) if they absolutely need to use an IE browser (not IE10) and need to use it when no net connectivity exists. I realize there are plenty of rich client solutions but am curious about any lightweight solutions whereby IE8 would access something like applicationCache. Apparently Google Gears is no longer a solution for this problem. Any other third party solution people would recommend? Any suggestions would be helpful! Thanks. A: The only currently practical option is Chrome Frame, but this is almost equivalent to just installing a whole new browser. A: Perhaps I'm misunderstanding the concept of offline web app, but we routinely use HTML Applications (HTA) to create web apps that operate client-side, accessing the file system and local data stores, and automating local apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Rewrite url and preserve posted data I have a php server and i want to rewrite incoming urls. Since incoming requests are post requests I also want posted data to be transferred at the new urls. I have managed to redirect urls with the following rewrite rules: RewriteRule ^test/(.*)$ http: //localhost/index.php?data=&1 [NC,L] or RewriteRule ^test/(.*)$ http: //localhost/index.php?data=&1 [NC,R=301] I have also managed to preserve post data with the following rewrite rule: RewriteRule ^test/(.*)$ http: //localhost/index.php?data=&1 [P] The problem is that I can not both of them at the same time. What am I doing wrong? Is there a way to redirect url and keep post data? A: Your issue probably is that you do redirects instead of rewrites. Redirects change the URL people see in the browser. Rewrites only change the URL that your PHP app sees. The latter is normally what you want. And in the latter case POST variables are automatically preserved. In order to rewrite instead of redirect, use a local path instead of a URL: RewriteRule ^test/(.)$ index.php?data=$1 [NC,L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7510799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to save mechanize.Browser() cookies to file? How could I make Python's module mechanize (specifically mechanize.Browser()) to save its current cookies to a human-readable file? Also, how would I go about uploading that cookie to a web page with it? Thanks A: Deusdies,I just figured out a way with refrence to Mykola Kharechko's post #to save cookie >>>cookiefile=open('cookie','w') >>>cookiestr='' >>>for c in br._ua_handlers['_cookies'].cookiejar: >>> cookiestr+=c.name+'='+c.value+';' >>>cookiefile.write(cookiestr) #binding this cookie to another Browser >>>while len(cookiestr)!=0: >>> br1.set_cookie(cookiestr) >>> cookiestr=cookiestr[cookiestr.find(';')+1:] >>>cookiefile.close() A: If you want to use the cookie for a web request such as a GET or POST (which mechanize.Browser does not support), you can use the requests library and the cookies as follows import mechanize, requests br = mechanize.Browser() br.open (url) # assuming first form is a login form br.select_form (nr=0) br.form['login'] = login br.form['password'] = password br.submit() # if successful we have some cookies now cookies = br._ua_handlers['_cookies'].cookiejar # convert cookies into a dict usable by requests cookie_dict = {} for c in cookies: cookie_dict[c.name] = c.value # make a request r = requests.get(anotherUrl, cookies=cookie_dict) A: The CookieJar has several subclasses that can be used to save cookies to a file. For browser compatibility use MozillaCookieJar, for a simple human-readable format go with LWPCookieJar, just like this (an authentication via HTTP POST): import urllib import cookielib import mechanize params = {'login': 'mylogin', 'passwd': 'mypasswd'} data = urllib.urlencode(params) br = mechanize.Browser() cj = mechanize.LWPCookieJar("cookies.txt") br.set_cookiejar(cj) response = br.open("http://example.net/login", data) cj.save()
{ "language": "en", "url": "https://stackoverflow.com/questions/7510806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android tabs changing between activities I have an application with 3 tabs. I have made the xml files to describe the layout and it works perfectly. But I'm stuck at this point. My tabs are A B C. I want when I click on tab A, the tabs B C to be replaced by another tab D. Are there any solutions for this? <!-- language: java --> public class AndroidTabLayoutActivity extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TabHost tabHost = getTabHost(); TabHost tabHost2 = getTabHost(); // Tab for Photos TabSpec photospec = tabHost.newTabSpec("Photos"); photospec.setIndicator("Photos", getResources().getDrawable(R.drawable.icon_photos_tab)); Intent photosIntent = new Intent(this, LoginActivity.class); photospec.setContent(photosIntent); // Tab for Songs TabSpec songspec = tabHost.newTabSpec("Songs"); // setting Title and Icon for the Tab songspec.setIndicator("Songs", getResources().getDrawable(R.drawable.icon_songs_tab)); Intent songsIntent = new Intent(this, SettingsActivity.class); songspec.setContent(songsIntent); // Tab for Videos TabSpec videospec = tabHost.newTabSpec("Videos"); videospec.setIndicator("Videos", getResources().getDrawable(R.drawable.icon_videos_tab)); Intent videosIntent = new Intent(this, AboutActivity.class); videospec.setContent(videosIntent); // Adding all TabSpec to TabHost tabHost.addTab(photospec); // Adding photos tab tabHost.addTab(songspec); // Adding songs tab tabHost.addTab(videospec); // Adding videos tab } } <!-- language: xml --> <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout> </TabHost>
{ "language": "en", "url": "https://stackoverflow.com/questions/7510807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaScript: inline function vs. regular statements Once again I found JavaScript code on the Internet that contains an inline function where, in my opinion, regular statements would make just as much sense. Here's the first sample: function outerHTML(node){ // if IE, Chrome take the internal method otherwise build one return node.outerHTML || ( function(n) { var div = document.createElement('div'), h; div.appendChild(n.cloneNode(true)); h = div.innerHTML; div = null; return h; })(node); } If you'd ask me to code the same thing, it would look like this: function outerHTML(node){ var div, h; // if IE, Chrome take the internal method otherwise build one if (node.outerHTML) { return node.outerHTML; } div = document.createElement('div') div.appendChild(node.cloneNode(true)); h = div.innerHTML; div = null; return h; } EDIT: As OverZealous stated, there is a difference in logic on this one. I leave it here so nobody gets confused about that answer. And maybe another original sample (yes, this doesn't "compile" as it's just a code fragment): addGetters: function (attributes) { var that = this; function addGetter(attr) { that.prototype["get" + attr.capitalize()] = function() { return this[attr]; }; } for(var i = 0; i < attributes.length; i++) { var attr = attributes[i]; addGetter(attr); } }, compared to my attempt addGetters: function (attributes) { for(var i = 0; i < attributes.length; i++) { var attr = attributes[i]; this.prototype["get" + attr.capitalize()] = function() { return this[attr]; }; } }, Is there a difference? Doesn't the original version consume more space since a function needs to be created and/or isn't it slower because of this? Is there a possible memory leak? The utilisation of CPU and memory is very important as I'm coding in an environment where both are limited and any "less" is good. And since there's no sizeof() in JavaScript and its implementation attempts aren't safe to interpret any thinking-ahead-fixes are important. Please note that as far as the "my version" is concerned I didn't test it. I'm just trying to explain what I'm trying to ask. EDIT: Even though this question has an answer, I'm still wondering about the memory utilisation. If somebody has some insights, please don't hesitate to add it here. A: For the first one, I don't believe there is any reason for the function. It might have (d)evolved into that state through small changes, but the extra function wrapper isn't providing any benefit that I can see. The second example, however, is actually critical to use the function wrapper. The reason is due to JavaScript's (sometimes frustrating) function-level scope. In your example, there is only one attr variable. It is shared across the different attributes. This means that, in the end, every attribute will return the value of last attribute in the array. e.g: var attrs = ['foo', 'bar', 'baz'] obj.addGetters(attrs); obj.getFoo(); // returns obj.baz obj.getBar(); // returns obj.baz By wrapping the getter creation in a function, you eliminate that issue, because attr ends up being scoped to the creating function. This is why Douglas Crockford's JSLint says "Don't create a function inside a loop". It leads to unexpected bugs like that one. A: As OverZealous pointed out, one needs to be sure about the logic that's happening. +1 for that. As far as the performance is concerned I finally had the time to do some testing on my own. However, I'm working in an environment where I can't really check memory utilisation. So I tried to fool around with the performance. The result is that it may have an impact depending on how often this feature is used. On my target system the simple creation of an inline function that does close to nothing, e.g. myArray.each(function inlineFunc(el) { return el; }); takes about 1.8 seconds for 10,000 creations of such a function (in the example above myArray had no elements). Just in comparison the PC-version of that browser needs 1,000,000 iterations to get somewhere close to that (obviously this also depends on the hardware). Since the 10,000 iterations are reached in the code we use (not directly in one loop, but functions are created all over the code), we will have a word with our subcontractor. A: The answer lies in the eye of the beholder. It's a matter of preference. It's up to you if you put "speed" above modularity. Ask yourself this: why do you use a for when it can be done with a while? It is proven that in some cases the while structure is a bit faster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSOperationQueue Implemetation I have shown a UIAlertView with "Please Wait" text while loading some data to let the user to know that something is being processing now. So I hide the UIAlertView in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath Function as below So now what I need to know is am I handling the NSOperationQueue in a correct manner? or am I missing anything in using NSOperationQueue Here is my code. please let me know your thoughts. Thanks -(void)buttonPressed { alertLoading =[[UIAlertView alloc] initWithTitle:@"Loading Data" message:@"Please wait..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil]; av=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; [av startAnimating]; [av setFrame:CGRectMake(125, 70, 37, 37)]; //[self.view addSubview:alertLoading]; [alertLoading show]; [alertLoading addSubview:av]; [av release]; NSOperationQueue *queue = [NSOperationQueue new]; NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(parsing) object:nil]; [queue addOperation:operation]; [operation release]; [queue release]; } -(void)parsing { NSString *searchUrl = [NSString stringWithFormat:@"%@profile.php?type=list&logged_id=%@&start=%d& rows=%d",ConstantURL,Reg_UserId_Trim,row_index,per_page]; NSURL *xmlURL = [NSURL URLWithString:searchUrl]; NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; parserXML =[[XMLParser alloc]initXMLParser]; profileName = [[ProfileName alloc]init]; myProfileParser =[[MyProfileParser alloc]initMyProfileParser]; //set the Delegate [xmlParser setDelegate:parserXML]; BOOL success = [xmlParser parse]; if (success) { NSLog(@"Successfully Executed"); [myTableView reloadData]; } else { NSLog(@"Error is occured"); } [av stopAnimating]; [self performSelectorOnMainThread:@selector(loadPageDetails) withObject:nil waitUntilDone:NO]; [myTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { } [alertLoading dismissWithClickedButtonIndex:0 animated:YES]; return cell; } A: You can see this example which is good for NSOpeationQueue. And also this one. A: You should not release the NSOperationQueue immediately after its creation, but rather store a reference to it in your class and release it when your class is deallocated. Otherwise is possible that your operations won't be executed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show calculated values in NSTableView? I have an NSTableView that binds via an NSArrayController to an NSMutableArray of NSString's. There's also a TextView in the same window. What I want to do is display a number of occurrences of each NSString in the NSTableView. I've thought of a way to do this, but that doesn't look elegant way of doing this: Inherit from NSString and define new method that performs a search in predefined object (NSTextView) and returns the number of occurrences. I'm guessing there must be a more natural way of achieving the same result? EDIT: Sorry, should have clarified. NSSMutableArray is an array of NSObjects that have an NSString property. I suppose I could define an extra method (findAllOccurencesOfString:inString:) which would return a number. But the question is how do I bind to this function and in that binding how to I pass a var (pointer to textField)?? A: You'll need to have a wordCount (read only) property on whatever objects are in your table data source, this will have to call your new method internally using the object's own string value, as you can't pass parameters in bindings (unless they've changed, I haven't used bindings for a while as I've been concentrating on iOS). Then bind to this property for the column in the table. Presumably you don't need to pass the pointer to the textfield as there is only one?
{ "language": "en", "url": "https://stackoverflow.com/questions/7510819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fslex, binary file lexing Is there any ability to lexemize binary file formats (e.g. jpeg images) with Fslex (with no readability lacks) or i should write my own lexer/use something like fparsec?
{ "language": "en", "url": "https://stackoverflow.com/questions/7510820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How cairngorm framework works internally I had gone through many documents, no where mentioned how cairngorm framework works internally, means, how cairngorm Event, frontController, BusinessDelegate,ServiceLocator,Commands works and why we are extending or implementing cairngorm class like ICommand, IResponder and cairngormEvent. Thanks, Ravi A: For the love of GOD, don't use Cairngorm (2) as a framework. Use either RobotLegs or Parsley. Both of which has awesome documentation and a very active community.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I change a varchar constraint in SQL Server 2005 after I have defined my PK's and FK's? Can I change a varchar constraint in SQL Server 2005, after I have defined my PK's and FK's? varchar(10) ----> varchar (50) A: If the column in question is part of a foreign key constraint, then obviously not - the data types on both sides of the constraint must match exactly, and an ALTER TABLE statement can only affect a single table at a time. If this is just another column in a table that has a foreign key constraint, then yes, it can be altered. If the column is just part of a primary key or unique constraint, and is not referenced by a foreign key, it can be altered. It took me ~30 seconds to write this: create table T1 ( ID varchar(10) not null PRIMARY KEY, Val1 varchar(10) not null UNIQUE ) go insert into T1 (ID,Val1) values ('abc','def') go alter table T1 alter column Val1 varchar(50) not null go alter table T1 alter column ID varchar(50) not null It runs without errors. A: Where the column is involved in a foreign key, you will need to drop the FK constraint, change the data type, then recreated the foreign key. Very trivial, actually, especially if, before dropping constraints, you script them out using SSMS because changing the data type does not affect the FK constraint's definition; the issue is just that you can't change the data type while the constraint is in place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mod_rewrite error: [client 127.0.0.1] File does not exist I want to start using mod_rewrite so i can use friendly url's in the future. Im testing all in my localhost dev. environment but, Im not having any luck getting the module to work! My modules is enabled (apache restarted): LoadModule rewrite_module modules/mod_rewrite.so The file named mod_rewrite.so exists under the modules folder in my Apache installation directory I've created a file named .htaccess under c:/public_html/ For testing purposes, ive created my first rules like so: RewriteEngine On # Translate my-product.html to /product.php?id=123 RewriteRule ^my-product\.html$ /product.php?id=123 for testing purposes, the product.php is extremely simple: <?php // display product details echo 'You have selected product #' . $_GET['id']; ?> When i load http://localhost/my-product.html I get the error: The requested URL /my-product.html was not found on this server. When i go see the log, i see: [Thu Sep 22 02:37:49 2011] [error] [client 127.0.0.1] File does not exist: C:/public_html/my-product.html It looks like it doesn't recognize the .htaccess rule at all! I'm not sure what to do next, i feel i've applied all the simpliest rules to get started with mod_rewrite but with no luck! Help! Thanks Marco A: Have you changed the Allowoverride property in httpd.conf file to 'All'. To check whether the mod-rewrite is enabled in your server, load the phpinfo file and search for the mod_rewrite extension. A: You should configure the mod_rewrite logging, so you can see what happens. Look up the RewriteLog directive in the manual. Initially you can set the log level to 9 (for learning). As long as the file stays empty, the .htaccess is ignored, as you already suspected. You can also just write rubbish into the .htaccess to see if it gets interpreted at all. If it does, you will get a 500 Internal Server Error. If not, you must configure the directory C:/public_html to allow htaccess files. See the Options directive in the manual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How cairngorm suites for Flex 4.5 mobile application Can cairngorm framework suites for developing mobile application using flex 4.5 ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7510831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is window.Close() not working in Firefox? Why javascript: window.Close() is not working in Firefox, Is there any solution? What are the parameters in window.Close()? A: In firefox you can't close a window that is not opened by javascript(pop-up). window.close() will not work. A: Probably because it is window.close() - with a lower-case c. JavaScript is a case-sensitive language, close and Close are not the same thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loading methods of a specific class from a C++ library using JNI I have a C++ library xyz. It has many classes like xyzA, xyzB etc. I want to use the method getAge() from the class xyzA which is in the xyz library. The xyz.so file already exists. Steps I have followed: * *Created a Java class xyz.java class xyz { public native int getAge(); public static void main(String[] args) { new xyz().getAge(); } static { System.loadLibrary("xyz"); } } *Created the header for the Java class. /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class xyz */ #ifndef _Included_xyz #define _Included_xyz #ifdef __cplusplus extern "C" { #endif /* * Class: xyz * Method: getAge * Signature: ()I */ JNIEXPORT jint JNICALL Java_xyz_getAge (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif *The cpp wrapper class looks like: #include <stdio.h> #include "xyz.h" #include <jni.h> JNIEXPORT jint JNICALL Java_xyz_getAge(JNIEnv *, jobject) { // some code } *I successfully compile the class as follows: gcc -fPIC -shared -l stdc++ -I/grid/0/gs/java/jdk64/current/include -I/grid/0/gs/java/jdk64/current/include/linux xyz.cpp *Then run the Java prog as: java -Djava.library.path=/grid/0/tmp/direct/lib xyz I get the following error: Exception in thread "main" java.lang.UnsatisfiedLinkError: xyz.getAge()I at xyz.getAge(Native Method) at xyz.main(xyz.java:6) It cannot find the method getAge() specific to the class xyzA. How can that method be accessed? Also, is the library getting linked through my wrapper class? Any pointers would be appreciated. Thanks. A: If you are running on Unix, the shared library has to be named libxyz.so, not xyz.so. A: Exported function names in C++ libraries are mangled: The plain function name is decorated with class and namespace names, parameter and return types. For instance, here is one of the methods from a boost library: ?estimate_max_state_count@?$perl_matcher@PB_WV?$alloca tor@U?$sub_match@PB_W@boost@@@std@@U?$regex_traits@_WV?$w32_regex_traits@_W@boos t@@@boost@@@re_detail@boost@@AAEXPAUrandom_access_iterator_tag@std@@@Z The format of the name is not standardised and varies from compiler to compiler. The end result is that it is difficult to call an exported C++ member function unless you're writing another module in C++ and compiling it using the same compiler. Trying to call from Java is more trouble than it is worth. Instead, if the C++ library is yours, export helper functions using the extern "C" calling convention: Foo * foo; extern "C" { void myfunc() { foo->bar(); // Call C++ function within a C-style function. } } If the library is third-party, you should wrap it with your own library which exposes necessary functions using the C-style export, as per above. A: This error normally means that the library has been successfully loaded, but that there is an inconsistency in the signature of the function. Globally, your code looks correct, but we do put an extern "C" in front of JNIEXPORT in our code base. We don't use the generated headers, so the definition of the function is the only place we could specify extern "C". In your case, I think that the compiler is supposed to recognize that the function declared in the header and the one defined in your .cpp are the same, and define the function as extern "C", but having never done it this way, I'm not 100% sure. You can verify by doing something like: nm -C libxyz.so | egrep getAge The function should appear as a C function, with a T in the second column; without the -C, it should appear unmangled. Note that the slightest difference in the definition and the declaration will mean that you're defining a different function; I don't see one in the code you've posted, but it's worth double checking. (I'd also wrap the call to LoadLibrary in a try block, just to be sure.) EDITED to add some additional information: I'm not sure when and how Linux links the additional libraries needed; we've always loaded all of our libraries explicitly. You might try adding a call to dlopen in either JNI_OnLoad or the constructor of a static object. (I would recommend this anyway, in order to control the arguments to dlopen. We found that when loading several different .so, RTTI didn't work accross library boundaries if we didn't.) I would expect not doing so to result in a loader error, but it all depends on when Linux tries to load libxyz.so; if it only does so when the JVM calls dlsym, then you'll get the above error. (I think this depends on the arguments the JVM passes to dlopen when you call java.lang.System.LoadLibrary: if it passes RTLD_LAZY or RTLD_NOW. By forcing the load in JNI_OnLoad or the constructor of a static object, you more or less guarantee that loader errors appear as loader errors, and not link errors, later.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7510840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Failed to call IResourceEventListener.resourceChangeEventEnd java.lang.StackOverflowError when I start eclipse ide.. An exception comes Failed to call IResourceEventListener.resourceChangeEventEnd java.lang.StackOverflowError How to resolve it.. Can anyone help me thanks A: It's quite old question, but maybe it will be useful for someone. In my case, this error was caused by importing R file from library project. Some class from library project B was moved to project A(which uses B), but it still had import from previous package package com.something.projectA import com.something.projectB.R Solution: Use proper R for project
{ "language": "en", "url": "https://stackoverflow.com/questions/7510843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: GET HTTPs request not working properly in phonegap I'm running this app in an Android phone (Samsung Galaxy mini running on ANdroid 2.2). I'm using couchdb for my database and host it on cloudant. On device ready, the app will make a get request to the https db server which contains feeds of data that i need to be displayed in my app. At first, it was working fine but when i try to post and add new data to my https db server, then trigger the get request method, the returned response from the server is still the same as before(the newly posted data was not included even though i checked my db server and saw that it was indeed saved). Then i tried to close and reopen the app again, which will then make a new instance of the get http request, but still, the response still is the same as the very first one and doesnt contain the new data that was added to the db server. Then, I tried to reinstall my app, then run the app again, and oddly enough, the response from the get request now contains the new data.. I don't know how that happens, and I'm not really experienced with REST api and javascript so I might be doing something obviously wrong. Here's a snippet of my code for the get request: var getFeedsClient; document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { if (window.XMLHttpRequest) { getFeedsClient=new XMLHttpRequest(); } else { getFeedsClient=new ActiveXObject("Microsoft.XMLHTTP"); } try{ getFeedsRequest(); } catch(e) { alert("Error on device ready: "+e); } }//on Device Ready function getFeedsRequest() { getFeedsClient.onreadystatechange = getFeedsFunction; getFeedsClient.open("GET","https://<username>.cloudant.com/te/_design/requestfeed/_view/all",true); getFeedsClient.send(); } function getFeedsFunction() { alert(" readystate: "+getFeedsClient.readyState+", status: "+getFeedsClient.status); if(getFeedsClient.readyState == 4 && getFeedsClient.status == 200 ) { var data = JSON.parse(getFeedsClient.responseText); console.log("RESPONSE FROM COUCHDB "+getFeedsClient.responseText); console.log("JSON data "+data); //at first the total rows is 2 but when a new data was added, the total rows should be three, but that was not the case alert("rows: "+data.total_rows); } } A: I ran into a similar issue last week of the device caching requests. I solved it by adding a dummy unique parameter to the link like below: function getFeedsRequest() { getFeedsClient.onreadystatechange = getFeedsFunction; var link = "https://<username>.cloudant.com/te/_design/requestfeed/_view/all"; var unique = (new Date).getTime(); getFeedsClient.open("GET",link + '?' + unique,true); getFeedsClient.send(); } A: Paul Beusterien's solution below worked for me with the following caveat: An android 4.0.4. phone did not need a unique URL, but the same code running on 2.2.2 did!
{ "language": "en", "url": "https://stackoverflow.com/questions/7510844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to write this javascript without using apostrophes I'm trying to get a line of flags wiht google translate on my site. This other site already has it, but it uses blogger API. I changed the JS accordingly, but I found out that my forum software encodes de apostrophe as \' Is there any way I can write the same html+js below without using apostrophes? <a target="_blank" rel="nofollow" onclick="window.open('http://www.google.com/translate?u='+encodeURIComponent(document.URL)+'&langpair=pt%7Czh-CN&hl=pt&ie=UTF8'); return false;" title="Google-Translate-Chinese (Simplified) BETA"><img style="border: 0px solid ; cursor: pointer; width: 24px; height: 24px;" alt="Google-Translate-Chinese" src="http://lh5.ggpht.com/_mcq01yDJ2uY/Sdke4C8za2I/AAAAAAAAAkU/Mpfn_ntCweU/China.png" title="Google-Translate-Chinese"> As it is, the forum engine translates it as ""window.open(\'http://www.google.com/translate?u=\'+" A: Try using something like this onclick="window.open(\"http://www.google.com/translate?u=\"+encodeURIComponent (document.URL)+\"&langpair=pt%7Czh-CN&hl=pt&ie=UTF8\"); return false;" Since you are already using escape string, your forum engine might not replace this with another '\'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which message queue can handle private queues that survive subscriber disconnects? I have some requirements for a system in need of a message queue: * *The subscribers shall get individual queues. *The individual queues shall NOT be deleted when the subscriber disconnects *The subscriber shall be able to reconnect to its own queue if it looses connection *Only the subscriber shall be able to use the queue assigned to it *Nice to have: the queues survive a server restart Can RabbitMQ be used to implement this, and in that case how? A: I have only recently started using Rabbit but I believe your requirements can be addressed fairly easily. 1) I have implemented specific queues for individual subscribers by having the subscriber declare the queue (and related routing key) using its machine name as part of the queue name. The exchange takes care of routing messages appropriately by way of the binding/routing keys. In my case, all subscribers get a copy of the same message posted by the publisher and an arbitrary number of subscribers can declare their own queues and start receiving messages. 2) That's pretty much standard. If you declare a queue then it will remain in the exchange, and if it is set as durable then it will survive broker restarts. In any case, your subscriber should call queue.Declare() at startup to ensure that the queue exists but in terms of the subscriber disconnecting, the queue will remain. 3) If the queue is there and a subscriber is listening to that queue by name then there's no reason why it shouldn't be able to reconnect. 4) I haven't really delved in to the security aspects of Rabbit yet. There may be a means of securing individual queues though I'll let someone else comment on this as I'm no authority. 5) See (2). Messages will also survive a restart if set as durable as they are then written to disk. This incurs a performance penalty as there's disk I/O but that's kind of what you'd expect. So basically, yes. Rabbit can do as you ask. In terms of 'how', there are varying degrees of 'how'. Will happily try to provide you with code-level answers should you have trouble implementing any of the above. In the meantime, and if you haven't already done so, I suggest reading through the docs: http://www.rabbitmq.com/documentation.html HTH. Steve
{ "language": "en", "url": "https://stackoverflow.com/questions/7510848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: django how to display users full name in FilteredSelectMultiple i am trying to use FilteredSelectMultiple widget to display list of users. currently it is displaying only username. I have tried to override the label_from_instance as seen below but it does not seem to work. how can it get to display users full name. class UserMultipleChoiceField(FilteredSelectMultiple): """ Custom multiple select Feild with full name """ def label_from_instance(self, obj): return "%s" % (obj.get_full_name()) class TicketForm(forms.Form): cc_to = forms.ModelMultipleChoiceField(queryset=User.objects.filter(is_active=True).order_by('username'), widget=UserMultipleChoiceField("CC TO", is_stacked=True) A: (For future reference) You should subclass ModelMultipleChoiceField instead: class UserMultipleChoiceField(forms.ModelMultipleChoiceField): """ Custom multiple select Feild with full name """ def label_from_instance(self, obj): return obj.get_full_name() class TicketForm(forms.Form): cc_to = UserMultipleChoiceField( queryset=User.objects.filter(is_active=True).order_by('username'), widget=FilteredSelectMultiple("CC TO", is_stacked=True) ) Another solution is to subclass User and use it in your query set (as in this question: Django show get_full_name() instead or username in model form) class UserFullName(User): class Meta: proxy = True ordering = ["username"] def __unicode__(self): return self.get_full_name() class TicketForm(forms.Form): cc_to = forms.ModelMultipleChoiceField( queryset=UserFullName.objects.filter(is_active=True), widget=FilteredSelectMultiple("CC TO", is_stacked=True) ) A: A little late, but I think it might help people trying to solve a similar problem: http://djangosnippets.org/snippets/1642/ A: The simplest solution is to put the following in a models.py where django.contrib.auth.models.User is imported: def user_unicode_patch(self): return '%s %s' % (self.first_name, self.last_name) User.__unicode__ = user_unicode_patch This will overwrite the User model's __unicode__() method with a custom function that displays whatever you want. A: I think you have to override User model unicode method. You can create new model, like this: class ExtendedUser(User): # inherits from django.contrib.auth.models.User def __unicode__(self): return '%s %s' % (self.first_name, self.last_name) A: I made the same as jnns and also override the _meta ordering list, to order users list by their user full name. # hack for displaying user's full name instead of username and order them by full name def user_unicode_patch(self): return '%s %s' % (self.first_name, self.last_name) User.__unicode__ = user_unicode_patch User._meta.ordering = ['first_name', 'last_name'] I've added this at the UserProfile model file. I don't thing this is the best way of doing that, but for sure is very easy and practical. Tested in Django 1.4 For Django 1.5 after, it will be easier to do that, since we'll have more control of the User model. A: let's say your models are class UserProfile(models.Model) : first_name = models.CharField(max_length=255, blank=True) second_name = models.CharField(max_length=255, blank=True) def full_name(self): """ : Return the first_name plus the last_name, with space in between. """ full_name = '%s %s' % (self.first_name, self.second_name) return full_name.strip()
{ "language": "en", "url": "https://stackoverflow.com/questions/7510849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: CSS direct descendant ">" operator not working (and it's not IE6)? I am trying to do something very simple - select the tags which are direct descendants of a tag. The CSS I am using is as follows: table.data > tr { background-color: red; } My HTML looks like this: <table class="data"> <tr> ... </tr> </table> But no red background is forthcoming! If I remove the ">" character from the CSS, it works! I have tried this in Firefox, IE 8, Chrome and Safari, and all the browsers do exactly the same thing. Hopefully someone can help me after so many frustrating hours! I know I am doing something extremely stupid, but I can't figure out what it is. A: Most1 browsers automatically insert a tbody element into a table, so the css should be: table.data > tbody > tr { background-color: red; } to account for that. 1 I think that all browsers do this, but I don't have the capacity, or time, to check that assumption. If you're concerned that there might be some users with a browser that doesn't do this, you could offer both selectors in the css: table.data > tr, table.data > tbody > tr { background-color: red; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: PHP join three tables when if the data is not in one of them I am working on joining three tables together, but in one of the tables no information will be in there, unless the user opens the email we sent them I am currently using this sql but it seems not to work correctly SELECT email.senton, customer.*, count(tracker.viewed) as viewed FROM email_sent AS email, customer_detail AS customer, email_tracker AS tracker WHERE email.customer_id = customer.customer_id AND customer.Email = tracker.emailaddress AND customer.LeadOwnerId = '{$this->userid}' This is due to the table email_tracker may not have the customers info in it, unless the customer has opened the email A: Try this: SELECT email.senton, customer.*, COUNT(tracker.viewed) as viewed FROM email_sent email INNER JOIN customer_detail customer ON email.customer_id = customer.customer_id LEFT JOIN email_tracker tracker ON customer.Email = tracker.emailaddress WHERE customer.LeadOwnerId = '{$this->userid}' The LEFT JOIN clause is used to always get columns on the left part and columns on the right part if they exist in the join... EDITED according to your comment: Try to change COUNT(tracker.viewed) part with CASE WHEN tracker.emailaddress IS NOT NULL THEN COUNT(tracker.viewed) ELSE 0 END as viewed I'm not sure it works, I cannot test it, but give it a try A: The behavior that you want is the LEFT OUTER JOIN (also known as LEFT JOIN). It just set's the value to NULL if the row doesn't exist in the other table. SELECT email.senton, customer.*, COUNT(tracker.viewed) AS viewed FROM email_sent AS email JOIN customer_detail AS customer USING(customer_id) LEFT OUTER JOIN email_tracker AS tracker ON customer.Email = tracker.emailaddress WHERE customer.LeadOwnerId = '{$this->userid}' PS: It's generally a better idea to use JOINs instead of a Cartesian product (what you did with ,).
{ "language": "en", "url": "https://stackoverflow.com/questions/7510851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Play back Rational Functional Tester How to play back Rational Functional Tester 8.1 without IDE instead use command prompt please provide the command A: Do a search for "command line" at the following link: http://publib.boulder.ibm.com/infocenter/rfthelp/v8r1/index.jsp You'll get a full page of info. A: java -classpath "Path for rational_ft.jar" com.rational.ft.test.rational_ft -datastore "projectfilePath" -compile "scriptName" java -classpath "Path for rational_ft.jar" com.rational.ft.test.rational_ft -datastore "projectfilePath" -playback "scriptName" A: java -classpath "%IBM_RATIONAL_RFT_INSTALL_DIR%\rational_ft.jar" com.rational.test.ft.rational_ft -datastore C:\Users\username\IBM\rationalsdp\workspace\Project1 -playback Script1 -log Script1
{ "language": "en", "url": "https://stackoverflow.com/questions/7510854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Smarty accessing array {foreach from=$ncache.recmd name=spon key=k item=v} {if ($smarty.foreach.spon.iteration%2) eq 0 || $smarty.foreach.spon.last} <tr> <td> <label> <input type="checkbox" name="iid[]" value="{$ncache.recmd[$k].item_id}"class="checkbox"/{$ncache.recmd[$k].model}{$ncache.recmd[$k].manufacturer} </label> </td> <td> <label> <input type="checkbox" name="iid[]" value="{$ncache.recmd[($k+1)].item_id}" class="checkbox"/>{$ncache.recmd[($k+1)].model}{$ncache.recmd[($k+1)].manufacturer} </label> </td> </tr> {/if} {/foreach} here is my smarty codes. {$ncache.recmd[($k+1)].item_id} {$ncache.recmd[$k+1].item_id} {$ncache.recmd[$k++].item_id} i tried to access to value but result is invalid i tried several form as above. but it still got problem. A: Your question isn't clear, but I think I see what you are trying to do. I don't know what version of Smarty you're using, but I had similar difficulty with Smarty v2. I found that $smarty.foreach..iteration was going to be the next index (1-based indexing instead of 0-based). In that case, try this: {foreach from=$ncache.recmd name=spon key=k item=v} {if ($smarty.foreach.spon.index % 2) eq 0 || $smarty.foreach.spon.last} <tr> <td> <label> <input type="checkbox" name="iid[]" value="{$ncache.recmd[$k].item_id}"class="checkbox"/{$ncache.recmd[$k].model}{$ncache.recmd[$k].manufacturer} </label> </td> <td> <label> <input type="checkbox" name="iid[]" value="{$ncache.recmd[$smarty.foreach.spon.iteration].item_id}" class="checkbox"/>{$ncache.recmd[$smarty.foreach.spon.iteration].model}{$ncache.recmd[$smarty.foreach.spon.iteration].manufacturer} </label> </td> </tr> {/if} {/foreach}
{ "language": "en", "url": "https://stackoverflow.com/questions/7510863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: GDB+Python: Determining target type Is there a way to determine whether the debugged target is a core dump or a 'live' process? A: As far as I know, there is no dedicated way to do it in Python, however, you can still use * *gdb.execute("<command>", to_string=<boolean>) to execute a "CLI" command in Python, where to_string being True will tell GDB to collect the output and return it as a string (cf. doc) *maint print target-stack which will print the layers used internally to access the inferior. You should see "core (Local core dump file)" if the core-debugging layer is active. So all-in-all, a bit of code like out = gdb.execute("maint print target-stack", to_string=True) print "Local core dump file" in out should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Click a button and it should load the content into the main content area I have create 3 buttons on the left menu for "Cars," "Music," and "Games" When the user clicks one, it should load the appropriate contents into a DIV in the main content area. Each button should replace the contents of anything previously displayed in the div. I created my buttons, but I do not know how to load the content into the main content div or how to replace the previous content. Can you help please? A: Use jquery load function A: <!DOCTYPE HTML> <html> <head> <title>Title of the document</title> <script src="../js/jquery.js"></script> <script> function load(url){ $('#content').load(url); } </script> </head> <body> <button onclick='load("url1");'>Content 1</button> <button onclick='load("url2");'>Content 2</button> <div id='content'></div> </body> UPDATE Ok lets clarify it a bit. The code above uses jQuery lib. Look here for more info about load function. If you cannot or dont want to use jQuery look here for JS solution. If you want to use only static content then you have two another options: //1: if the new content is only small portion of info text <script> function load(newContent){ document.getElementById('content').innerHTML = newContent; } </script> <button onclick='load("some text 1");'>Content1</button> <button onclick='load("another text 2");'>Content2</button> <div id='content'></div> //2: put content directly to your page the several DIVs and hide them <script> function show(index){ var n=2; // number of DIVs //show desired content and hide any others for(var i=1; i<=n; i++){ document.getElementById('content'+i).style.display = i == index ? 'block' : 'none'; } } </script> <button onclick='show(1);'>Content 1</button> <button onclick='show(2);'>Content 2</button> <div id='content1'></div> <div id='content2' style='display:none;'></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7510866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call an activity from ListView Adapter? I have custom ListView,my ListView contains one button, if we click on button i want to go another activity with some data.I used following code, holder.mMore.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == event.ACTION_DOWN){ Intent moreIntent=new Intent(getContext(),SelectItemDesp.class); v.getContext().startActivity(moreIntent); } return false; } }); it is showing error.pls help me A: I'll assume that you have written a class for your ListView adapter. Let's just name this class quickly: MyListViewAdapter. And in this class you most probably have a constructor. It could look like this: public MyListViewAdapter (Context context, ArrayList<String> myList) { super (context, R.layout.my_layout, R.id.my_text_view, myList); Now the context is what you need to start a new Activity because a ListView adapter which extends an ArrayAdapter cannot start an Activity because its not derived from the Activity-class. So this is how you start an Activity then: context.startActivity(context, GoToClass.class); Just make sure to add a global but private variable to your code (private Context context) and add this to your constructor this.context = context and if you create the object you have to put MyListViewAdapter m = new MyListViewAdapter(CurrentClass.this, myListFullOfStrings); A: Replace Intent moreIntent=new Intent(getContext(),SelectItemDesp.class); v.getContext().startActivity(moreIntent); With Intent lObjIntent = new Intent(getApplicationContext(), SelectItemDesp.class); startActivity(lObjIntent); finish(); A: I am also using customlistview and also have one delete button in that listview and i have done something like below and it work for me.and one thing my class extends ArrayAdapter public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.row_layout_mymedicine, null); holder.btnDelete = (Button)convertView.findViewById(R.id.btnDelete); holder.btnDelete.setOnClickListener(this); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } return convertView; } then onClick() method i have do public void onClick(View v) { switch(v.getId()) { case R.id.btnDelete: getContext().startActivity(new Intent(getContext(),DeleteActivity.class)); break; default: break; } } A: You're invoking the new activity from an anonymous inner class, anything like this would refer to this anonymous class only. Use MyClass.this as Vinayak suggested and if error persists, post the logcat here A: Try This. It should Work Intent intent = new Intent(context, SelectItemDesp.class); context.startActivity(intent);
{ "language": "en", "url": "https://stackoverflow.com/questions/7510868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Coldfusion - Subdirectory file not displaying Recently set up a new ColdFusion8 server instance on a Win2K8/R2 / IIS7.5 / CF8 Enterprise Hostgator dedicated server and everything seemed to be working, until I browsed to a subdirectory: http://www.quirkup.com/myQuirkup/ There is an index.cfm in that subdirectory. IIS permits .cfm files. Yet, the index.cfm does not display. I don't get any error, just a blank page, with absolutely nothing in the source. Can anyone shed light on this? A: Is IIS set-up to server index.cfm as a default document in that sub-dir? Is anything being logged in the IIS logs, the CF logs or the JRun logs? Browsing to http://www.quirkup.com/myQuirkup/foo.cfm (ie: an invalid file name), I am getting a CF 404 error, which does seem like IIS is passing requests to CF, which is a start. Can you replace whatever the code of index.cfm is with this: <cfset message = "Hello World"> <cfoutput>#message#</cfoutput> And see if that runs. Do you have an Application.cfc or .cfm in that dir or any ancestor dir that could be interfering? To verify that there isn't one, put an Application.cfm in that sub-dir with nothing in it (just whilst troubleshooting).
{ "language": "en", "url": "https://stackoverflow.com/questions/7510870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save all cookies from first page in text file on hard disk I need to save all cookies from first page in text file on hard disk. How to do this with javascript? A: For security reasons you cannot use javascript to read/write files on the client computer. You can read/write cookies which could be persistent and if they are persistent they are actually stored by the browser on the client computer but the way and location this is done is out of your control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access external objects in Jersey Resource class I have the scenario where I have the following embedded jetty server: Server server = new Server(8080); Context root = new Context(server, "/", Context.SESSIONS); root.addServlet( new ServletHolder( new ServletContainer( new PackagesResourceConfig( "edu.mit.senseable.livesingapore.platform.restws.representations"))), "/"); Myobj myobj = new Myobj(12,13); server.start(); and have the following resource class (using Jersey framework) import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/") public class DataStreams { @GET @Path("/datastreams") @Produces(MediaType.TEXT_PLAIN) public String getDataStreams() { return getStreams("text"); } } Here in my resource class I want to access a object "myobj" . can someone suggest how I can access it? because the resource class in directly called by the framework. [edit] Basically I want to know how to inject any object into resource class? [Edit] I tried this: pkgrc.getSingletons().add( new SingletonTypeInjectableProvider<Annotation, InjectZk>( InjectZk.class, new InjectZk(this.zooKeeper)) { }); following is the provider class @Provider public class InjectZk { private ZooKeeper zk; public InjectZk() { // TODO Auto-generated constructor stub } public InjectZk(ZooKeeper zk) { // TODO Auto-generated constructor stub this.zk = zk; } public ZooKeeper getZk() { return zk; } } and I am using it in resource class as: @Context InjectZk zk; I am getting the following erorr while running the server: SEVERE: Missing dependency for field: edu.mit.senseable.livesingapore.platform.core.components.clientrequest.InjectZk edu.mit.senseable.livesingapore.platform.core.components.clientrequest.DataStreams.zk 2011-09-28 16:18:47.714:/:WARN: unavailable com.sun.jersey.spi.inject.Errors$ErrorMessagesException Any suggestions? ( BTW I am using Embedded jetty) A: You can inject things by writing your own InjectableProvider and Injectable implementations and registering them as providers in your application. For an example of how such provider can be implemented you can check the SingletonTypeInjectableProvider or PerRequestTypeInjectableProvider which are helper classes you can use to implement that and OAuthProviderInjectionProvider for an example of a concrete implementation of a singleton type provider. sample code: Server server = new Server(8080); Context root = new Context(server,"/",Context.SESSIONS); ResourceConfig rc = new PackagesResourceConfig("edu.mit.senseable.livesingapore.platform.restws.representations"); rc.getSingletons().add(new SingletonTypeInjectableProvider<javax.ws.rs.core.Context, Myobj>(Myobj.class, new Myobj(12,13)){}); root.addServlet(new ServletHolder(new ServletContainer(rc)), "/"); server.start(); and you should be able to incject Myobj instance using @Context annotation. @Path("/helloworld") public class HelloWorldResource { @Context Myobj myClass; .... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: write a function to returns 0 with probability p? a function f() returns 0 or 1 with 0.5 probability each. Write a function g() that returns 0 with a probability of p..?? Assume p is given and lies between 0 and 1. A: If you had access to a (pseudo-) random number generator you could generate a random number between 0 and 1. If that number is below p, return 0, otherwise return 1. You didn't make it clear in your question, but I will assume the only access to a random source you have is to call f() to get one bit at a time. Consider the binary representation of p, for example: 0.011010010110... Similarly call f() repeatedly generating an unlimited length sequence of random binary digits x: 0.0110110010101... As soon as you are sure that x is above or below p, you are done. You only need to call f as many times as necessary to be sure of the result. p=0.011010... x=0.011011... ^ x>p: Stop and return 1. I assume this is homework, so I won't give full source code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IOS4 removing shadow of the icon of the application I have given an icon to my application the image i am giving is not having any shadow over it but on iphone it shows the shadow over the icon. Is it possible to remove the shadow. A: Yes,you can Remove shadow by doing this. Include a row in the info.plist file of your app Icon already includes gloss effects and checkmark the checkbox. A: To remove shadow of the icon of the application, Just do this:
{ "language": "en", "url": "https://stackoverflow.com/questions/7510877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: read the html element with array name jquery Possible Duplicate: How to get a value of an element by name instead of ID How can I read the value of the field named item[tags][] from the following HTML document: <ul id="mytags" class="tagit"> <li class="tagit-choice"> Acrylic <input type="hidden" name="item[tags][]" value="Acrylic" style="display: none;"> </li> <li class="tagit-choice"> Bath <input type="hidden" name="item[tags][]" value="Bath" style="display: none;"> </li> </ul> A: $(document).ready(function() { $('input[name="item[tags][]"]').each(function (){ alert($(this).val()); }); }); A: You can use this for getting value of a input with named 'something'. And you shouldnt use display none if you want to get its value $('input[name=something]').val() A: You don't have to use brackets to pass values as an array since name is not required to be unique across the page. Values with the same name attribute are passed on form submit as an array automatically. I created an example filling JS array with elements values. Markup: <ul id="mytags" class="tagit"> <li class="tagit-choice"> Acrylic <input type="hidden" name="tags" value="Acrylic"> </li> <li class="tagit-choice"> Bath <input type="hidden" name="tags" value="Bath"> </li> </ul> Code var tags = new Array[]; $("#mytags").find("[name='tags']").each( function() { tags.push($(this).val()); } ); alert(tags.toString()); You can play with it: http://jsfiddle.net/VAjeN/
{ "language": "en", "url": "https://stackoverflow.com/questions/7510884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing LOCALE_SISO639LANGNAME for LOCALE_USER_DEFAULT Is there a way to change "LOCALE_SISO639LANGNAME" on runtime? I would like to set another language for "LOCALE_SISO639LANGNAME" on runtime and when queried by "GetLocaleInfo", it should be new language instead of system default. By the way, it seems, you can't set "LOCALE_SISO639LANGNAME" by using "SetLocaleInfo". Thank you in advance for your kind concern. A: LOCALE_SISO639LANGNAME is a constant (C++ #define) so you cannot really change it on runtime. If I understand you correctly, you want to replace GetLocaleInfo calls with this value as a first argument so that effectively another argument is passed to the API. It would not be a big deal if it was all in your code (code edit and binary rebuild could really do the job), and I can assume that you want this rather to have effect for something you only have in binary. Provided that the guesswork above is correct, and especially you want it just for your process, you could perhaps hook GetLocaleInfo entry point and patch it in order to intercept the call and update arguments. It is not something easy or safe to use though, you will have to understand what you are doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Help with File descriptors in Unix Every process has a file descriptor table (FDT) and each file has a file descriptor. The file descriptors for stdin, stdout and stderr are 0,1, and 2. These values are same for all processes. The FDT I believe contains references to the INODE entries of those file. The file descriptors are reused across processes i.e. they are not globally unique. Is there a global FDT maintained by kernel to which each process' FDT references? What do FDT for stdin, stdout and stderr correspond to? Are these special files linked to the keyboard, display etc. Please provide links to articles, books etc. A: A good starting point is the article "A small trail through the Linux kernel" from 2001. The mechanisms are still similar, though the implementation has moved on and is best studied in a more recent kernel. Inside the kernel each open file descriptor corresponds to a struct file, which contains all the information about the open file or device. The file descriptor is really no more than an index into the FDT for the process. In the Linux kernel the struct file is attached to the FDT by the function fd_install(). The struct file can be reassigned to another file descriptor by the dup2 system call. Processes can share the same FDT if the processes were created by the clone system call with the CLONE_FILES flag, but there is no global FDT. The normal fork operation creates a new FDT which is a copy of the parent FDT. The practical use of this is for each thread of an multi-threaded application to be a cloned process sharing a common FDT, ensuring that all threads can use the same integer file descriptors. If you create a new process using fork/exec, the new process starts with the same file descriptors but can open and close files without affecting the parent. The FDT entries for stdin, stdout, stderr are inherited from the parent. There is nothing special about their kernel implementation of these three FDT entries; their meaning comes from the conventional use by the C library. The parent process alone decides what they are connected to. They may connect to character devices, or they may have been connected to files or to pipes. For the character device case, the most normal is to be a tty or pty device. The free book Linux Device Drivers has a good overview of these.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: passing size of an array to a function ...,you must pass to the function the array size. (Note:Another practise is to pass a pointer to the beginning of the array and a pointer to the location just beyond the end of the array.The difference of the two pointers is the length of the array and resulting code is simpler.) I couldn't write the codes for what it's saying in the note. Can anyone help me? A: The problem is that if you cannot pass an array to a function. When you do so, the name of the array "decays" to a pointer to its first element. That means you no longer know the size of that array, as you can only pass around a pointer to an element in that array. So you have to pass it a size, so the function receiving the "array" knows how long it is. e.g. //the below declaration is even the same as e.g. //void foo(unsigned char array[4], size_t length) //the array notation doesn't really apply to a function argument list //it'll mean a pointer anyhow. void foo(unsigned char *array, size_t length) { size_t i; for(i = 0; i < length ; i++) { printf("%02X ", array[i]); } } Or in the case where you pass in a pointer one element past the end of the array: void bar(unsigned char *array, unsigned char *end) { while(array != end) { printf("%02X ", *array); array++; } } And you call it like unsigned char data[] = {1,2,3,4}; foo(data,sizeof data); //same as foo(&data[0], siseof data); bar(data, data + 4); //same as bar(&data[0], &data[4]); A: Let's assume we have this array of integers: #define CAPACITY 42 int foo[CAPACITY]; And these two functions that process it: void func1(int* begin, int* end) { // Loop over the array while(begin < end) { int val = *begin++; // process element } } void func2(int* begin, int size) { // Loop over the array for(int i = 0; i < size; ++i) { int val = begin[i]; // process element } } The first one would be called like func1(foo, foo + CAPACITY): passing in a pointer to the start of the array, and a pointer to just beyond the last element. The second would be called like func2(foo, CAPACITY): passing in a pointer to the start of the array and the array size. Due to how pointer arithmetic works, both versions are equivalent. A: Something like this: int accumulate( int *first, int *last ) { int result = 0; for( ; first != last; ++first ) { result += *first; } return result; } int main() { int arr[] = {1,2,3,4,5}; int sum = accumulate( arr, arr + 5 ); return 0; } The code above sums all the elements in the range [first, last); where first in included in the range and last is excluded. So you need to pass a pointer to the beginning of the range you want to sum and another to one location past the last element you want added to the sum. A: void f(int* arr, int len) { ... } void f(int* start, int* end) { ... } A: If you only want to pass the array size you could do pass the following to the function : function(sizeof(array)/sizeof(array[0])); A: int A[] = {1,2,3,4,5,6,7,8,9,0}; printf("Size of the Array %d \n", sizeof(A)/sizeof(int));//size of the array you can use this value to function void getSize(int A[], size_t size){ //do somthing } void function() { //from where you call this int A[] = {1,2,3,4,5,6,7,8,9,0}; getSize(A, sizeof(A)/sizeof(int)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7510887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make Magento support some French Characters? I've been trying to make Magento support some french characters but haven't got any success so far. The French text that I would want to display is: Vous aimerez peut-être aussi But somehow, it appears like this: Its been the same with several other characters. Magento does use UTF-8 by default, but still these characters are not being displayed (surprisingly, because StackOverflow is using UTF-8 and is able to display the characters) I noticed that ISO-8859-1 is able to display them, tried to change the default character encoding by editing the following file: app/code/core/Mage/Page/etc/config.xml And changed the node <default_charset>'s value to ISO-8859-1. Now Firefox displays the following in Page Info, and the text is still not being displayed properly: I am using Eclipse to edit the phtml files and often these french texts are being generated by php code. Any idea what I might be doing wrong? A: you have wrong encoding either in database or in documents , translation files. Ensure that the encoding is utf-8 all the way in all places that you deal with * *magento *database *document encoding while editing
{ "language": "en", "url": "https://stackoverflow.com/questions/7510889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Wordpress custom user table I have defined a custom user table in my wp-config. define('CUSTOM_USER_TABLE', 'wp_users'); define('CUSTOM_USER_META_TABLE', 'wp_usermeta'); But, when i try to print out the logged in user info, user_level seems to be missing and the roles is empty. Any idea? Any help is appreciated!!!! A: If you are using only a single users table for multiple WordPress installations, WordPress will only generate the user role for the WordPress installation that you create the user on. So, if you create john_doe on site1, john_doe will be assigned a user role on site1 (be it administrator, editor, author, etc), but site2 will not assign john_doe a user role. This is known as an "orphaned role." When john_doe logs into site2, he will receive a You do not have sufficient permissions to access this page error message. So, you can either manually add the role into the usermeta database, or have an admin update the user's role for that installation, or finally you can use a plugin. I found a plugin that makes managing orphaned user roles much easier. It is called WP-Orphanage Extended. I also created a video screencast explaining the whole issue, and showing how to use a single users table for multiple WordPress sites. You can find it here: http://mikemclin.net/single-users-table-multiple-wordpress-sites/ A: user roles are stored in wp_options with option_name: wp_user_roles Does that exist, or is it empty? Are all your tables prefixed with 'wp_'? if so. In wp_usermeta you have to set meta_key: wp_user_level Also check meta_key wp_capabilities
{ "language": "en", "url": "https://stackoverflow.com/questions/7510901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Want to develop a Newsletter Sending system for about 18000 email recipients using swift mailer I would like to develop a newsletter sending system using Swiftmailer. I would like to know: 1) Do I require to set a cron job for this ? 2) Batchsend() or Send() with a loop, which one is better ( I want each address to be in To field ) ? A: With regards to the first question; it's best to create the script to send the next x emails from the recipients list and call it repetitively until all the recipients have been processed. You'll need to keep track of who's been processed in the db and introduce error handling in case it fails; a good strategy is for each user: * *mark in db as processing *send recipient email *mark in db as processed This way you can see how many people failed at the end (i.e. those who still are marked as "processing"). In order to repeat the process you could use CRON and repeat every minute; but what if the sending takes over 1 minute (e.g. due to slow SMTP connection) then you'll have two processes running together so you'll either need to prevent this or introduce some sort of locking (the above example of marking users as "processing" will prevent two concurrent instances of the script from processing the same people). The other problem with CRON every minute is that it might take you ages to send all your emails. I had this exact problem and so I wrote The Fat Controller which handles parallel processing and repeating for you. I made a simple shell script which is started every day by CRON and runs The Fat Controller which then runs many instances of the PHP sending script. Here are some use cases and more information: http://fat-controller.sourceforge.net/use-cases.html With regards to your second question; I'm not sure of the internals of Swift mailer, but you'll want to open an SMTP connection, send emails, then close it - so you're not opening and closing a connection for each email. Check the documentation, I've used Swift before and it worked very well and had very clear documentation. A: Off topic I know, but possibly useful: Have you considered using an email newsletter provider such as http://mailchimp.com/? There's a cost involved obviously, but you have to compare that to the cost of developing and running it yourself, and maintaining it. If a few of your users decide that your mail is spam, which is guaranteed to happen, regardless of how thoroughly you have obtained consent, then you could easily get onto blacklists, which will seriously impede your mail. The big providers are much less likely to get blacklisted, as they're recognised legitimate mass mailers. They'll also take care of unsubscribe management. Edit: I am in no way affiliated with MailChimp. It's just the one I've used. A: send() is preferred. In fact, batchSend() has been removed. Construct a loop and send them all manually. A: I do a similar thing for notifications in an ERP application, customised emails basically. The way I do this is to use Gearman, and queue all the emails to be sent, then have a Gearman worker to do the actual sending. That way you can have multiple workers sending the emails and the front-end doesn't lock up waiting for each email to be sent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asset Pipeline: Trouble on deploying my Rails 3.1 application with Capistrano I am using Ruby on Rails 3.1.0 and Capistrano. I have a problem on make the application to work in production mode (the remote machine is running Ubuntu 10.4 - my local machine is a MacOS running Snow Leopard 10.6.7). When I deploy with Capistrano I get this error: uninitialized constant Rake::DSL When I try to access a web page I get this error: ActionView::Template::Error (application.css isn't precompiled) What I should to do in order to make the application to work in production mode on the remote machine? In my Capfile file I have: # Uncomment if you are using Rails' asset pipeline load 'deploy/assets' In my Gemfile file I have: group :production do gem 'execjs' gem 'therubyracer' end If I comment the load 'deploy/assets' I do not get anymore the uninitialized constant Rake::DSL but I get still the ActionView::Template::Error (application.css isn't precompiled) error. A: See: http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets " If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the precompile array: config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js'] " A: Try to add config.assets.compile = true in production.rb. Hope that helps. A: Try to create new Rails 3.1 project with scaffolding and deploy it. If everything will be ok, compare configs and other files with your real project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: richTextEditor problem in symfony I have installed sfExtraPluginForm in my symfony and i want to get a rich text editor in my forms but it just shows a simple textarea. I have installed sfExtraPluginForm and created a form in form folder. The code i have written is: $this->setWidgets(array( 'title' => new sfWidgetFormInput(), 'description' => new sfWidgetFormTextareaTinyMCE(array( 'width' => 550, 'height' => 350, 'theme' => 'advanced', )) What more do I need to do? A: You probably forgot to load tinyMCE library. Download it from the offcial website and include tiny_mce.js in your page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get Django application name for a file inside that application? Having full path for the file that is a part of django application I would like to get a Django application name. For example for this path: /lib/python2.6/site-packages/django/contrib/auth/tests/auth_backends.py Application name is auth. I wonder how this Django application name could be programatically calculated for specific filename inside an app. Background: I want to integrate calling Django test management command from a vim editor. It should run tests for an app currently edited file belongs. A: You can get module by filename with __import__. You can get it's package name with __package__ attribute. Then you can check which app from settings.INSTALLED_APPS is a substring of package name. It's your app. A: If you have an instance of a class in that module you could try: instance._meta.app_label
{ "language": "en", "url": "https://stackoverflow.com/questions/7510930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to take multiple values from user as input using gridview in c#? I need to input values for a week in my website. To use multiple labels and textbox doesn't look nice. Can I use gridview for that? and how? because gridview will always have modes as edit,cancel and not for input. Are there any other control that will be more suitable to take this kind of multiple input from user? A: Can I ask why you are not considering creating a user control that way you will be able to customise the the control just the way you want. If thats not an option then yes you can use the gridview. This example will get you started http://geekswithblogs.net/dotNETvinz/archive/2009/08/09/adding-dynamic-rows-in-asp.net-gridview-control-with-textboxes-and.aspx http://devpinoy.org/blogs/keithrull/archive/2008/07/28/how-to-create-dynamic-input-rows-in-a-gridview-with-asp-net.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7510931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What version of LLVM and Clang is available in XCode 4.2? What version of LLVM and Clang is available in XCode 4.2? I have searched a lot to try to find this information and the only thing i have seen is that it could be LLVM 3.0 A: The version of llvm-gcc and clang in Xcode is not related to llvm.org releases. They are branched from a random development version sometime in the lifetime of the development of that Xcode release. If you're looking to know what features are available in Clang, please make use of the __has_feature capability: http://clang.llvm.org/docs/LanguageExtensions.html#feature_check
{ "language": "en", "url": "https://stackoverflow.com/questions/7510933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to edit wall posts? Is it possible to edit wall posts? If so, how can I do this? Anyhow, I'd like to replace a wall post with modified one. Wall posts often fail to read meta data which is provided by open graph elements when I post a link to Wall through my app. A: This is not possible. According to the documentation: Update You cannot edit any of the fields in the status message object. A: You can delete wall posts, like you can delete most objects. I do not if it possible to edit but you can repost your message.
{ "language": "en", "url": "https://stackoverflow.com/questions/7510935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Could not create message from InputStream: Invalid Content-Type:text/html Hello. I made a client for WSDL by the manual: http://static.springsource.org/spring-ws/site/reference/html/client.html But when I start up my application, I get this error: Exception in thread "main" org.springframework.ws.soap.SoapMessageCreationException: Could not create message from InputStream: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response?; nested exception is com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response? at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java:204) at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java:58) at org.springframework.ws.transport.AbstractWebServiceConnection.receive(AbstractWebServiceConnection.java:90) at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:548) at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:496) at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:451) at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:395) at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:386) at org.springframework.ws.client.core.WebServiceTemplate.sendSourceAndReceiveToResult(WebServiceTemplate.java:376) at com.software.prod.core.ws.WebServiceClient.simpleSendAndReceive(WebServiceClient.java:36) at com.software.pro.core.common.ServiceRunner.main(ServiceRunner.java:19) Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Invalid Content-Type:text/html. Is this an error message instead of a SOAP response? at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.identifyContentType(MessageImpl.java:602) at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.<init>(MessageImpl.java:275) at com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl.<init>(Message1_1Impl.java:67) at com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl.createMessage(SOAPMessageFactory1_1Impl.java:61) at org.springframework.ws.soap.saaj.SaajSoapMessageFactory.createWebServiceMessage(SaajSoapMessageFactory.java:182) ... 10 more A: Are there a web service running at whatever URL you are trying to call? It seems as that the response you are receiving is probably a html page or a HTTP error (I would guess 404 - File or Directory not found). What URL are you trying to call? A web service you created or some external web service? I would recommend trying to call the web service using SoapUI first (to be sure that the web service exists and is working)
{ "language": "en", "url": "https://stackoverflow.com/questions/7510937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }