text
stringlengths
8
267k
meta
dict
Q: POSIX threading on ios I've started experimenting with POSix threads using the ios platform. Coming fro using NSThread it's pretty daunting. Basically in my sample app I have a big array filled with type mystruct. Every so often (very frequently) I want to perform a task with the contents of one of these structs in the background so I pass it to detachnewthread to kick things off. I think I have the basics down but Id like to get a professional opinion before I attempt to move on to more complicated stuff. Does what I have here seem "o.k" and could you point out anything missing that could cause problems? Can you spot any memory management issues etc.... struct mystruct { pthread thread; int a; long c; } void detachnewthread(mystruct *str) { // pthread_t thread; if(str) { int rc; // printf("In detachnewthread: creating thread %d\n", str->soundid); rc = pthread_create(&str->thread, NULL, DoStuffWithMyStruct, (void *)str); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); //exit(-1); } } // /* Last thing that main() should do */ // pthread_exit(NULL); } void *DoStuffWithMyStruct(void *threadid) { mystruct *sptr; dptr = (mystruct *)threadid; // do stuff with data in my struct pthread_detach(soundptr->thread); } A: One potential issue would be how the storage for the passed in structure mystruct is created. The lifetime of that variable is very critical to its usage in the thread. For example, if the caller of detachnewthread had that declared on the stack and then returned before the thread finished, it would be undefined behavior. Likewise, if it were dynamically allocated, then it is necessary to make sure it is not freed before the thread is finished. In response to the comment/question: The necessity of some kind of mutex depends on the usage. For the sake of discussion, I will assume it is dynamically allocated. If the calling thread fills in the contents of the structure prior to creating the "child" thread and can guarantee that it will not be freed until after the child thread exits, and the subsequent access is read/only, then you would not need a mutex to protect it. I can imagine that type of scenario if the structure contains information that the child thread needs for completing its task. If, however, more than one thread will be accessing the contents of the structure and one or more threads will be changing the data (writing to the structure), then you probably do need a mutex to protect it. A: Try using Apple's Grand Central Dispatch (GCD) which will manage the threads for you. GCD provides the capability to dispatch work, via blocks, to various queues that are managed by the system. Some of the queue types are concurrent, serial, and of course the main queue where the UI runs. Based upon the CPU resources at hand, the system will manage the queues and necessary threads to get the work done. A simple example, which shows the how you can nest calls to different queues is like this: __block MYClass *blockSelf=self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [blockSelf doSomeWork]; dispatch_async(dispatch_get_main_queue(), ^{ [blockSelf.textField setStringValue:@"Some work is done, updating UI"]; }); }); __block MyClass *blockSelf=self is used simply to avoid retain cycles associated with how blocks work. Apple's docs: http://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html Mike Ash's Q&A blog post: http://mikeash.com/pyblog/friday-qa-2009-08-28-intro-to-grand-central-dispatch-part-i-basics-and-dispatch-queues.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7518449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: want to play TTS on Bluetooth headset I have a TTS Application which works fine on phone speaker and wired headsets. But when I connect Bluetooth headset, it does not speak on Bluetooth headset. How can I do this without using any deprecated API. The problem is in Android 2.3 AudioManager .. setRouting(), setBluetoothA2DP all are deprecated. Please guide how can I send my TTS output to bluetooth. A: Are you sure you try this: HashMap<String, String> myHashAlarm = new HashMap<String, String>(); myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_SYSTEM_CALL)); mTts.speak(" aabb1321100111000",TextToSpeech.QUEUE_ADD, myHashAlarm); AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); mAudioManager.setStreamMute(AudioManager.STREAM_VOICE_CALL, true); mAudioManager.startBluetoothSco();
{ "language": "en", "url": "https://stackoverflow.com/questions/7518452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to play background music while recording voice? friends Now I'm developing iPhone Recorder App. I can easily record my voice with sample code. I want to record background music with my voice. For example,When I click "Record" button,background music plays Then I sing a song. In this case,I should record background music with my voice. But,If I did like that,I can't record anything. What's wrong? To do this,what should I do? Please help me.. Thanks. A: I'm not familiar with programming for the iPhone but I can imagine there would be a limitation to what you like to achieve IF you intend to make this work without using headphones/headset. It just might be that the OS wont let you play music and record at the same time because the recording would result in an echo because of the background music. That said, I'm sure an experienced iPhone programmer is able to tell you exactly how this would work. Good luck and I hope my suggestion helps you out. A: friends I solved this problem by using OpenAL. Thanks for all your effet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to encode long-string in the DB where attribute type is varchar(254)? Say for some reason I’ve got a table in the DB that only have varchar(254) attribute types. So in other words, I cannot store a String directly which has more than 254 characters. But would there be a way around this, i.e. is it possible to encode a long string (say approx 700 chars) in the DB given this constraint. What would be the easiest way to do this? I use Java. A: Depending on the nature of the string you're wanting to store, you might be able to compress it down to the required length. However, this is a can of worms. If I were in your shoes, I'd first investigate whether widening the column is an option (in most SQL DBMSs all it takes is a simple ALTER COLUMN command). P.S. If you have to compress the data, take a look at the Deflater class. However, if I were you, I'd fight really hard for that trivial schema change.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Daemon to monitor activity I am working on some kind of communication which might get interrupted once in a while. For this I need some kind of monitor that fires after 5 seconds, if not in the meantime has been reset by any valid communication to start waiting for another 5 seconds, and so on.... Thanks! A: Take a look at the NSTimer class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery that just waits I normally set up my javascript code to have a function. But due to the fact that the application generates most of the HTML and javascript calls from a VB6 application I would like to create a jQuery function that is more like a listener. So for example if I have a td tag that has the class 'gridheader1' I would like the jQuery to wait for it to be clicked. I'm assuming that I would use the bind... But I'm getting javascript errors with it... If you can offer suggestions on where my code is wrong that would be great. $('.gridheader1').bind('click', function() { alert('hi I got clicked'); }); Again this just has to sit out there on the main .js file. It isn't attached to any functions. Please let me know. Thanks A: you want $('.gridheader1').bind('click', function(){ alert('hi I got clicked'); }); note the dot at the start of selector - it means class A: // static tags $(function(){ // DOM ready $('.gridheader1').click(function() { alert('gridheader1 clicked'); }); }); // or if the tag is loaded via ajax use 'live'... $(function(){ // DOM Ready $('.gridheader1').live('click', function() { alert('gridheader1 clicked'); }); }); // or if you already have a function defined that you want to call, you can pass in the function instead of using an anonymous function. function alertAboutStuff(){ alert('gridheader1 clicked'); } $(function(){ $('.gridheader1').click(alertAboutStuff); // $('.gridheader1').live('click', alertAboutStuff); // for tags loaded via ajax });
{ "language": "en", "url": "https://stackoverflow.com/questions/7518466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access the SVNClientAdapter that subclipse is using during runtime? I am using the Subclipse API and I would like to implement the ISVNNotifyListener so that I can find out about the subclipse events as they happen during runtime. I believe I need to add (subscribe) my instance of the notify listener to the set of listeners that the Client Adapter will notify, but I am at a loss for how to get access to the Client Adapter that is being used by Subclipse at runtime. Is there a way to access it so that I can add my listener to the set? A: Sorry, but unfortunately Subclipse has not been coded in such a way to provide access to the internals. Subclipse constructs a new ISVNClientAdapter object for each API call it needs to make into Subversion and it adds its ISVNNotifyListener to this object on the fly as needed. So there is no way for you to interject your own listener. Perhaps you could write a class that implements IConsoleListener and have it act as a proxy for the Subclipse class. You could then call SVNProviderPlugin.getConsoleListener to get the current console listener and store a reference to it in your class. Then call SVNProviderPlugin.setConsoleListener to replace the class held in Subclipse with your class. As the events are fired in your class, you could just forward them on to the Subclipse class and do whatever you want with the events in your code. Something like this: import java.io.File; import org.tigris.subversion.subclipse.core.client.IConsoleListener; import org.tigris.subversion.svnclientadapter.SVNNodeKind; public class ProxyListener implements IConsoleListener { private IConsoleListener subclipseListener; public ProxyListener(IConsoleListener subclipseListener) { super(); this.subclipseListener = subclipseListener; } public void setCommand(int command) { subclipseListener.setCommand(command); // TODO add your code } public void logCommandLine(String commandLine) { subclipseListener.logCommandLine(commandLine); // TODO add your code } public void logMessage(String message) { subclipseListener.logMessage(message); // TODO add your code } public void logError(String message) { subclipseListener.logError(message); // TODO add your code } public void logRevision(long revision, String path) { subclipseListener.logRevision(revision , path); // TODO add your code } public void logCompleted(String message) { subclipseListener.logCompleted(message); // TODO add your code } public void onNotify(File path, SVNNodeKind kind) { subclipseListener.onNotify(path, kind); // TODO add your code } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Phonegap GPS without internet I m trying to make an android app which count the distance traveled from log,lan values with phonegap.But phonegap GPS work only when internet or wifi in ON condition.How can get log ,lan values without internet by using geolocation api.Thanks in advance . A: See the PhoneGap API Docs for Geolocation under the geoLocationOptions: Android Quirks The Android 2.x simulators will not return a geolocation result unless the enableHighAccuracy option is set to true. { enableHighAccuracy: true } Enabling that option will allow the Android device to get the location even with the WIFI option disabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Django’s filter() method joins parameters using an AND statement. Is there an alternative that uses OR? I’m trying to write a Django query that returns objects that match either of two parameters. If I do this: MyModel.objects.filter(parameter1=True, parameter2=True) Then I only get objects that match both parameters. What query can I use to select objects that match either parameter? A: It's very simple. You just need to use special Q object. As it is described here: https://docs.djangoproject.com/en/1.3/topics/db/queries/#complex-lookups-with-q-objects
{ "language": "en", "url": "https://stackoverflow.com/questions/7518477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pagedown (WMD-Editor) Java Sanitizer (or OWASP xml rules) I'm using the reimplementation of the famous wmd-javascript editor PageDown on client side (which is also used on Stackoverflow). Now, I'm searching an HTML sanitizer for my server (runs tomcat7) which should only filter the HTML-subset that the PageDown editor can create. My first choice was the OWASP project but I didn't found a xml rule file for PageDown - the rule-file for tinymce was too restrictive because it didn't include e.g. an "img"-tag. Building my own set of rules is not only quite painful, it gives me security concerns. For this reason I wanted to ask if there are Java-classes or OWASP-Rules or something else out there which also have been tested. Help would be very appreciated! Thx in advance, Thomas A: You can use JSoup. Its allows you to whitelist the elements you want in the resulting HTML. See jsoup_cookbook_cleaning-html_whitelist-sanitizer A: Use HTML Purifier, html5lib, or another system built specifically for HTML sanitization. (Since you asked about OWASP: The good ones will use the OWASP whitelist of allowed tags, attributes, and other syntax.) A: OWASP's new HTML Sanitizer doesn't require you to maintain rules in an XML configuration language. It comes with pre-packaged policies which can be unioned together, and if you want to do a custom policy, you can do that in Java code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS to change background color of ASP.NET server controls I have a Div with a table (2x2) inside it. I also have a CSS file but I am not following how to change the background color of table columns where ASP.NET DropDown exists. I tried: Edited <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ddl1.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <link href="Stylesheet1.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td> <asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList> </td> <td></td> </tr> <tr> <td> <asp:DropDownList ID="ddl2" runat="server"></asp:DropDownList> </td> <td></td> </tr> </table> </div> </form> </body> </html> The CSS I attempted: body { } table { border-color:Olive; border-style:solid; border-collapse:collapse; } table td { width:200px; } table.DropDownList { width:200px; background-color:Gray; } A: Best guess without full HTML: #form1 td { background-color:Gray } EDIT: But this will colour all of your cells, even those not containing SELECT. You need to use JavaScript. jQuery makes this quite easy: $(document).ready(function() { $('#form1 select').parent().css('background-color','Gray') } A: does it work within the tags without css? <asp:DropDownList backcolor="gray" ID="ddl1" runat="server"></asp:DropDownList> edit also, since it probably gets rendered into html you might want to change the style of the select box?.. select { background-color: gray; } ..you could use the within functionality, but only for the select-boxes again - so not exactly what you wanted, without further logic I think you could only go for css-classes or ids (used at the td's): td select { background-color: gray; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to split image into smaller rectangles for iPhone, Android, or Rails? My client would like to create an iPhone & Android app that turns custom photos into jigsaw puzzles. (Yes, we know these exist already.) What's the best way to take a custom image and split it into smaller rectangles? This SO post is close (http://stackoverflow.com/questions/5991302/algorithm-to-split-an-image-into-smaller-images-reducing-the-amount-of-whitespace), but we're wondering if there are any libraries to facilitate the process either for mobile devices or even for Rails (i.e., we perform the image processing on the server instead of on the client). A: I believe that ImageMagick, http://www.imagemagick.org/script/index.php, would be suitable for this task on the server side. IIRC, Rails has a gem that integrates with ImageMagick nicely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: flash player is outside of div (only in IE) I'm using the following code to display a fusionchart inside a div tag. The chart is rendered correctly in Chrome and FF, but with IE it's outside the boundaries of my div tag. Any idea what I'm missing? <div id="chart_div" style="width: auto;border: solid 1px #ff0000;><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="chart" > <param name="movie" value="../FusionCharts/Column2D.swf" /> <param name="FlashVars" value="&dataURL=' . 'chart_data/'.$xml_file . '&chartWidth=100%&chartHeight=500px"> <param name="quality" value="high" /> <embed src="../FusionCharts/Column2D.swf" flashVars="&dataURL=' . 'chart_data/'.$xml_file . '&chartWidth=100%&chartHeight=500px" quality="high" width="100%" height="500px" name="chart" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/> </object></div> IE always seems to be difficult... A: You are missing a closing / Try changing <param name="FlashVars" value="&dataURL=' . 'chart_data/'.$xml_file . '&chartWidth=100%&chartHeight=500px"> to <param name="FlashVars" value="&dataURL=' . 'chart_data/'.$xml_file . '&chartWidth=100%&chartHeight=500px"/> A: Your problem is because of unclosed elements and missing qoutes. You need to change, <param name="FlashVars" value="&dataURL=' . 'chart_data/'.$xml_file . '&chartWidth=100%&chartHeight=500px"> To this... <param name="FlashVars" value="&dataURL=' . 'chart_data/'.$xml_file . '&chartWidth=100%&chartHeight=500px"> And this... <div id="chart_div" style="width: auto;border: solid 1px #ff0000;> To this... <div id="chart_div" style="width: auto;border: solid 1px #ff0000;"> This should solve your problem. Happy coding bud. A: Could you please try setting Flash vars in this fashion? &chartWidth=100%&chartHeight=500 (without the px) Also, You can try mentioning : <object width="100%" ..> A: You're missing a close quote at the end of the <div>'s style attribute. Maybe try adding overflow:hidden if it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to count the number of children of parents in prolog (without using lists) in prolog? I have the following problem. I have a certain number of facts such as: parent(jane,dick). parent(michael,dick). And I want to have a predicate such as: numberofchildren(michael,X) so that if I call it like that it shows X=1. I've searched the web and everyone puts the children into lists, is there a way not to use lists? A: Counting number of solutions requires some extra logical tool (it's inherently non monotonic). Here a possible solution: :- dynamic count_solutions_store/1. count_solutions(Goal, N) :- assert(count_solutions_store(0)), repeat, ( call(Goal), retract(count_solutions_store(SoFar)), Updated is SoFar + 1, assert(count_solutions_store(Updated)), fail ; retract(count_solutions_store(T)) ), !, N = T. A: I can only see two ways to solve this. The first, which seems easier, is to get all the solutions in a list and count it. I'm not sure why you dislike this option. Are you worried about efficiency or something? Or just an assignment? The problem is that without using a meta-logical predicate like setof/3 you're going to have to allow Prolog to bind the values the usual way. The only way to loop if you're letting Prolog do that is with failure, as in something like this: numberofchildren(Person, N) :- parent(Person, _), N is N+1. This isn't going to work though; first you're going to get arguments not sufficiently instantiated. Then you're going to fix that and get something like this: ?- numberofchildren(michael, N) N = 1 ; N = 1 ; N = 1 ; no. The reason is that you need Prolog to backtrack if it's going to go through the facts one by one, and each time it backtracks, it unbinds whatever it bound since the last choice point. The only way I know of to pass data across this barrier is with the dynamic store: :- dynamic(numberofchildrensofar/1). numberofchildren(Person, N) :- asserta(numberofchildrensofar(0)), numberofchildren1(Person), numberofchildrensofar(N), !. numberofchildren1(Person) :- parent(Person, _), retract(numberofchildrensofar(N)), N1 is N + 1, asserta(numberofchildrensofar(N1), !, fail. numberofchildren1(_). I haven't tested this, because I think it's fairly disgusting, but it could probably be made to work if it doesn't. :) Anyway, I strongly recommend you take the list option if possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom dialog to alert web page didn't load I want to alert people if a page doesn't load and the Toast feature doesn't stay up for a long enough period of time (but i left the code in and commented out in case i want to go back to it). So I am now trying to do a custom dialog instead but that doesn't pop up. I basically open the web page, which works I added a loader in the status bar so folks will see the page is loading, and that works I added code to keep the navigation in the app so folks don't exit to a new browser, and that works As I said, the toast technically works, but doesn't stay up for as long as I would like Then I added the custom alert dialog, and that's where I fail I also created a separate XML file for the custom alert And then I haven't even get this far yet, but would I need to add code to close it, or does just hitting the back button automatically close it? Thanks! Here's my code in the .java file public class FC extends Activity { WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //this one line added for progress support this.getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.web); //makes progress bar visible getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); //get web view mWebView = (WebView) findViewById( R.id.webWeb ); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setSupportZoom(true); mWebView.getSettings().setBuiltInZoomControls(true); mWebView.setInitialScale(45); mWebView.loadUrl("http://www.chipmunkmobile.com"); //sets the Chrome client final Activity MyActivity = this; mWebView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { //makes the bar disappear after URL is loaded, and changes string to Loading... MyActivity.setTitle("Loading..."); MyActivity.setProgress(progress * 100); //return the app name after finish loading if(progress == 100) MyActivity.setTitle(R.string.app_name); } }); //makes page stay in same web client mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return false; } }); //looks to see if connects mWebView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { //Toast.makeText(getApplicationContext(), "NO CONNECTION?\nVisit the Cyberspots in the SW and NW Halls to find out how to get on the free WiFi", //Toast.LENGTH_LONG).show(); //showDialog(0); AlertDialog.Builder builder; AlertDialog alertDialog; Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup) findViewById(R.id.layout_root)); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("WHATEVER"); ImageView image = (ImageView) layout.findViewById(R.id.imgid); image.setImageResource(R.drawable.img); builder = new AlertDialog.Builder(mContext); builder.setView(layout); alertDialog = builder.create(); } }); } Here's my code in the .xml file <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/layout_root" android:padding="10dp"> <ImageView android:id="@+id/imgid" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout> A: Add an alertDialog.show() to the end of the method to actually display the dialog. Also, you may want to add a setNeutralButton("ok", new DialogInterface.OnClickListener() {...} and call finish to close the dialog in the OnClickListener. A: Instead of using an alert I just used an embedded HTML error message...I didn't find a fix to the alertDialog problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7518491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write stream in the same browser window using OutputStreamWriter? In the server side code, I am writing a string (which gets written on a browser page) using OutputStreamWriter. This gets written in a new window. I need to be able to write this in the same window. The class extends HttpServlet and following is the structure of the code: void foo(HttpServletResponse response...) { ... OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream()); response.reset(); response.setContentType("text/html"); out.write("Hello World!"); // Or some html string out.flush(); out.close(); } A: The server side (the servlet) don't and can't open a new window (fortunately, otherwise spamming the client with popups would be tremendously easy...). The client (the browser) is the only who can open a new window. Most likely you've used one of the following constructs in HTML or JavaScript which will show the result in a new window: <form action="servleturl" target="_blank"> or <a href="servleturl" target="_blank"> or <script>window.open('servleturl', 'windowname');</script> You need to remove the target="_blank" to get the response in the current window, or in case you're using JavaScript, to use window.location = 'servleturl'; instead. Unrelated to the concrete question, emitting HTML in a servlet is a poor practice. Use JSP instead. See also: * *Our servlets wiki page *Our JSP wiki page
{ "language": "en", "url": "https://stackoverflow.com/questions/7518497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Wordpress 3.2.1 javascript error - $ is not a function I'm receiving a $ is not a function error. This is new since I updated from 3.2.1. I have an identical setup working on 3.1. Have folks run into this issue? I have turned off all plugins and am just attempting to load the superfish (or any jquery) and am receiving this error. What changed that I'm missing? These are all currently on the same server if that is any help. thank you, A: What happens if you change $ to jQuery? Does that work? $ is simply a variable for the jQuery object. In some setups, you need to use jQuery rather than $. A: EDIT I had the same error, and it was because of jQuery not loaded. You can this error if your jquery is not loading. To determine if this is the case, you need to debug your webpage network traffic using IE9 -> F12 -> Network -> Capture to see if you get 404 for jQuery files (i.e. something/wp-includes/jquery.js), or use same thing in Firefox's Firebug extension. You can also search for jquery in page source, it should be in tag, and when you find src (i.e. http://code.jquery.com/jquery-1.6.4.min.js) try open it, if it says 404 not found then you need to place jquery in that file on server (or change whatever php/plugin loads that script tag to correct path) If you do not know how to do this, please provide link to your wordpress installation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How does the JavaScript Image object interact with the browser cache? I'm using simple objects to wrap Image objects and track when they are loaded, like so: var preloader = { loaded: false, image: new Image() } preloader.image.onload = function() { preloader.loaded = true; } preloader.image.src = 'http://www.example.com/image.jpg'; When the image is finished loading, preloader.loaded is set to true. That all works fine. My question is, what happens when I have so many of these objects and so many images that the browser cache is used up. Eventually once enough images are loaded, the browser will start to dump older ones out of the cache. In that case won't I end up with JavaScript objects where loaded=true, but the image file is not actually cached anymore? This is hard to test, because I can't tell at any given point which images are still in the cache and which aren't. A: Once you've loaded the image from a web page, it's not being used from the cache. It's actually in the browser page memory for the duration of the browser page lifetime or until you get rid of this JS object so it can be garbage collected. The cache is not used for storage of loaded images on a page. The cache is used so that the next time a load of this image is requested, it can be loaded much faster. If you load so many images that it exceeds the storage of the cache, nothing will happen to the images you have already loaded as they are in browser memory for the duration of the page (independent of the cache). What will happen is that some of the images you loaded will no longer be in the cache so the next time some browser pages wants to load them, they won't be in the cache and will have to be fetched from their original web-site over the internet. A: Yesterday I deleted 800MB of internet cache that had built up over the past few months. In short, I don't think it's possible to exhaust the browser cache unless the user has a really old machine, or you're preloading WAY too many images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Overlapping Grids inside a Tab I have two grids inside a TabItem and in the code-behind I want to be able to add controls to both grids and have all the controls visible at run-time. Currently at run-time the controls added to "Grid3" are not visible while he controls added to "Grid4" are visible. The overlapping grids have the same rows but a different set of columns. I'm trying to do this with two grids so that I can vary the number of controls I can add per row in the code-behind by adding the controls to one of the two grids. Here's the XML: <Grid Name="TabControlGrid" Margin="20,171,0,70"> <TabControl > <TabItem Header="Tab1" > <Grid Name="InnerTabControlGrid"> <!--Start Grid3--> <Grid Name="Grid3" Background="#FFE3EFFF" Height="188"> <Grid.ColumnDefinitions> <ColumnDefinition Width="98*" /> <ColumnDefinition Width="296*" /> <ColumnDefinition Width="88*" /> <ColumnDefinition Width="327*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="10*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="30*" /> </Grid.RowDefinitions> <Grid Name="InnerGrid3" Grid.ColumnSpan="4" Grid.RowSpan="8" VerticalAlignment="Top" HorizontalAlignment="Left" Width="807"> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="TextBlock1" Text="Row 1, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,35,0,0" Name="TextBlock2" Text="Row 2, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,60,0,0" Name="TextBlock3" Text="Row 3, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,85,0,0" Name="TextBlock4" Text="Row 4, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,110,0,0" Name="TextBlock5" Text="Row 5, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,135,0,0" Name="TextBlock6" Text="Row 6, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,160,0,0" Name="TextBlock7" Text="Row 7, Col 1" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="405,10,0,0" Name="TextBlock8" Text="Row 1, Col 2" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="405,35,0,0" Name="TextBlock9" Text="Row 2, Col 2" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="405,60,0,0" Name="TextBlock10" Text="Row 3, Col 2" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="405,85,0,0" Name="TextBlock11" Text="Row 4, Col 2" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="405,110,0,0" Name="TextBlock12" Text="Row 5, Col 2" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="403,135,0,0" Name="TextBlock13" Text="Row 6, Col 2:" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <TextBlock Height="23" HorizontalAlignment="Left" Margin="403,160,0,0" Name="TextBlock14" Text="Row 7, Col 2" VerticalAlignment="Top" Width="71" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,11,0,0" Name="ComboBox9" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,10,0,0" Name="ComboBox10" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,35,0,0" Name="ComboBox11" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,35,0,0" Name="ComboBox12" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,60,0,0" Name="ComboBox13" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,60,0,0" Name="ComboBox14" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,85,0,0" Name="ComboBox15" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,85,0,0" Name="ComboBox16" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,110,0,0" Name="ComboBox17" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,111,0,0" Name="ComboBox18" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,135,0,0" Name="ComboBox19" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,136,0,0" Name="ComboBox20" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="98,160,0,0" Name="ComboBox21" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,160,0,0" Name="ComboBox22" VerticalAlignment="Top" Width="291" Visibility="Collapsed"/> </Grid> </Grid> <!--End Grid3--> <Grid Name="Grid4" Background="#FFE3EFFF"> <Grid.ColumnDefinitions> <ColumnDefinition Width="97*" /> <ColumnDefinition Width="102*" /> <ColumnDefinition Width="91*" /> <ColumnDefinition Width="102*" /> <ColumnDefinition Width="87*" /> <ColumnDefinition Width="102*" /> <ColumnDefinition Width="99*" /> <ColumnDefinition Width="125*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="10*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="26*" /> <RowDefinition Height="30*" /> </Grid.RowDefinitions> <Grid Name="InnerGrid4" Grid.ColumnSpan="8" Grid.RowSpan="8" VerticalAlignment="Top" HorizontalAlignment="Left" Width="803" Height="193"> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="TextBlock15" Text="Row 1, Col 1" VerticalAlignment="Top" Width="73" Visibility="Collapsed" /> <TextBox BorderBrush="#FF898C95" Height="23" HorizontalAlignment="Left" Margin="98,11,0,0" Name="TextBox13a" VerticalAlignment="Top" Width="100" Visibility="Collapsed" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="210,10,0,0" Name="TextBlock16" Text="Row 1, Col 2" VerticalAlignment="Top" Width="73" Visibility="Collapsed" /> <TextBox BorderBrush="#FF898C95" Height="23" HorizontalAlignment="Left" Margin="289,11,0,0" Name="TextBox14a" VerticalAlignment="Top" Width="100" Visibility="Collapsed" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="410,12,0,0" Name="TextBlock17" Text="Row 1, Col 3" VerticalAlignment="Top" Width="67" Visibility="Collapsed" /> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,10,0,0" Name="ComboBox23" VerticalAlignment="Top" Width="100" Visibility="Collapsed" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="600,14,0,0" Name="TextBlock18" Text="Row 1, Col 4" VerticalAlignment="Top" Width="71" Visibility="Collapsed" /> <TextBox BorderBrush="#FF898C95" Height="23" HorizontalAlignment="Left" Margin="680,11,0,0" Name="TextBox18a" VerticalAlignment="Top" Width="100" Visibility="Collapsed" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="10,35,0,0" Name="TextBlock19" Text="Row 2, Col 1" VerticalAlignment="Top" Visibility="Collapsed" Width="73" /> <TextBox BorderBrush="#FF898C95" Height="23" HorizontalAlignment="Left" Margin="98,36,0,0" Name="TextBox1" VerticalAlignment="Top" Visibility="Collapsed" Width="100" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="210,35,0,0" Name="TextBlock20" Text="Row 2, Col 2" VerticalAlignment="Top" Visibility="Collapsed" Width="73" /> <TextBox BorderBrush="#FF898C95" Height="23" HorizontalAlignment="Left" Margin="289,36,0,0" Name="TextBox2" VerticalAlignment="Top" Visibility="Collapsed" Width="100" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="410,37,0,0" Name="TextBlock21" Text="Row 2, Col 3" VerticalAlignment="Top" Visibility="Collapsed" Width="67" /> <ComboBox Height="23" HorizontalAlignment="Left" Margin="479,35,0,0" Name="ComboBox24" VerticalAlignment="Top" Visibility="Collapsed" Width="100" /> <TextBlock Height="23" HorizontalAlignment="Left" Margin="600,39,0,0" Name="TextBlock22" Text="Row 2, Col 4" VerticalAlignment="Top" Visibility="Collapsed" Width="71" /> <TextBox BorderBrush="#FF898C95" Height="23" HorizontalAlignment="Left" Margin="680,36,0,0" Name="TextBox3" VerticalAlignment="Top" Visibility="Collapsed" Width="100" /> </Grid> </Grid> </Grid> </TabItem> <TabItem Header="Tab2" > </TabItem> </TabControl> </Grid> The controls in the XML are just place holders for the controls I am adding to the grids in the code-behind. If anyone can suggest a solution I'd appreciate it. Thanks! -mg A: Your InnerTabControlGrid does not define any Row or Column Definitions, so both child grids are placed on top of each other in a single grid cell. Change InnerTabControlGrid to a DockPanel or a UniformGrid, or give it some Grid.ColumnDefinitions or Grid.RowDefinitions and assign your child grid's Grid.Column or Grid.Row A: Remove the background from the grid. You can not see through a solid color.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically maintaining sitemaps Hoping someone can chime in on an ideal methodology. I don't want to run my site through a crawler every month to add new pages to my sitemap, I'd like some robust systematic method to do so, because maintaining it by hand seems very prone to ahem human forgetfulness. Is there some sorta way to programmatically validate new controllers, controller methods, views, etc. to some special controller? What I'm picturing is some mechanism that enforces updating the sitemap whenever you create a new controller method or view. I work in LAMP stack if that's relevant. This guy here is doing it through the file system and that's not what I want for a public facing sitemap. Perhaps there's another best practice for this type of maintenance other than the concept I'm proposing. Would love to hear how everyone else does this! :) A: If your site is content based, best practise is reading database periodically and generating each contents link. With this method you can specify some subjects are more prior or vice versa in sitemap. That method already mentioned before at topic that you linked. Else, you can hold a visited pages list (static) at server-side. Or just log them. After recording your site traffic, without blocking the user experience, I mean asynchronously, check the sitemaps and add your page links there. You can specify priority with this method too, by visiting intensity of your pages and some statistical logic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Qt state machine framework connect signals In the Qt State Machine Framework documentation there is an example how to set properties on state activation: s1->assignProperty(label, "text", "In state s1"); s2->assignProperty(label, "text", "In state s2"); s3->assignProperty(label, "text", "In state s3"); Is there a way to connect slots on state activation? like s1_buttonclick will only be connected when s1 is active and s2_buttonclick will only be connected when s2 is active? A: You want the connections to be different based on which state the state machine is currently in? I think you will have to manage this yourself using other slots and the entered() and exited() signals. Just create a slot for the each entrance and exit of the states. QObject::connect(s1, SIGNAL(entered()), connectionManager, SLOT(connectS1())); QObject::connect(s1, SIGNAL(exited()), connectionManager, SLOT(disconnectS1())); //continue for each state A: Filtering signal-slot connections can be done using a helper class that represents a connection and provides an active property of the connection. Note that Qt 5's QMetaObject::Connection is not sufficient for this. #include <QMetaMethod> #include <QPointer> class Connection : public QObject { Q_OBJECT Q_PROPERTY(bool active READ isActive WRITE setActive NOTIFY activeChanged USER true) Q_PROPERTY(bool valid READ isValid) QMetaMethod m_signal, m_slot; QPointer<QObject> m_source, m_target; #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) QMetaObject::Connection m_connection; #else bool m_connection; #endif bool m_active; void release() { if (!m_source || !m_target) return; #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) disconnect(m_connection); #else disconnect(m_source, m_signal, m_target, m_slot); #endif } public: Connection(QObject * source, const char * signal, QObject * target, const char * slot, QObject * parent = 0) : QObject(parent), m_signal(source->metaObject()->method(source->metaObject()->indexOfSignal(signal))), m_slot(target->metaObject()->method(target->metaObject()->indexOfSlot(slot))), m_source(source), m_target(target), m_connection(connect(m_source, m_signal, m_target, m_slot)), m_active(m_connection) {} ~Connection() { release(); } QObject* source() const { return m_source; } QObject* target() const { return m_target; } QMetaMethod signal() const { return m_signal; } QMetaMethod slot() const { return m_slot; } bool isActive() const { return m_active && m_source && m_target; } bool isValid() const { return m_connection && m_source && m_target; } Q_SIGNAL void activeChanged(bool); Q_SLOT void setActive(bool active) { if (active == m_active || !m_source || !m_target) return; m_active = active; if (m_active) { m_connection = connect(m_source, m_signal, m_target, m_slot); } else { release(); } emit activeChanged(m_active); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7518513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Performing an action on one view, and the action doing something on another view? Is this possible? I have 2 views: * *OneViewController *TwoViewController TwoViewController has an IBAction which plays a sound. Once the user has pressed the button on TWoViewController I want a UILabel which will appear on OneViewController saying that the sound has been played. Thanks for the help A: All you have to do is reference one viewController in the other one, that way you can call it's methods. Or you can simply create a delegate. A: One possible solution is to use notifications. In the action that plays a sound, post a notification to the default notification center that indicates the sound has played. [[NSNotificationCenter defaultCenter] postNotificationName:"playSoundNotification" object:self userInfo:nil]; When OneViewController is created, have it register for the notification. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPlayedLabel:) name:"playSoundNotification" object:nil]; When it receives the notification -- in showPlayedLabel: -- display the UILabel. Note that showPlayedLabel must follow the appropriate signature format. - (void) showPlayedLabel:(NSNotification*) aNotification;
{ "language": "en", "url": "https://stackoverflow.com/questions/7518516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert a string to a url encoded I want to be able to convert for example ™ to %99 but i dont know what encoding is that I tried looking at httputility class but i dont get %99 i get other wierd signs can you please help me? thanks Im using C# I want to do that so my the login would work with all chars like ™ im using http post method for a vb forum i need first to correct the encoding EDIT : Not sure but can i just change the Content-Type : application/x-www-form-urlencoded to something that accepts signs like trademark so it would work? A: From the subject it seems that you are trying to encode given string to url string, e.g. changing something like user@email.com to user%40email.com so it can be in a url http://www.example.com?email=user%40gmail.com Can you provide a little more information? If you are trying to pass the string through a URL, than I highly recommend the HttpUtility.UrlEncode method to be on the safe side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: templated variable I currently have the following non templated code: class Vector{ public: double data[3]; }; static Vector *myVariable; void func() { myVariable->data[0] = 0.; } int main() { myVariable = new Vector(); func(); } I then want to template the dimension : template<int DIM> class Vector{ public: double data[DIM]; }; static Vector<3>* myVariable; void func() { myVariable->data[0] = 0.; } int main() { myVariable = new Vector<3>(); func(); } But I finally want to template my variable as well, with the dimension : template<int DIM> class Vector{ public: double data[DIM]; }; template<int DIM> static Vector<DIM> *myVariable; void func() { myVariable->data[0] = 0.; // or perform any other operation on myVariable } int main() { int dim = 3; if (dim==3) myVariable = new Vector<3>(); else myVariable = new Vector<4>(); func(); } However, this last version of the code produces an error : this static variable cannot be templated ("C2998: Vector *myVariable cannot be a template definition"). How could I possibly correct this error without a complete redesign (like inheriting the templated Vector class from a non templated class, which would require more expensive calls to virtual methods , or manually creating several myVariables of different dimensions) ? Maybe I'm just tired and don't see an obvious answer :s Edit: Note that this code is a minimal working code to show the error, but my actual implementation templates the dimension for a full computational geometry class, so I cannot just replace Vector by an array. I see that there doesn't seem to be a solution to my problem. Thanks! A: It's been a while, but I've used constants in the template declaration before. I eventually went another direction with what I was working on, so I don't know if it'll ultimately be your solution either. I think the problem here is that any templated variable must know its template argument at compile time. In your example, Vector<3> and Vector<4> are different types, and cannot be assigned to the same variable. That's why template<int DIM> static Vector<DIM> *myVariable doesn't make any sense; it doesn't have a discernible type. A: template<int DIM> static Vector<DIM> *myVariable; This is not allowed by the language specification. End of the story. And since I don't understand the purpose of your code, or what you want to achieve, I cannot suggest any better alternative than simply suggesting you to try using std::vector<T>. It's also because I don't know how much am I allowed to redesign your code, and the way you use it, to make your code work. A: You can use std::array to template-ize the dimension but you can't cast the pointer of one dimension to the pointer of another. A: I think I found! template<int DIM> class Vector{ public: double data[DIM]; }; static void *myVariable; template<int DIM> void func() { ((Vector<DIM>*)myVariable)->data[0] = 0.; // or perform any other operation on myVariable } int main() { int dim = 3; if (dim==3) { myVariable = (void*) new Vector<3>(); func<3>(); } else { myVariable = (void*) new Vector<4>(); func<4>(); } } A: Vector<3> and Vector<4> are entirely different types and have no formal relation to one another. The fact that they are superficially similar from your point of view doesn't matter. If you want them to be equivalent up to a certain type, we have a name for that: interfaces template <typename Scalar = float> class BasicVector { public: typedef Scalar * iterator; virtual ~ BasicVector () {} virtual size_t size () const = 0; virtual iterator begin () = 0; virtual iterator end () = 0; }; template <unsigned N, typename Scalar = float> class Vector : public BasicVector <Scalar> { Scalar m_elements [N]; public: using Scalar :: iterator; size_t size () const {return N;} iterator begin () {return m_elements;} iterator end () {return m_elements + N;} }; int main () { BasicVector * a; a = new Vector <3>; a = new Vector <4>; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rails 3 - routes for admin section I am building my first admin section in Rails and I am struggling with routing problems. My routes.rb looks like this: get "admin/menuh" get 'admin/welcome' namespace :admin do resources :users resources :menuh resources :menuv resources :welcome end And my views structure looks like views/admin/users/files. If I will set to url address of browser the url localhost:3000/admin/users/new, so I will get the error message No route matches {:controller=>"users"} (it's in the file views/admin/users/_form.html.erb - this file is generated by scaffold)... so I would like to ask you - where is the problem? Is here anything important, what I am disregarding? A: You've set up your form_for like this, I reckon: <%= form_for @user do |f| %> Because the route is in a namespace, you need to tell the form that also: <%= form_for [:admin, @user] do |f| %> That should help you fix that issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you save file on server? I am saving images on file and i am creating first folder which has Guid name for avoiding to duplicate file names. And entities hold reference src of image. I feel that creating folder and giving guid name is wrong from point of performance. So how i have to avoid duplicate names ? And second problem is the project seperated into 2 project. One is admin and other for user interface so i can not access my saved files from user interface. What is best practice about these problems ? A: About the first problem, I think you could create a folder per user and replace the existing file, asking user confermation. The second problem can be solved using a NFS or a shared directory where the admin and the user application can both read and write files (and you need to develope a component that retrieve the files and return them to your web apps).
{ "language": "en", "url": "https://stackoverflow.com/questions/7518531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Immediately accessing an object's property Given these four examples of defining an object and then attempting to immediately access their properties: {foo: 'bar'}.foo // syntax error: unexpected_token I expected this would return the value of 'foo', but it results in a syntax error. The only explanation I can come up with is that the object definition hasn't been executed and therefore is not yet an object. It seems that the object definition is therefore ignored and the syntax error comes from attempting to execute just: .foo // results in the same syntax error: unexpected_token Similarly: {foo: 'bar'}['foo'] // returns the new Array ['foo'] Which seems to be evidence that the object literal is ignored and the trailing code is executed. These, however, work fine: ({foo: 'bar'}).foo // 'bar' ({foo: 'bar'})['foo'] // 'bar' The parentheses are used to run the line of code and since the result of that parenthetical operator is the instantiated object, you can access properties. So, why is the object definition ignored and not executed immediately? A: It's not ignored, it's just not recognized as an object here. { ... } at the start of a statement is parsed as a Block[spec] of code. In the case of {foo: 'bar'}.foo, the inner code foo: "bar" is parsed as a LabelledStatement[spec]. So {foo: 'bar'} parses correctly (even if it doesn't do what you expect) but the property access syntax is actually causing the syntax error, as accessing a property on a block is not valid. As you noticed the solution is to enclose the object in parentheses: ({foo: 'bar'}).foo Starting the statement with ( causes the parser to search for an expression inside of the parentheses. {foo: 'bar'} when parsed as an expression is an Object Initializer[spec], as you expected. For {foo: 'bar'}['foo'], it's actually parsed as two separate statements: a block ({foo: 'bar'} and an Array initializer (['foo']): {foo: 'bar'}; ['foo']; A: It's a matter of the "context", your first two examples are not object literals! They are statement blocks, for example: { foo: 'bar' } The above code is evaluated as a block, containing a labelled statement (foo) that points to an expression statement (the string literal 'bar'). When you wrap it on parentheses, the code is evaluated in expression context, so the grammar matches with the Object Literal syntax. In fact there are other ways to force the expression evaluation, and you will see that the dot property accesor notation works when applied directly to an object literal e.g.: ({foo:'bar'}.foo); // 'bar' 0, {foo:'bar'}.foo; // 'bar' 0||{foo:'bar'}.foo; // 'bar' 1&&{foo:'bar'}.foo; // 'bar' // etc... Now in your second example: {foo: 'bar'}['foo'] What happens here is that the two statements are evaluated, first the block and then the expression statement that contains the Array literal. Is a syntax ambiguity similar to what happens with function expressions vs function declarations. See also: * *SyntaxError or no SyntaxError
{ "language": "en", "url": "https://stackoverflow.com/questions/7518538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using DOS batch script: find a line in a properties file and replace text Trying to replace a string in a properties file on a certain line by using a batch file. I know that this can be done WITHOUT the use of a temp file, as I have seen it before, but forgotten how to do it. I know that if I have a var.properties file that contains this: CLASSPATH=bsh.jar;other.jar VARTEST=dummy ANOTHERVAR=default I am trying to update the CLASSPATH value in the .properties file without changing the order of the properties file. This is a properties file and so I believe the answer would be related to using: for /f "tokens=1,2* delims==" %%i in (var.properties) do ( @echo Key=%%i Val=%%j ) A: Instead of findstr use find with the /v and /i switches on "classpath". This will OMIT returning the line with classpath in it, then you can echo what you want in the file along w/VARTEST=dummy SET NEWVAL=CLASSPATH=test.jar SET FILE=think.properties FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%FILE%" ^|FIND /V /I "classpath"`) DO ( ECHO CLASSPATH=%NEWVAL%>>"%FILE%" ECHO %%A>>"%FILE%" ) EDIT: SETLOCAL ENABLEDELAYEDEXPANSION SET NEWVAL=test.jar SET OLDFILE=OLD_think.properties SET NEWFILE=think.properties SET COUNT=1 MOVE "%NEWFILE%" "%OLDFILE%" FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%OLDFILE%" ^|FIND /C /I "classpath"`) DO ( SET LINE=%%A ) FOR /F "USEBACKQ tokens=*" %%A IN (`FIND /V "" ^<"%OLDFILE%"`) DO ( IF %COUNT% NEQ %LINE% (ECHO %%A>>"%NEWFILE%") ELSE (ECHO %NEWVAL%>>"%NEWFILE%") SET /a COUNT=!COUNT!+1 ) Basically states, * *rename think.properties to OLD_think.properties *read OLD_think.properties and find the line number with string "classpath" in it and set it to variable LINE *Find all lines in OLD_think.properties, and echo them into think.properties. once you reach the line where your "CLASSPATH" string existed, it inserts the new line you wanted to replace it with, and everything else stays the same. A: I finally broke down and accepted a method using a "temp" file. Using delayed expansion with the '!' character solved my question. Much of this success was due to input by mecaflash . You can call this script with: CALL Script.bat PropKey NewPropValue Filename @echo off :: script for updating property files SETLOCAL EnableExtensions SETLOCAL EnableDelayedExpansion if "%3"=="" ( ECHO Script will optionally accept 3 args: PropKey PropVal File SET PROPKEY=UseCompression SET PROPVAL=false SET FILE=config.properties ) ELSE ( SET PROPKEY=%1 SET PROPVAL=%2 SET FILE=%3 ) FINDSTR /B %PROPKEY% %FILE% >nul IF %ERRORLEVEL% EQU 1 GOTO nowork MOVE /Y "%FILE%" "%FILE%.bak" FOR /F "USEBACKQ tokens=*" %%A IN (`TYPE "%FILE%.bak" ^|FIND /N /I "%PROPKEY%"`) DO ( SET LINE=%%A ) FOR /F "tokens=1,2* delims=]" %%S in ("%LINE%") DO SET LINE=%%S SET /A LINE=%LINE:~1,6% SET /A COUNT=1 FOR /F "USEBACKQ tokens=*" %%A IN (`FIND /V "" ^<"%FILE%.bak"`) DO ( IF "!COUNT!" NEQ "%LINE%" ( ECHO %%A>>"%FILE%" ) ELSE ( ECHO %PROPKEY%=%PROPVAL%>>"%FILE%" ECHO Updated %FILE% with value %PROPKEY%=%PROPVAL% ) SET /A COUNT+=1 ) GOTO end :nowork echo Didn't find matching string %PROPKEY% in %FILE%. No work to do. pause :end
{ "language": "en", "url": "https://stackoverflow.com/questions/7518539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are there validation rules for UniqueIdentifiers in SQL Server? Supposing I've got a bit of SQL that filters data by a column which is of type UniqueIdentifier. Select * from core.Pages WHERE PageId = '1DC4E71C-4E68-489D-A837-2C9BA8DCC1DC' (This guid was generated by the NewID() function) For the purposes of a quick test/sanity check I thought I'd replace one of the characters with an 'x' and run the query again. Imagine my surprise when I got an error message: Conversion failed when converting from a character string to uniqueidentifier. I thought GUID or UniqueIdentifier was unlimited in its scope ie. any alphanumeric character could be replaced with any other but it seems that SQL Server has its own ideas about what constitutes a GUID. Any use of the letter 'X' generates this error. Other characters don't seem to upset the RDBMS. Can anyone explain this? A: GUIDs are a hexidecimal number - it's not just "any character can be used to replace any other character", the resulting string must be a valid hexidecimal number. It's not the GUID itself that is necessarily unique, it's that the range of numbers that the GUID can represent (2^128) that the odds of the same GUID being generated twice within a system are negligible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a more elegant way of switching templates based on the user-agent, in JSF? We have a web application written with JSF and are trying to add a mobile version to it. Ideally, we'd have a separate folder with templates, CRUD and resources (e.g. jQuery Mobile) and our landing page would be able to choose the appropriate template based on the user-agent attribute of the header. One way would be to use a scriptlet and redirect to mobile/index.xhtml - end of story, but people don't like scriptlets :D Another way would be to wrap the content of the landing page (includind the templated parts) in a panelGroup with rendered="#{mobileDetector.isMobile()}", having a backing bean perform what the scriptlet would have done otherwise. But I think it kind of cripples the templates, plus it doesn't apply to the head section. So - is there a better way? A: Either use a separate subdomain, e.g. mobile.example.com for mobile users and (www.)example.com for desktop users, and/or sniff the user agent. There are public APIs available on: * *http://user-agent-string.info *http://www.useragentstring.com Alternatively, you can use CSS to hide/change parts of the the HTML markup based on the media type. <link rel="stylesheet" href="css/desktop.css" media="screen,projection"> <link rel="stylesheet" href="css/mobile.css" media="handheld"> <link rel="stylesheet" href="css/print.css" media="print"> <link rel="stylesheet" href="css/iphone.css" media="all and (max-device-width: 480px)"> <link rel="stylesheet" href="css/ipad-portrait.css" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)"> <link rel="stylesheet" href="css/ipad-landscape.css" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)">
{ "language": "en", "url": "https://stackoverflow.com/questions/7518543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: YouTube video on Flash Banner CS4 AS3 I am trying to make a flash banner in CS4 with AS3. In this banner I have to embed youtube videos. My problem is.. after the video loaded I cant have/see usual controls (fullscreen, pause, stop, etc) on the video.. and the video has the autoplay by default. I am using this code: Security.allowDomain("*"); Security.allowDomain("www.youtube.com"); Security.allowDomain("youtube.com"); Security.allowDomain("s.ytimg.com"); Security.allowDomain("i.ytimg.com"); var my_player1:Object; var my_loader1:Loader = new Loader(); my_loader1.load(new URLRequest("http://www.youtube.com/apiplayer?version=3")); my_loader1.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit); function onLoaderInit(e:Event):void{ addChild(my_loader1); my_player1 = my_loader1.content; my_player1.addEventListener("onReady", onPlayerReady); } function onPlayerReady(e:Event):void{ my_player1.setSize(200,100); ///////////////////////////////// //this example is with parameter// //my_player1.loadVideoByUrl("http://www.youtube.com/v/ID-YOUTUBE?autohide=1&amp;autoplay=0&amp;fs=1&amp;rel=0",0); ////////////////////////////////// // this one is only the video id// my_player1.loadVideoByUrl("http://www.youtube.com/v/ID-YOUTUBE",0); } I was trying to pass the parameter in the url to try but seems to be is not working. I was checking too the google API for AS3 (http://code.google.com/apis/youtube/flash_api_reference.html) but honestly I dont find the way to implement that I need. Whats is the way to see this controls in the video?? Thank you :) A: I was trying different thing and I found a partial solution that i want to share with: Security.allowDomain("www.youtube.com"); Security.allowDomain("youtube.com"); Security.allowDomain("s.ytimg.com"); Security.allowDomain("i.ytimg.com"); Security.allowDomain("s.youtube.com"); var my_player1:Object; var my_loader1:Loader = new Loader(); //before I used that: //my_loader1.load(new URLRequest("http://www.youtube.com/apiplayer?version=3")); //Now is use this: my_loader1.load(new URLRequest("http://www.youtube.com/v/ID_VIDEO?version=3)); my_loader1.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit); function onLoaderInit(e:Event):void{ addChild(my_loader1); my_player1 = my_loader1.content; my_player1.addEventListener("onReady", onPlayerReady); } function onPlayerReady(e:Event):void{ my_player1.setSize(200,100); my_player1.loadVideoByUrl("http://www.youtube.com/v/ID_VIDEO",0); } Basically Instead of use the "Loading the chromeless player" I use the "Loading the embedded player" My problem now is How I can modify for example the size of the controls bar.. because is taking 35px height and I want to reduce it Thank
{ "language": "en", "url": "https://stackoverflow.com/questions/7518549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automate SHH commands using PuTTY I am trying to automate connecting to UNIX using PuTTY and sending commands. My team use this to execute a series of processes that can get really repetitive. I have already accomplished this using autoit v3, however I can only send commands to the putty window but not read anything from it, which doesn´t allow me to change the flow of the script based on command responses and to know exactly when a specific command executed (currently using Sleep()) A: Check out Plink on this page: http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html You can use Run, StdoutRead and StdinWrite to write input and read output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query to return rows where column does not contain a certain substring Is there something I can put in my WHERE clause to only select fields from a column where that field does not contain a certain string. In this case, I am looking through to make sure the codes in this particular field do not have a "cs" in it. The code could be something like cs023 or bg425, just to give you a little bit more of an idea what I'm looking to do. A: You can use WHERE [column] NOT LIKE '%cs%' Replace [column] with your column name. A: Just a couple of alternatives (for folks who like VB's InStr() or JS' .indexOf() type syntax). WHERE CHARINDEX('cs', [column]) = 0; ...or... WHERE PATINDEX('%cs%', [column]) = 0; You might also want to deal with NULL values: WHERE COALESCE([column], '') NOT LIKE '%cs%';
{ "language": "en", "url": "https://stackoverflow.com/questions/7518551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: TortoiseGit, Git SVN Rebase and FETCH_HEAD slowness When I do a Git SVN Rebase and the dialog window pops up to Pick, Squash, etc., the UpStream dropdown box always defaults to FETCH_HEAD now. Ideally I'd like it to point to remotes/git-svn instead. In addition, it takes almost a minute for the dialog box to stop updating (I'm assuming it's because FETCH_HEAD has a lot of things to parse). Is there a way to either get FETCH_HEAD to stop showing, make remotes/git-svn the default or get rid of FETCH_HEAD?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I create a virtual directory that points to a letter drive that doesn't have wwwroot directory? Greetings all and please forgive me if my question is too cheap. I have drives on our server, C:\ drive and D:\ drive. IIS is installed and configured. C:\drive has inetpub\wwroot D:\drive has only inetpub; no wwwroot. I am trying to create a virtual directory and have it point to the D:\ drive that doesn't have wwwroot directory. Will this still work or do I have need to move my physical files to C:\drive since it has wwwroot directory? Thanks in advance. A: Its just an Microsoft preference to put them in wwwroot You can point a virtual directory anywhere you wish. C:\Temp if you feel the need!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Blackberry RIM runtime code signing : can't make my appli signed, and don't start on device I've succed to download and install the 3 file for the RRT on Eclipse, Blackberry plug-in, version 1.3. After installing the keys, everything seem to be OK. I can clik on BlackBerry --> Sign -->Sign with Signature tool. On my project, when I click on this, nothing happend. Perhaps is it normal ? But nothing to do : on device (not on simulator), my appli alaways say "Error starting testappli : Module 'testappli' must be signed with the RIM Runtime Code Signing Key (RTT)" I've tried at home and at works, with differents keys, it's always the same. Perhaps something is wrong ? Thanks A: I had the same problem just the other night when I tried signing my first app for the first time. The top-level Blackberry > Sign > Sign with Signature Tool menu item doesn't work correctly. It compiles the project but does attempt to sign anything. What worked for me was to go into the Package Explorer, right-click on the project, and choose Blackberry > Sign with Signature Tool instead. That compiles and signs correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multithreading -- matching instances I want to run two XPath-Expressions concurrently on two revisions of a database which both return results from an Iterator/Iterable and match resulting nodes with nodes in a List. I think the best thing is to run both queries in two threads from an executorservice and save results from both threads in a BlockingQueue, whereas another Thread is going to sort the results from the BlockingQueue or actually saves the incoming nodes or nodeKeys in the right position. Then it's trivial to get the intersection of the resulting sorted List and another sorted List. Any other suggestions? I'm also free to use whatever technology I like (preferably Java). Guava is in the classpath, but I already thought about using Actors from Akka. Edit: An additional related question would be if it's faster to use InsertionSort in a pipeline manner (to process the generated XPath results right when they are received) or to wait until the whole result has been generated and use QuickSort or MergeSort. I think InsertionSort should be preferable regardless of the resulting number of elements. In general I hope sorting and then computing the intersection of two lists is faster than O(n^2) for the search of each item in the XPath result list, even if the list is divided by the number of CPU processors available. Edit: I've currently implemented the first part: final ExecutorService executor = Executors.newFixedThreadPool(2); final AbsTemporalAxis axis = new NextRevisionAxis.Builder(mSession).setRevision(mRevision) .setIncludeSelf(EIncludeSelf.YES).build(); for (final IReadTransaction rtx : axis) { final ListenableFuture<Void> future = Futures.makeListenable(executor.submit(new XPathEvaluation(rtx, mQuery))); future.addListener(new Runnable() { @Override public void run() { try { mSemaphore.acquire(); } catch (final InterruptedException e) { LOGWRAPPER.error(e.getMessage(), e); } } }, executor); } executor.shutdown(); final ExecutorService sameThreadExecutor = MoreExecutors.sameThreadExecutor(); sameThreadExecutor.submit(new XPathResult()); sameThreadExecutor.shutdown(); return null; The semaphore is initialized to 2 and in XPathEvaluation the resulting nodeKeys are added to a LinkedBlockingQueue. Then I'm going to sort the XPathResults denoted with the comment, which isn't implemented yet: private final class XPathResult implements Callable<Void> { @Override public Void call() throws AbsTTException, InterruptedException { while (true) { final long key = mQueue.take(); if (key == -1L) { break; } if (mSemaphore.availablePermits() == 0) { mQueue.put(-1L); } // Do InsertionSort. } return null; } } Without any JavaDoc, but I think at least it should work, what do you think? Do you have any preferable solutions or do I have made some mistakes so far? kind regards, Johannes A: Are you sure you need to do this concurrently? Can't you just build the two lists consecutively and after that perform your sorting/intersecting? - That would take a lot of complexity from the subject. I assume that intersecting cannot be done until both lists are filled completely, am I correct? Then, no queue or synchronization would be needed, just fill two lists/sets and, once done, process both full lists. But maybe I'm not quite getting your point...
{ "language": "en", "url": "https://stackoverflow.com/questions/7518564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When to use comma-separated values in a DB Column? OK, I know the technical answer is NEVER. BUT, there are times when it seems to make things SO much easier with less code and seemingly few downsides, so please here me out. I need to build a Table called Restrictions to keep track of what type of users people want to be contacted by and that will contain the following 3 columns (for the sake of simplicity): minAge lookingFor drugs lookingFor and drugs can contain multiple values. Database theory tells me I should use a join table to keep track of the multiple values a user might have selected for either of those columns. But it seems that using comma-separated values makes things so much easier to implement and execute. Here's an example: Let's say User 1 has the following Restrictions: minAge => 18 lookingFor => 'Hang Out','Friendship' drugs => 'Marijuana','Acid' Now let's say User 2 wants to contact User 1. Well, first we need to see if he fits User 1's Restrictions, but that's easy enough EVEN WITH the comma-separated columns, as such: First I'd get the Target's (User 1) Restrictions: SELECT * FROM Restrictions WHERE UserID = 1 Now I just put those into respective variables as-is into PHP: $targetMinAge = $row['minAge']; $targetLookingFor = $row['lookingFor']; $targetDrugs = $row['drugs']; Now we just check if the SENDER (User 2) fits that simple Criteria: COUNT (*) FROM Users WHERE Users.UserID = 2 AND Users.minAge >= $targetMinAge AND Users.lookingFor IN ($targetLookingFor) AND Users.drugs IN ($targetDrugs) Finally, if COUNT == 1, User 2 can contact User 1, else they cannot. How simple was THAT? It just seems really easy and straightforward, so what is the REAL problem with doing it this way as long as I sanitize all inputs to the DB every time a user updates their contact restrictions? Being able to use MySQL's IN function and already storing the multiple values in a format it will understand (e.g. comma-separated values) seems to make things so much easier than having to create join tables for every multiple-choice column. And I gave a simplified example, but what if there are 10 multiple choice columns? Then things start getting messy with so many join tables, whereas the CSV method stays simple. So, in this case, is it really THAT bad if I use comma-separated values? ****ducks**** A: You already know the answer. First off, your PHP code isn't even close to working because it only works if user 2 has only a single value in LookingFor or Drugs. If either of these columns contains multiple comma-separated values then IN won't work even if those values are in the exact same order as User 1's values. What do expect IN to do if the right-hand side has one or more commas? Therefore, it's not "easy" to do what you want in PHP. It's actually quite a pain and would involve splitting user 2's fields into single values, writing dynamic SQL with many ORs to do the comparison, and then doing an extremely inefficient query to get the results. Furthermore, the fact that you even need to write PHP code to answer such a relatively simple question about the intersection of two sets means that your design is badly flawed. This is exactly the kind of problem (relational algebra) that SQL exists to solve. A correct design allows you to solve the problem in the database and then simply implement a presentation layer on top in PHP or some other technology. Do it correctly and you'll have a much easier time. A: Suppose User 1 is looking for 'Hang Out','Friendship' and User 2 is looking for 'Friendship','Hang Out' Your code would not match them up, because 'Friendship','Hang Out' is not in ('Hang Out','Friendship') That's the real problem here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the right way to extend EditText to give it additional "default" functionality I'm wondering if it's possible to add functionality to EditText such that when I include my newly extended field in the layout xml, I don't have to then add any code to the Activity class to get it to behave in specific ways. For example, I'd like to make a EditPhone field which is just an EditText that has the added feature of listening for key events and modifying the field to include parenthesis and dashes in their appropriate locations. At the moment, I'm always having to include the listener code and attach it to the view, manually. But obviously the class has a ton of default behavior that is wrapped up in it (for example, it brings up the keyboard when you click it). So, I'm guessing it shouldn't be all that tough, but I'm not clear on what the steps would be to accomplish this. And to be clear, I don't need help with the Phone specific feature described above (I have that all worked out), I'm trying to understand how to extend View in a way that it takes on additional functionality by default, so as not to have to clutter my Activities with the same code over and over. A: Actually there is nothing complicated about that. Usually you would apply a InputFilter to your EditText in your code and this would do the job. But if you see a pattern in that and want a EditText which always behaves that way you could create a custom widget that way: public class PhoneEditText extends EditText { public PhoneEditText(Context context) { super(context); init(); } public PhoneEditText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PhoneEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { // set your input filter here } } In XML layout you would simply use the full path to your custom class instead EditText: <my.package.path.to.PhoneEditText attribute="value (all EditText attributes will work as they did before)" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7518573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: maven connecting to Sonar I have maven installed on my local machine and I'm trying to test out Sonar installed on a remote box. I found a few post online to configure settings.xml (maven\config\settings.xml) and append a profile entry...which I did but does not work <profile> <id>sonar</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- SERVER ON A REMOTE HOST --> <sonar.host.url>http://remotebox:9000</sonar.host.url> </properties> </profile> What is the cli way? I tried several options but nothing worked. I tried: mvn sonar:sonar http://remotebox:9000 What is the correct syntax? Thanks in advance. Damian PS. this works fine on the remote box where both maven and sonar are installed...i just want to try it my box to the remote box. A: Problem 1 As explained you need to specify the JDBC connection details, otherwise Sonar will attempt to talk to the embedded Derby instance, it assumes is running on localhost. Problem 2 Are you using Derby? Well, the default configuration of Derby does not accept remote connections, but only connections from the same host. The SONAR-1039 issue explains how to work-around this problem, but my advise would be to setup a full-blown database such as MySQL or Postgresql. A: Running sonar with mvn sonar:sonar -Dsonar.jdbc.url=jdbc:h2:tcp://ipaddr:9092/sonar -Dsonar.host.url=http://ipaddr:9000 ,where ipaddr is your remote host, seems to work. A: Up to Version 5.2 beside the sonar.host.url you also have to specify the database parameters as described here. That way it works for me. Configuration example <profile> <id>sonar</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- EXAMPLE FOR MYSQL --> <sonar.jdbc.url> jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8 </sonar.jdbc.url> <sonar.jdbc.username>sonar</sonar.jdbc.username> <sonar.jdbc.password>sonar</sonar.jdbc.password> <!-- optional URL to server. Default value is http://localhost:9000 --> <sonar.host.url> http://myserver:9000 </sonar.host.url> </properties> </profile> Since Version 5.2 this not not necessary anymore: Quote: Scanners don't access the database This is the biggest change of this new version: scanners (e.g. Sonar Runner) no longer access the database, they only use web services to communicate with the server. In practice, this means that the JDBC connection properties can now be removed from analysis CI jobs: sonar.jdbc.url, sonar.jdbc.username, sonar.jdbc.password A: Just the following works for sonar-maven-plugin:3.2: mvn sonar:sonar -Dsonar.host.url=http://<sonarqubeserver>:<port> A: I had some problem and then realized, I was running mavn on parent pom whereas sonar configuration was in a child pom, for which I wanted analysis report anyway, so running mvn sonar:sonar with child pom worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Runtime Error '9' Subscript out of range I have a macro that needs to open a few excel files and copy data from those files and paste them into the macro file in a sheet named "Consolidated". The macro goes to a specified path, counts the number of files in the folder and then loops through to open a file, copy the contents and then save and close the file. The macro runs perfectly on my system but not on the users systems. The error i am receiving during the looping process is "Runtime Error '9' Subscript out of range". The line on which this error pops up is Set wb = Workbooks.Open(Filename:=.FoundFiles(file_count)) At first i thought that the files might be opening slower than the code execution so i added wait time of 5 seconds before and after the above line...but to no avail. The code is listed below Sub grab_data() Application.ScreenUpdating = False Dim rng As Range srow = ThisWorkbook.Sheets("Consolidated Data").Cells(65536, 11).End(xlUp).Row 'Number of filled rows in column A of control Sheet ThisWorkbook.Sheets("Control Sheet").Activate rawfilepth = Sheets("Control Sheet").Cells(65536, 1).End(xlUp).Row 'Loop to find the number of excel files in the path in each row of the Control Sheet For folder_count = 2 To rawfilepth wkbpth = Sheets("Control Sheet").Cells(folder_count, 1).Value With Application.FileSearch .LookIn = wkbpth .FileType = msoFileTypeExcelWorkbooks .Execute filecnt = .FoundFiles.Count 'Loop to count the number of sheets in each file For file_count = 1 To filecnt Application.Wait (Now + TimeValue("0:00:05")) Set wb = Workbooks.Open(Filename:=.FoundFiles(file_count)) Application.Wait (Now + TimeValue("0:00:05")) filenm = ActiveWorkbook.Name For sheet_count = 1 To Workbooks(filenm).Sheets.Count If Workbooks(filenm).Sheets(sheet_count).Name <> "Rejected" Then Workbooks(filenm).Sheets(sheet_count).Activate ActiveSheet.Columns("a:at").Select Selection.EntireColumn.Hidden = False shtnm = Trim(ActiveSheet.Name) lrow = ActiveSheet.Cells(65536, 11).End(xlUp).Row If lrow = 1 Then lrow = 2 For blank_row_count = 2 To lrow If ActiveSheet.Cells(blank_row_count, 39).Value = "" Then srow = ActiveSheet.Cells(blank_row_count, 39).Row Exit For End If Next blank_row_count For uid = srow To lrow ActiveSheet.Cells(uid, 40).Value = ActiveSheet.Name & uid Next uid ActiveSheet.Range("a" & srow & ":at" & lrow).Copy ThisWorkbook.Sheets("Consolidated Data").Activate alrow = ThisWorkbook.Sheets("Consolidated Data").Cells(65536, 11).End(xlUp).Row ThisWorkbook.Sheets("Consolidated Data").Range("a" & alrow + 1).Activate ActiveCell.PasteSpecial xlPasteValues ThisWorkbook.Sheets("Consolidated Data").Range("z" & alrow + 1).Value = shtnm ThisWorkbook.Sheets("Consolidated Data").Range("z" & alrow + 1 & ":z" & (alrow+lrow)).Select Selection.FillDown ThisWorkbook.Sheets("Consolidated Data").Range("ap" & alrow + 1).Value = wkbpth ThisWorkbook.Sheets("Consolidated Data").Range("ap" & alrow + 1 & ":ap" & (alrow + lrow)).Select Selection.FillDown ThisWorkbook.Sheets("Consolidated Data").Range("ao" & alrow + 1).Value = filenm ThisWorkbook.Sheets("Consolidated Data").Range("ao" & alrow + 1 & ":ao" & (alrow + lrow)).Select Selection.FillDown Workbooks(filenm).Sheets(sheet_count).Activate ActiveSheet.Range("am" & srow & ":am" & lrow).Value = "Picked" ActiveSheet.Columns("b:c").EntireColumn.Hidden = True ActiveSheet.Columns("f:f").EntireColumn.Hidden = True ActiveSheet.Columns("h:i").EntireColumn.Hidden = True ActiveSheet.Columns("v:z").EntireColumn.Hidden = True ActiveSheet.Columns("aa:ac").EntireColumn.Hidden = True ActiveSheet.Columns("ae:ak").EntireColumn.Hidden = True End If Next sheet_count Workbooks(filenm).Close True Next file_count End With Next folder_count Application.ScreenUpdating = True End Sub Thanks in advance for your help. A: First off, make sure you have Option Explicit at the top of your code so you can make sure you don't mess any of your variables up. This way, everything is dimensioned at the beginning of your procedure. Also, use variables for your workbooks, it'll clean up the code and make it more understandable, also, use indenting. This worked for me, I found that I need to make sure the file isn't already open (assuming you aren't using an add-in) so you don't want to open the workbook with the code in it when it is already open): Sub grab_data() Dim wb As Workbook, wbMacro As Workbook Dim filecnt As Integer, file_count As Integer Application.ScreenUpdating = False Application.EnableEvents = False Set wbMacro = ThisWorkbook With Application.FileSearch .LookIn = wbMacro.Path .FileType = msoFileTypeExcelWorkbooks .Execute filecnt = .FoundFiles.Count 'Loop to count the number of sheets in each file For file_count = 1 To filecnt If wbMacro.FullName <> .FoundFiles(file_count) Then Set wb = Workbooks.Open(Filename:=.FoundFiles(file_count)) Debug.Print wb.Name wb.Close True End If Next file_count End With Application.EnableEvents = True Application.ScreenUpdating = True End Sub Hope that helps. Try this (hope I didn't mess any of it up), basically, I'm checking to make sure the directory exists also, and I cleaned up the code quite a bit to make it more understandable (mainly for myself): Sub grab_data() Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual Dim i As Long Dim lRow As Long, lRowEnd As Long, lFolder As Long, lFilesTotal As Long, lFile As Long Dim lUID As Long Dim rng As Range Dim sWkbPath As String Dim wkb As Workbook, wkbTarget As Workbook Dim wksConsolidated As Worksheet, wks As Worksheet Dim v1 As Variant Set wkb = ThisWorkbook Set wksConsolidated = wkb.Sheets("Consolidated Data") 'Loop to find the number of excel files in the path in each row of the Control Sheet For lFolder = 2 To wksConsolidated.Cells(65536, 1).End(xlUp).Row sWkbPath = wksConsolidated.Cells(lFolder, 1).Value 'Check if file exists If Not Dir(sWkbPath, vbDirectory) = vbNullString Then With Application.FileSearch .LookIn = sWkbPath .FileType = msoFileTypeExcelWorkbooks .Execute lFilesTotal = .FoundFiles.Count 'Loop to count the number of sheets in each file For lFile = 1 To lFilesTotal If .FoundFiles(lFile) <> wkb.FullName Then Set wkbTarget = Workbooks.Open(Filename:=.FoundFiles(lFile)) For Each wks In wkbTarget.Worksheets If wks.Name <> "Rejected" Then wks.Columns("a:at").EntireColumn.Hidden = False lRowEnd = Application.Max(ActiveSheet.Cells(65536, 11).End(xlUp).Row, 2) v1 = Application.Transpose(wks.Range(Cells(2, 39), Cells(lRowEnd, 39))) For i = 1 To UBound(v1) If Len(v1(i)) = 0 Then lRow = i + 1 Exit For End If Next i v1 = Application.Transpose(wks.Range(Cells(lRow, 40), Cells(lRowEnd, 40))) For lUID = 1 To UBound(v1) v1(lUID) = wks.Name & lUID Next lUID Application.Transpose(wks.Range(Cells(lRow, 40), Cells(lRowEnd, 40))) = v1 wks.Range("a" & lRow & ":at" & lRowEnd).Copy i = wksConsolidated.Cells(65536, 11).End(xlUp).Row With wksConsolidated .Range("A" & i).PasteSpecial xlPasteValues Application.CutCopyMode = False .Range("z" & i + 1).Value = wks.Name .Range("z" & i + 1 & ":z" & i + lRowEnd).FillDown .Range("ap" & i + 1) = sWkbPath .Range("ap" & i + 1 & ":ap" & i + lRowEnd).FillDown .Range("ao" & i + 1) = wkbTarget.FullName .Range("ao" & i + 1 & ":ao" & (i + lRowEnd)).FillDown End With With wks .Range("am" & lRow & ":am" & lRowEnd) = "Picked" .Columns("b:c").EntireColumn.Hidden = True .Columns("f:f").EntireColumn.Hidden = True .Columns("h:i").EntireColumn.Hidden = True .Columns("v:z").EntireColumn.Hidden = True .Columns("aa:ac").EntireColumn.Hidden = True .Columns("ae:ak").EntireColumn.Hidden = True End With End If Next wks wkbTarget.Close True End If Next lFile End With End If Next lFolder Application.ScreenUpdating = True Application.EnableEvents = True Application.Calculation = xlCalculationAutomatic End Sub A: There may be two issues here The macro runs perfectly on my system but not on the users systems I presume you are running this in xl2003 as Application.FileSearch was deprecated in xl2007. So you are probably best advised to use a Dir approach instead to ensure your code works on all machines. Are you users all using xl2003? You will get a "Object doesn't support this action" error in xl2007/10 The error i am receiving during the looping process is "Runtime Error '9' Subscript out of range Is this error occuring on your machine, or on one/all of the user machines? A: Ok guys, I have finally been able to figure out the problem. This error is occuring because some of the files in the raw data folder are corrupted and get locked automatically. So when the macro on opening the file gets an error and stops there. I have now made a change to the macro. It would now first check if the files are all ok to be imported. If there is a corrupt file then it would list down their names and the user will be required to manually open it and then do a "save As" and save a new version of the corrupt file and then delete it. Once this is done then the macro does the import of the data. I am putting down the code below for testing the corrupt files. Sub error_tracking() Dim srow As Long Dim rawfilepth As Integer Dim folder_count As Integer Dim lrow As Long Dim wkbpth As String Dim alrow As Long Dim One_File_List As String Application.ScreenUpdating = False Application.DisplayAlerts = False ThisWorkbook.Sheets("Control Sheet").Activate rawfilepth = Sheets("Control Sheet").Cells(65536, 1).End(xlUp).Row Sheets("Control Sheet").Range("E2:E100").Clear 'Loop to find the number of excel files in the path 'in each row of the Control Sheet For folder_count = 2 To rawfilepth wkbpth = Sheets("Control Sheet").Cells(folder_count, 1).Value One_File_List = Dir$(wkbpth & "\*.xls") Do While One_File_List <> "" On Error GoTo err_trap Workbooks.Open wkbpth & "\" & One_File_List err_trap: If err.Number = "1004" Then lrow = Sheets("Control Sheet").Cells(65536, 5).End(xlUp).Row Sheets("Control Sheet").Cells(lrow + 1, 5).Value = One_File_List Else Workbooks(One_File_List).Close savechanges = "No" End If One_File_List = Dir$ Loop Next folder_count If Sheets("Control Sheet").Cells(2, 5).Value = "" Then Call grab_data Else MsgBox "Please check control sheet for corrupt file names.", vbCritical, "Corrupt Files Notification" End If Application.DisplayAlerts = True Application.ScreenUpdating = True End Sub This may not be one of the cleanest codes around, but it gets the job done. For those who have been troubled by this problem this is one of the ways to get around this problem. For those who havae a better way of doing this please respond with your codes. Thanks to all for helping me out!!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Conditional Statements (please see explanation) Ok, I have three conditions here. It's seems pretty simple, but I can't get it working how I want, bear with me as I try to explain it. If(conditionA){ Play Sound 1} If(conditionB) { changedrawable ///(irrelevant) } If(conditionA && conditionB){ Play sound 2 } ////Unfortunately, since condition A is true, it plays sound 1 too, and I only want it to play sound 2 FWIW These conditions are just coordinates on the touchscreen, and I have them set up as boolean's Boolean conditionA; conditionA = y > 0 && y < (0.2 * tY) && x > 0 && x < (0.1667 * tX) || y2 > 0 && y2 < (0.2 * tY) && x2 > 0 && x2 < (0.1667 * tX); ConditionA and ConditionB are referring to different points on the touchscreen. The main question: how on earth can I get it so when conditionA and conditionB are BOTH true, ONLY Play Sound 2 (instead of both sounds)? I have been pulling my hair out the last day trying to figure this out. Please let me know if there is a solution or if you need further details. Thanks! A: This may not be perfectly optimal, but it's easy to read: if (conditionA && conditionB) { play sound 2 } else if (conditionA) { // Implies that conditionB == false play sound 1 } else if (conditionB) { change drawable } A: How about: if (conditionA && conditionB) { // play sound2 } else if (conditionA) { // play sound1 } else if (conditionB) { // change drawable } If both conditions aren't satisfied, it'll run the code for the condition that is. If they are both satisfied, it'll only run //play sound2. A: Just put the third option as the first, and then use else ifs in case not both conditions are fulfilled. edit/ what he says :) A: This may not be the most elegant solution, but it should work: if (conditionA && conditionB) { play sound 2 } else { if (conditionA){ play sound 1 } if (conditionB) { change drawable } } A: Shouldn't it be if(conditionA && conditionB) { play sound 2 } else if(conditionA) { play sound 1 } if(conditionB) { change drawable } You only want the else if for playing the sound. Not for changing the drawable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVCContrib Grid - Sort(GridSortOptions, prefix) not generating links for sorting I'm trying to use two grids in the same page and following what I found here: http://mvccontrib.codeplex.com/workitem/7032 Has anyone else had a problem with the Sort() method not generating links? The sorting was working before but it was sorting both grids the same way. The only thing I have changed is added the Bind attributes as the page above instructs and added the prefix to the call to Sort. A: So the mvccontrib grid code checks if the SortOptions has been populated and if the column is sortable. If false, no links. Apparently the BindAttribute causes the default model binder to NOT populate the paramter objects first time through which in this case meant my GridSortOption parameters were both null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any mechanism in Shell script alike "include guard" in C++? let's see an example: in my main.sh, I'd like to source a.sh and b.sh. a.sh, however, might have already sourced b.sh. Thus it will cause the codes in b.sh executed twice. Is there any mechanism alike "include guard" in C++? A: If you're sourcing scripts, you are usually using them to define functions and/or variables. That means you can test whether the script has been sourced before by testing for (one of) the functions or variables it defines. For example (in b.sh): if [ -z "$B_SH_INCLUDED" ] then B_SH_INCLUDED=yes ...rest of original contents of b.sh fi There is no other way to do it that I know of. In particular, you can't do early exits or returns because that will affect the shell sourcing the file. You don't have to use a name that is solely for the file; you could use a name that the file always has defined. A: In bash, an early return does not affect the sourcing file, it returns to it as if the current file were a function. I prefer this method because it avoids wrapping the entire content in if...fi. if [ -n "$_for_example" ]; then return; fi _for_example=`date` A: TL;DR: Bash has a source guard mechanism which lets you decide what to do if executed or sourced. Longer version: Over the years working with Bash sourcing I found that a different approach worked excellently which I will discuss below. The problem for me was similar to the one of the original poster: * *sourcing other scripts led to double script execution *additionally, scripts are less testable with unit test frameworks like BATS The main idea of my solution is to write scripts in a way that can safely sourced multiple times. A major part plays the extraction of functionality (compared to have a large script which would not render very testable). So, only functions and global variables are defined, other scripts can be sourced at will. As an example, consider the following three bash scripts: main.sh #!/bin/env bash source script2.sh source script3.sh GLOBAL_VAR=value function_1() { echo "do something" function_2 "completely different" } run_main() { echo "starting..." function_1 } # Enter: the source guard # make the script only run when executed, not when sourced) if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then run_main "$@" fi script2.sh #!/bin/env bash source script3.sh ALSO_A_GLOBAL_VAR=value2 function_2() { echo "do something ${1}" } # this file can be sourced or be executed if called directly if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then function_2 "$@" fi script3.sh #!/bin/env bash export SUPER_USEFUL_VAR=/tmp/path function_3() { echo "hello again" } # no source guard here: this script defines only the variable and function if called but does not executes them because no code inside refers to the function. Note that script3.sh is sourced twice. But since only functions and variables are (re-)defined, no functional code is executed during the sourcing. The execution starts with with running main.sh as one would expect. There might be a drawback when it comes to dependency cycles (in general a bad idea): I have no idea how Bash reacts if files source (directly or indirectly) each other. A: Personally I usually use set +o nounset # same as set -u on most of my scripts, therefore I always turn it off and back on. #!/usr/bin/env bash set +u if [ -n "$PRINTF_SCRIPT_USAGE_SH" ] ; then set -u return else set -u readonly PRINTF_SCRIPT_USAGE_SH=1 fi If you do not prefer nounset, you can do this [[ -n "$PRINTF_SCRIPT_USAGE_SH" ]] && return || readonly PRINTF_SCRIPT_USAGE_SH=1
{ "language": "en", "url": "https://stackoverflow.com/questions/7518584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Access widgets in a VerticalPanel in Google Apps Scripts? Is there a way to access the widgets within a panel in GAS? Something like: function clickHandler_(e) { var app = UiApp.getActiveApplication(); var panel = app.getElementById(e.parameter.whatever); // short-cutting here for (var i=0; i<panel.widgets.length; i++) { var widget = panel.widgets[i]; // do something with them } return app; } A: There isn't something simple like this. You have to give all widgets an id when adding them and save them somewhere so you can retrieve it later. For example, as a tag on the panel: function doGet(e) { var app = UiApp.createApplication(); ... var panel = app.createXYZPanel().setId('mypanel'); var IDs = ''; //list of child widgets on this panel panel.add(widget.setId('id1')); IDs += ',id1'; panel.add(widget2.setId('id2')); IDs += ',id2'; //and so on... panel.setTag(IDs); //save the IDs list as a tag on the panel ... return app; } //...later on a handler function handler(e) { var app = UiApp.getActiveApplication(); //the panel or a parent must be added as callback of the handler var IDs = e.parameter.mypanel_tag.split(','); for( var i = 1; i < IDs.length; ++i ) { //skipping the 1st empty element var widget = app.getElementById(IDs[i]); //do something } return app; } By the way, you probably know that, but your code had a mistake: It's not UiApp.getElementById, but app.getElementById.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does a function like this already exist? (Or, what's a better name for this function?) I've written code with the following pattern several times recently, and was wondering if there was a shorter way to write it. foo :: IO String foo = do x <- getLine putStrLn x >> return x To make things a little cleaner, I wrote this function (though I'm not sure it's an appropriate name): constM :: (Monad m) => (a -> m b) -> a -> m a constM f a = f a >> return a I can then make foo like this: foo = getLine >>= constM putStrLn Does a function/idiom like this already exist? And if not, what's a better name for my constM? A: Hmm, I don't think constM is appropriate here. map :: (a -> b) -> [a] -> [b] mapM :: (Monad m) => (a -> m b) -> [a] -> m b const :: b -> a -> b So perhaps: constM :: (Monad m) => b -> m a -> m b constM b m = m >> return b The function you are M-ing seems to be: f :: (a -> b) -> a -> a Which has no choice but to ignore its first argument. So this function does not have much to say purely. I see it as a way to, hmm, observe a value with a side effect. observe, effect, sideEffect may be decent names. observe is my favorite, but maybe just because it is catchy, not because it is clear. A: Well, let's consider the ways that something like this could be simplified. A non-monadic version would I guess look something like const' f a = const a (f a), which is clearly equivalent to flip const with a more specific type. With the monadic version, however, the result of f a can do arbitrary things to the non-parametric structure of the functor (i.e., what are often called "side effects"), including things that depend on the value of a. What this tells us is that, despite pretending like we're discarding the result of f a, we're actually doing nothing of the sort. Returning a unchanged as the parametric part of the functor is far less essential, and we could replace return with something else and still have a conceptually similar function. So the first thing we can conclude is that it can be seen as a special case of a function like the following: doBoth :: (Monad m) => (a -> m b) -> (a -> m c) -> a -> m c doBoth f g a = f a >> g a From here, there are two different ways to look for an underlying structure of some sort. One perspective is to recognize the pattern of splitting a single argument among multiple functions, then recombining the results. This is the concept embodied by the Applicative/Monad instances for functions, like so: doBoth :: (Monad m) => (a -> m b) -> (a -> m c) -> a -> m c doBoth f g = (>>) <$> f <*> g ...or, if you prefer: doBoth :: (Monad m) => (a -> m b) -> (a -> m c) -> a -> m c doBoth = liftA2 (>>) Of course, liftA2 is equivalent to liftM2 so you might wonder if lifting an operation on monads into another monad has something to do with monad transformers; in general the relationship there is awkward, but in this case it works easily, giving something like this: doBoth :: (Monad m) => ReaderT a m b -> ReaderT a m c -> ReaderT a m c doBoth = (>>) ...modulo appropriate wrapping and such, of course. To specialize back to your original version, the original use of return now needs to be something with type ReaderT a m a, which shouldn't be too hard to recognize as the ask function for reader monads. The other perspective is to recognize that functions with types like (Monad m) => a -> m b can be composed directly, much like pure functions. The function (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c) gives a direct equivalent to function composition (.) :: (b -> c) -> (a -> b) -> (a -> c), or you can instead make use of Control.Category and the newtype wrapper Kleisli to work with the same thing in a generic way. We still need to split the argument, however, so what we really need here is a "branching" composition, which Category alone doesn't have; by using Control.Arrow as well we get (&&&), letting us rewrite the function as follows: doBoth :: (Monad m) => Kleisli m a b -> Kleisli m a c -> Kleisli m a (b, c) doBoth f g = f &&& g Since we don't care about the result of the first Kleisli arrow, only its side effects, we can discard that half of the tuple in the obvious way: doBoth :: (Monad m) => Kleisli m a b -> Kleisli m a c -> Kleisli m a c doBoth f g = f &&& g >>> arr snd Which gets us back to the generic form. Specializing to your original, the return now becomes simply id: constKleisli :: (Monad m) => Kleisli m a b -> Kleisli m a a constKleisli f = f &&& id >>> arr snd Since regular functions are also Arrows, the definition above works there as well if you generalize the type signature. However, it may be enlightening to expand the definition that results for pure functions and simplify as follows: * *\f x -> (f &&& id >>> arr snd) x *\f x -> (snd . (\y -> (f y, id y))) x *\f x -> (\y -> snd (f y, y)) x *\f x -> (\y -> y) x *\f x -> x. So we're back to flip const, as expected! In short, your function is some variation on either (>>) or flip const, but in a way that relies on the differences--the former using both a ReaderT environment and the (>>) of the underlying monad, the latter using the implicit side-effects of the specific Arrow and the expectation that Arrow side effects happen in a particular order. Because of these details, there's not likely to be any generalization or simplification available. In some sense, the definition you're using is exactly as simple as it needs to be, which is why the alternate definitions I gave are longer and/or involve some amount of wrapping and unwrapping. A function like this would be a natural addition to a "monad utility library" of some sort. While Control.Monad provides some combinators along those lines, it's far from exhaustive, and I could neither find nor recall any variation on this function in the standard libraries. I would not be at all surprised to find it in one or more utility libraries on hackage, however. Having mostly dispensed with the question of existence, I can't really offer much guidance on naming beyond what you can take from the discussion above about related concepts. As a final aside, note also that your function has no control flow choices based on the result of a monadic expression, since executing the expressions no matter what is the main goal. Having a computational structure independent of the parametric content (i.e., the stuff of type a in Monad m => m a) is usually a sign that you don't actually need a full Monad, and could get by with the more general notion of Applicative. A: I don't really have a clue this exactly allready exists, but you see this a lot in parser-generators only with different names (for example to get the thing inside brackets) - there it's normaly some kind of operator (>>. and .>> in fparsec for example) for this. To really give a name I would maybe call it ignore? A: There's interact: http://hackage.haskell.org/packages/archive/haskell98/latest/doc/html/Prelude.html#v:interact It's not quite what you're asking for, but it's similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Memory Clean Up in Windows Phone Mango How i can implement memory clean up in WP7? Does GC.Collect() do the trick? or need clean up manually? A: You don't need to manually clean up memory on Windows Phone. You shouldn't call GC.Collect() unless it's absolutely necessary. I would recommend you read this article: Windows Phone 7 App Development: When does the GC run A: As Claus mentioned, the GC handles memory cleanup for you. If you are asking because you are running into memory usage issues, you can use the profile your memory usage using the Windows Phone Profiler (as long as you are targetting 7.1).
{ "language": "en", "url": "https://stackoverflow.com/questions/7518590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to group by a given column in a List of T collection using linq? Say I have a collection of IList<Products> products And I want to group by Product.Type in that collection, where Type is a Guid. Just thinking about it, I really just need to Order by the Product.Type, wouldn't ordering and grouping return the same results? A: Ordering and grouping are not the same thing, no. Grouping is generally implemented using ordering, but grouping implies the isolation of the items in the group from items in another group, whereas ordering merely arranges the items so that the items of one group are collected together in a particular section of the collection. For example: // Grouping var groups = products.GroupBy(x => x.Type); foreach (var group in groups) { Console.WriteLine("Group " + group.Key); foreach (var product in group) { // This will only enumerate over items that are in the group. } } // Ordering var ordered = products.OrderBy(x => x.Type); foreach (var product in ordered) { // This will enumerate all the items, regardless of the group, // but the items will be arranged so that the items with the same // group are collected together } A: There is an OrderBy extension method you could use. var orderedProducts = products.OrderBy(p => p.Type); Or for grouping, use GroupBy: var groupedProducts = products.GroupBy(p => p.Type); A: var list = from product in productList group product by product.Type;
{ "language": "en", "url": "https://stackoverflow.com/questions/7518596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: fail compile if required flags aren't present I have some legacy code that needs certain gcc flags passed in. Can I add pre-processor checks for these flags? For example, let's say I need -fno-strict-aliasing, can I do something like this: #ifndef _FNO_STRICT_ALIASING #error -fno-strict-aliasing is required! #endif A: You can use #pragma GCC optimize "no-strict-aliasing" to compile the file with that flag (overriding what was specified on the command line). You can also use __attribute__((optimize("no-strict-aliasing"))) to apply the flag to a single function within a source file... A: There is definitely no #define for it, at least on my version of GCC. To see all predefined preprocessor symbols: g++ -dM -E - < /dev/null I do not think there is any way to test these options. However, if you are using GCC 4.4 or later, you can use the "optimize" function attribute or the "optimize" #pragma to enable specific options on a per-function or per-file basis. For example, if you add this to a common header file: #if defined(__GNUC__) #pragma GCC optimize ("no-strict-aliasing") #else #error "You are not using GCC" #endif ...it should enable the option for every file that includes the header. [update] OK so it took me about 10 minutes too long to compose this answer. I am going to leave it here anyway for the links to the GCC docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Symfony2 Doctrine2 Translatable Strange behavior I have a question about a strange behavior in the Translatable extension. I have two tables, one called pages, and one called pages_translations in which I've the translation of my title|subtitle|text fields. When I save for the first time a record, in the table pages I've title|subtitle|text fields that contains my default locale, and in the pages_translations both English, Italian, French etc... If I change all the translation in my pages_translations table I've the right changed values, but in my pages tables I've have the old record with the first data saved. This is not a big problem because when I call getTitle() or similar Doctrine takes the right value in the pages_translations table, but I don't like having the old values in my pages tables, there is a way to update also the pages table or (better) delete the title|subtitle|text fields because this fields doctrine really don't need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asking for help to fix inline assembly issue in D program Hello I'm trying to use ASM in a little D program : asm { mov AX,12h ; int 10h ; } I've got this message : "end of instruction" from the two lines in the asm statement I cannot fix the issue, that's why I'me asking help from you. thanks for your answer I apologize for my english A: Since asm statements are embedded in D, you have to use D number syntax. That is, 0xNUMBER instead of NUMBERh for hexadecimal numbers. So, asm { mov AX, 0x12; int 0x10; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: I don't know how to "sort" arrays I have this array : array(2) { [1]=> array(4) { ["name"]=> string(14) "Les Contenants" ["ordre"]=> string(1) "3" [9]=> array(1) { ["name"]=> string(20) "Corbeilles unitaires" } [10]=> array(1) { ["name"]=> string(6) "Mannes" } } [6]=> array(3) { ["name"]=> string(7) "L'utile" ["ordre"]=> string(1) "1" [133]=> array(3) { ["name"]=> string(7) "Paniers" [192]=> array(1) { ["name"]=> string(13) "à provisions" } [193]=> array(2) { ["name"]=> string(13) "anses mobiles" [201]=> array(1) { ["name"]=> string(19) "non doublés tissus" } } } } } I need to sort this array on this key : array[$i]['ordre'] on an ascending order. The results must be : array(2) { [6]=> array(3) { ["name"]=> string(7) "L'utile" ["ordre"]=> string(1) "1" [133]=> array(3) { ["name"]=> string(7) "Paniers" [192]=> array(1) { ["name"]=> string(13) "à provisions" } [193]=> array(2) { ["name"]=> string(13) "anses mobiles" [201]=> array(1) { ["name"]=> string(19) "non doublés tissus" } } } } [1]=> array(4) { ["name"]=> string(14) "Les Contenants" ["ordre"]=> string(1) "3" [9]=> array(1) { ["name"]=> string(20) "Corbeilles unitaires" } [10]=> array(1) { ["name"]=> string(6) "Mannes" } } } Have you an idea to do it ? A: usort($array,function($a,$b) {return $a['ordre']-$b['ordre'];}); Or, if your version of PHP doesn't support lambda-functions: usort($array,create_function('$a,$b','return $a["ordre"]-$b["ordre"];'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7518604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse builder incompatible with m2Eclipse and Maven I'm seeing an issue where a given source file built by Maven produces a class file that is different than the one built by Eclipse. The Eclipse builder is optimising away the following method: public SomeClass clone() { SomeClass clone = (SomeClass) super.clone(); return clone; } This method is obviously unnecessary but I don't have the option to change the source because it is generated. Which builder is Eclipse using to compile these classes? I'm using the m2Eclipse plugin which I thought just invoked Maven to perform the build. Why is it that Eclipse then thinks it needs to perform another build with a different builder? Can I disable this Eclipse builder or configure it to prevent optimisation? * *Eclipse version: 3.7 *m2Eclipse version: 1.0.100.20110804-1717 (configured to use external Maven) *Maven version: 2.2.1 Update I found an Eclipse bug report that describes what is going on. To clarify, its not actually the Eclipse compiler that is removing anything, it is just not introducing a synthetic 'bridge' method that the standard JDK compiler introduces. The bug report is marked as Resolved- Won't Fix. I still haven't found a way to prevent the Eclipse builder from running after the Maven builder has run. But our fix is to modify the code generator to add an explicit serialVersionUID to the generated code. A: You could try disabling Java Builder if configured for the project. You can check this by clicking on Builders tab in Project -> Properties. From Eclipse help... The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification. A: I don't have Eclipse 3.7, but I expect that these things haven't changed since 3.6 . If you open Properties -> Builder on your project you should see that the Maven Builder comes last, or at least after the Java Builder. This means that when the Maven Builder sees your Java source files they are already compiled. By the way, the external Maven you configured is only used when you perform Run as -> and not when building with Maven. All this is to say that what you see is likely do to the fact that when you compile from within Eclipse the internal Java compiler is used, while when you run Maven from the command line I expect that a JDK compiler is used, depending on what you have installed. I don't think there's anything you can do to change this state of things. One thing you could try is to ensure that their behaviour is as close as possible by specifying in your POM which Java version to be compliant to by adding something like <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> To your build section. I have to say that I expected that the Java compiler was not allowed to remove public methods from classes, even if they are useless.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Writing Java equivalent of the Fortran program I have something like this in fortran. 20: call TESTBEGIN(a,b,c) if(c<1) goto 40 30: call TESTMIDDLE(e,f,g) if(g==1) goto 20 40: return But my code is like this Subroutine testCase() 20: CALL beginTest(a,b) IF (b.EQ.-1) GOTO 999 30: CALL middleTest(c,b) IF (b.EQ.-1) GOTO 20 40: CALL endTest(d,b) IF (b.EQ.-1) GOTO 30 CALL LastTest(e,b) IF (.b.EQ.-1) GOTO 40 DO I =1,j DTEMP(j)=1.0 END DO some code 999:return A: Something like that? do { c = TESTBEGIN(a,b); if (c < 1) break; g = TESTMIDDLE(e,f); } while ( g == 1 ); For the second code snippet try a state machine: for(int state = 1; state != 0; ) { switch(state) { case 1: state = (beginTest(a) == -1) ? 0 : 2; break; case 2: state = (middleTest(c) == -1) ? 1 : 3; break; case 3: state = (endTest(d) == -1) ? 2 : 4; break; case 4: state = (lastTest(e) == -1) ? 3 : 5; break; } case 5: state = 0; // DO I =1,j // Honestly I don't know what does it do. // DTEMP(j)=1.0 break; } Or better try to reconsider the algorithm, I think you could do it more easy to read and understand using Java.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using geometry shader to create new primitives types Is it possible to output new primitive type from geometry shader other than was input? I'd like to input a point and render a triangle. The point would be used just as center for this triangle. If not, is there other option to input just point and render some other piece of geometry defined by that point? With the help from answer here is geometry shader doing just what I asked for (if anyone ever needed): #version 120 #extension GL_EXT_geometry_shader4 : enable layout(points) in; layout(triangle_strip) out; void main() { gl_Position = gl_in[0].gl_Position; EmitVertex(); gl_Position = gl_in[0].gl_Position+vec4(1,0,0,0); EmitVertex(); gl_Position = gl_in[0].gl_Position+vec4(0, 1, 0, 0); EmitVertex(); EndPrimitive(); } A: Yes, this is perfectly possible, that's what the geometry shader is there for. Just specify the input primitive type as point and the output primitive type as triangle (or rather triangle strip, no matter if it's only a single triangle) using either glProgramParameteri in the application or using the more modern layout syntax directly in the shader.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: refresh window after facebook like I have created an app inside a company page to add more tabs/pages with a "like-gate" to ensure the user likes our page before moving forward. The like gate sits at a location say "index.php" if the user likes our page "index2.php" is included, in they do NOT like us "index1.php" is include instead. This all functions correctly. My problem is that I would like to include a "like" button inside the "index1.php" (if they dont like us) page. I included a button allowing the user to like us, but need to refresh after this button is clicked so the user can be evaluated at the like-gate again and redirect accordingly. The code below allows a user to like but does not redirect as I would like it to. I have look at the examples on the fb developer page but am new to fb app dev and cannot figure out my error. Any help would be appreciated, hopefully this is enough information, but reply if you need more. Thanks for any help you can provide. <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); FB.Event.subscribe('edge.create', function() { top.window.location = 'http://www.facebook.com/pages/TAG_Communications/122751567742494?sk=app_243094502403141'; } ); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like" data-href="http://www.facebook.com/pages/TAG_Communications/122751567742494" data-send="false" data-layout="button_count" data-width="450" data-show-faces="false"></div> A: Wow, I'm trying to do the exact same thing and was searching this at the same time you posted this question! Not much out there on this. I came across http://www.techjam.gr/2011/web-design/execute-javascript-facebook-button-clicked/ which explains what to do to run a callback script after the button is clicked very clearly. I see you already are doing this for the most part, but maybe there are a few pieces explained that you left out or didn't specify. Also I've run into a lot of trouble trying to redirect parent frames because it triggers a cross domain javascript access security error. Not sure if that's part of your problem. For my own case I plan to just redirect my iframe page from something like no-fan.php to fan.php on the click - I don't need to re-evaluate if they are a fan or not with my fangate code if they clicked the like button. Hope that helps you out. UPDATE: Got it working with help from the link above! Here's what I did (code below): Be sure to use the normal FB.init code. Add the callback script with the redirect code above the button. Add the xfbml version of the like button. That's it! Note that I did actually use top.window.location and sent it to my fangate evaluation code anyways. The reason is, if you just redirect the frame it leaves the rest of the page as is , and it still has the facebook like button near the title. Refreshing the whole page gets everything looking the way it should and avoids confusion. code: <div id="fb-root"></div> <script src="http://connect.facebook.net/en_US/all.js"></script> <script> FB.init({ appId :'your id here', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML channelUrl : 'full path to file', // channel.html file oauth : true // enable OAuth 2.0 }); </script> <script> FB.Event.subscribe('edge.create', function(href, widget) { top.window.location = 'your tab url'; }); </script> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like"><fb:like href="your page you want to like" send="false" layout="button_count" width="200" show_faces="false"></fb:like></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7518612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: use drawn image for game on iphone I want to use this user drawn image for the game that follows - i need it do be smaller and go to the top of the screen so that it can move left and right (to dodge objects). What do I do next? @implementation DrawView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code. } return self; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code. CGColorRef yellow = [[UIColor yellowColor] CGColor]; CGColorRef red = [[UIColor redColor] CGColor]; CGColorRef blue = [[UIColor blueColor] CGColor]; context = UIGraphicsGetCurrentContext(); // draw tryangle CGContextBeginPath(context); // give vertices CGContextMoveToPoint(context, point.x, point.y); CGContextAddLineToPoint(context, point.x+10, point.y); CGContextAddLineToPoint(context, point.x+10, point.y+10); CGContextAddLineToPoint(context, point.x, point.y+10); CGContextClosePath(context); // fill the path CGContextSetFillColorWithColor(context, red); CGContextFillPath(context); } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ touch=[[event allTouches]anyObject]; point= [touch locationInView:touch.view]; [self setNeedsDisplayInRect:CGRectMake(point.x, point.y, 10, 10)]; } - (void)dealloc { [super dealloc]; } @end A: As far as how to create a program that lets the user draw a picture, that's a bigger issue than stackoverflow questions are intended for. But let's assume you have got the user input and represented it as a set of points, colors, etc. You have the right idea to use drawRect to draw that variable content in your view. However, rather than redraw the content every time they move, just draw the content in the same place in the view and move the whole view. For example instead of drawing a square with corners (point.x, point.y), (point.x + 10, point.y), (point.x + 10, point.y + 10), (point.x, point.y + 10) draw a square with corners (0, 0), (10, 0), (10, 10), (0, 10) Then in touchesMoved instead of the line with setNeedsDisplay, write self.center = point; Also to make it smaller you can set the transform property of the view. So assume the view naturally draws itself large, the way the user drew it, then to make it much smaller you can write self.transform = CGAffineTransformMakeScale(0.1, 0.1); That will make it one tenth the size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Navigation menu to show current page link active - jquery I'm using the jquery accordion plugin, so far it works right but it displays the active link but they are not linking to any page, they are just using as a numbered link locator inside the same page. How can I make it to show the current page link active after I have clicked on it to open a new page? I'm new to JQuery and really need this to work. Please help! Here is the HTM, if you see the code youll find for example sub1 but how can I use a real page link and preserve de same link active state through the website <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Accordion Test</title> <link rel="stylesheet" href="accordionDemo.css" /> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript">google.load("jquery", "1");</script> <script type="text/javascript" src="../js/chili-1.7.pack.js"></script> <script type="text/javascript" src="../js/jquery.easing.js"></script> <script type="text/javascript" src="../js/jquery.dimensions.js"></script> <script type="text/javascript" src="../js//jquery.accordion.js"></script> <script type="text/javascript"> jQuery().ready(function(){ // simple accordion with mouseover event jQuery('#navigation').accordion ({ active: false, header: '.head', navigation: true, event: 'mouseover', fillSpace: true, animated: 'easeslide' }); }); </script> </head> <body> <div id="wrapper"> <div id="navBar"> <ul id="navigation"> <li> <a class="head" href="?p=1">About SfT</a> <ul> <li><a href="?p=1.1">sub1</a></li> <li><a href="?p=1.2">sub2</a></li> <li><a href="?p=1.3">sub3</a></li> <li><a href="?p=1.4.1">sub4</a></li> <li><a href="?p=1.4.2">sub4.1</a></li> <li><a href="?p=1.4.3">sub4.2</a></li> </ul> </li> <li> <a class="head" href="?p=1.2">Your Life</a> <ul> <li><a href="?p=1.2.1">sub1</a></li> <li><a href="?p=1.2.2">sub2</a></li> <li><a href="?p=1.2.3">sub3</a></li> <li><a href="?p=1.2.4">sub4</a></li> <li><a href="?p=1.2.5">sub5</a></li> </ul> </li> </ul> </div> </div> <!--end wrapper--> </body> </html> The CSS * { margin: 0; padding: 0; } body { margin: 0; padding: 0; font-size: small; color: #333 } #wrapper { width:600px; margin:0 auto; padding-top:100px; } #navBar { height:330px; margin-bottom:1em; } #navigation { margin:0px; padding:0px; text-indent:0px; /*background-color:#EFEFEF; sublists background color */ width:200px; } #navigation a.head { /* list header */ height: 40px; cursor:pointer; background: url(collapsed.gif) no-repeat scroll 3px 4px; /* list header bg color and img settings */ color:#999; display:block; font-weight:bold; font-size: 22px; margin:0px; padding:0px; text-indent:20px; text-decoration: none; } #navigation a.head:hover { color:#900; } #navigation a.selected { background-image: url(expanded.gif); color:#900; } #navigation a.current { color: #F60;; font-weight:bold; } #navigation ul { margin:0px; padding:0px; text-indent:0px; } #navigation li { list-style:none outside none; /*display:inline;*/ padding:5px 0 5px 0; height:0 auto; } #navigation li li a { color:#000000; display:block; font-size:16px; text-indent:20px; text-decoration: none; } #navigation li li a:hover { /* sublist hover state bg and color */ color:#F60;; font-weight:bold; } And the jquery.accordion.js code /* * jQuery UI Accordion 1.6 * * Copyright (c) 2007 Jörn Zaefferer * * http://docs.jquery.com/UI/Accordion * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.accordion.js 4876 2008-03-08 11:49:04Z joern.zaefferer $ * */ ;(function($) { // If the UI scope is not available, add it $.ui = $.ui || {}; $.fn.extend({ accordion: function(options, data) { var args = Array.prototype.slice.call(arguments, 1); return this.each(function() { if (typeof options == "string") { var accordion = $.data(this, "ui-accordion"); accordion[options].apply(accordion, args); // INIT with optional options } else if (!$(this).is(".ui-accordion")) $.data(this, "ui-accordion", new $.ui.accordion(this, options)); }); }, // deprecated, use accordion("activate", index) instead activate: function(index) { return this.accordion("activate", index); } }); $.ui.accordion = function(container, options) { // setup configuration this.options = options = $.extend({}, $.ui.accordion.defaults, options); this.element = container; $(container).addClass("ui-accordion"); if ( options.navigation ) { var current = $(container).find("a").filter(options.navigationFilter); if ( current.length ) { if ( current.filter(options.header).length ) { options.active = current; } else { options.active = current.parent().parent().prev(); current.addClass("current"); } } } // calculate active if not specified, using the first header options.headers = $(container).find(options.header); options.active = findActive(options.headers, options.active); if ( options.fillSpace ) { var maxHeight = $(container).parent().height(); options.headers.each(function() { maxHeight -= $(this).outerHeight(); }); var maxPadding = 0; options.headers.next().each(function() { maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height()); }).height(maxHeight - maxPadding); } else if ( options.autoheight ) { var maxHeight = 0; options.headers.next().each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }).height(maxHeight); } options.headers .not(options.active || "") .next() .hide(); options.active.parent().andSelf().addClass(options.selectedClass); if (options.event) $(container).bind((options.event) + ".ui-accordion", clickHandler); }; $.ui.accordion.prototype = { activate: function(index) { // call clickHandler with custom event clickHandler.call(this.element, { target: findActive( this.options.headers, index )[0] }); }, enable: function() { this.options.disabled = false; }, disable: function() { this.options.disabled = true; }, destroy: function() { this.options.headers.next().css("display", ""); if ( this.options.fillSpace || this.options.autoheight ) { this.options.headers.next().css("height", ""); } $.removeData(this.element, "ui-accordion"); $(this.element).removeClass("ui-accordion").unbind(".ui-accordion"); } } function scopeCallback(callback, scope) { return function() { return callback.apply(scope, arguments); }; } function completed(cancel) { // if removed while animated data can be empty if (!$.data(this, "ui-accordion")) return; var instance = $.data(this, "ui-accordion"); var options = instance.options; options.running = cancel ? 0 : --options.running; if ( options.running ) return; if ( options.clearStyle ) { options.toShow.add(options.toHide).css({ height: "", overflow: "" }); } $(this).triggerHandler("change.ui-accordion", [options.data], options.change); } function toggle(toShow, toHide, data, clickedActive, down) { var options = $.data(this, "ui-accordion").options; options.toShow = toShow; options.toHide = toHide; options.data = data; var complete = scopeCallback(completed, this); // count elements to animate options.running = toHide.size() == 0 ? toShow.size() : toHide.size(); if ( options.animated ) { if ( !options.alwaysOpen && clickedActive ) { $.ui.accordion.animations[options.animated]({ toShow: jQuery([]), toHide: toHide, complete: complete, down: down, autoheight: options.autoheight }); } else { $.ui.accordion.animations[options.animated]({ toShow: toShow, toHide: toHide, complete: complete, down: down, autoheight: options.autoheight }); } } else { if ( !options.alwaysOpen && clickedActive ) { toShow.toggle(); } else { toHide.hide(); toShow.show(); } complete(true); } } function clickHandler(event) { var options = $.data(this, "ui-accordion").options; if (options.disabled) return false; // called only when using activate(false) to close all parts programmatically if ( !event.target && !options.alwaysOpen ) { options.active.parent().andSelf().toggleClass(options.selectedClass); var toHide = options.active.next(), data = { instance: this, options: options, newHeader: jQuery([]), oldHeader: options.active, newContent: jQuery([]), oldContent: toHide }, toShow = options.active = $([]); toggle.call(this, toShow, toHide, data ); return false; } // get the click target var clicked = $(event.target); // due to the event delegation model, we have to check if one // of the parent elements is our actual header, and find that if ( clicked.parents(options.header).length ) while ( !clicked.is(options.header) ) clicked = clicked.parent(); var clickedActive = clicked[0] == options.active[0]; // if animations are still active, or the active header is the target, ignore click if (options.running || (options.alwaysOpen && clickedActive)) return false; if (!clicked.is(options.header)) return; // switch classes options.active.parent().andSelf().toggleClass(options.selectedClass); if ( !clickedActive ) { clicked.parent().andSelf().addClass(options.selectedClass); } // find elements to show and hide var toShow = clicked.next(), toHide = options.active.next(), //data = [clicked, options.active, toShow, toHide], data = { instance: this, options: options, newHeader: clicked, oldHeader: options.active, newContent: toShow, oldContent: toHide }, down = options.headers.index( options.active[0] ) > options.headers.index( clicked[0] ); options.active = clickedActive ? $([]) : clicked; toggle.call(this, toShow, toHide, data, clickedActive, down ); return false; }; function findActive(headers, selector) { return selector != undefined ? typeof selector == "number" ? headers.filter(":eq(" + selector + ")") : headers.not(headers.not(selector)) : selector === false ? $([]) : headers.filter(":eq(0)"); } $.extend($.ui.accordion, { defaults: { selectedClass: "selected", alwaysOpen: true, animated: 'slide', event: "click", header: "a", autoheight: true, running: 0, navigationFilter: function() { return this.href.toLowerCase() == location.href.toLowerCase(); } }, animations: { slide: function(options, additions) { options = $.extend({ easing: "swing", duration: 300 }, options, additions); if ( !options.toHide.size() ) { options.toShow.animate({height: "show"}, options); return; } var hideHeight = options.toHide.height(), showHeight = options.toShow.height(), difference = showHeight / hideHeight; options.toShow.css({ height: 0, overflow: 'hidden' }).show(); options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate({height:"hide"},{ step: function(now) { var current = (hideHeight - now) * difference; if ($.browser.msie || $.browser.opera) { current = Math.ceil(current); } options.toShow.height( current ); }, duration: options.duration, easing: options.easing, complete: function() { if ( !options.autoheight ) { options.toShow.css("height", "auto"); } options.complete(); } }); }, bounceslide: function(options) { this.slide(options, { easing: options.down ? "bounceout" : "swing", duration: options.down ? 1000 : 200 }); }, easeslide: function(options) { this.slide(options, { easing: "easeinout", duration: 700 }) } } }); })(jQuery); A: As I understand, you want the current page aka. the active link. I can see from your links href="" that you are using PHP platform for displaying the pages, not JS. So in that case, this has basically nothing to do with JS and most of your provided scripts are irrelevant. You want to do this with PHP and CSS. So basically, if you are using CMS type of software, while generating the menu.. you want to match the menus pageid with current pageid, inside the menu generating loop. So the basic idea behind the loop is something like this: foreach ($menus as $menu) { echo '<a href="?p=' . $menu['pageid'] . '"' . ($menu['pageid'] == $pageid ? ' class="active"' : '') . '>' . $menu['title'] . '</a>'; } So, the active link is being set via PHP and CSS gives it "pop". This is how everybody does it. Also, better to use this method, as you don't have to wait after the page load, so the JS would start working. Alternative However, if you want to.. You can use JS by setting a cookie, everytime user clicks on some link. So next page the active link will be set based on that cookie value. However, this is not recommended, as it will cause lag and will look overall.. not as good as PHP and CSS. In my example, you can see I'm using Klaus Hartl's Cookie Plugin.. However, I couldn't find a direct link to that plugin.. so I used one of my local ones. You can get the link in the resources. Example: http://jsfiddle.net/hobobne/qruXC/ This is a very raw example of the concept. Since your provided CSS is partial, then you can see.. it doesn't look pretty. I also, simply added the #navigation a.active {} to the CSS. I hope you get the idea and can go from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to control level of debugging info in glib? I have a library written in C with glib/gobject. It produces significant number of debugging information via g_debug() call. This info is very helpful for troubleshooting, however I do not want it to be shown, when library is included with actual application. So, basically I need a way to control/filter amount of debugging information and I could not figure out how it supposed to work with glib. Could someone point me in the right direction, please? A: I implemented custom log handler and here is how it turned out: void custom_log_handler (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) { gint debug_level = GPOINTER_TO_INT (user_data); /* filter out messages depending on debugging level */ if ((log_level & G_LOG_LEVEL_DEBUG) && debug_level < MyLogLevel_DEBUG) { return; } else if ((log_level & G_LOG_LEVEL_INFO) && debug_level < MyLogLevel_INFO) { return; } g_printf ("%s\n", message); } int main(int argc, char *argv[]) { ... if (verbose) { g_log_set_handler (NULL, G_LOG_LEVEL_MASK, custom_log_handler, GINT_TO_POINTER (MyLogLevel_DEBUG)); } else { g_log_set_handler (NULL, G_LOG_LEVEL_MASK, custom_log_handler, GINT_TO_POINTER (MyLogLevel_NORMAL)); } ... } I hope it will be helpful to somebody :-) A: You can control whether to print debug (log) messages with setting the G_MESSAGES_DEBUG environment variable when running your application. The easiest is to use $ G_MESSAGES_DEBUG=all ./your-app when you need debugging (log) messages to be printed. However, when G_MESSAGES_DEBUG=all glib libraries itself print debug (log) messages too which you may not need. So, predefine G_LOG_DOMAIN as a separate custom log domain string for your application and set G_MESSAGES_DEBUG to the same string when running. For example, use -DG_LOG_DOMAIN=\"my-app\" among compiler flags and run application with $ G_MESSAGES_DEBUG="my-app" ./your-app. A: You could try setting G_DEBUG environment variable as mentioned in the GLib developer site. Please refer to Environment variable section under Running and debugging GLib Applications in http://developer.gnome.org/glib/2.28/glib-running.html. EDIT: Update to set the logger in the code. You can use g_log_set_handler ( http://developer.gnome.org/glib/2.29/glib-Message-Logging.html#g-log-set-handler ) to do this in your code. Initially you can set the log handler to a dummy function which display nothings & then you can set the log handler to g_log_default_handler based on the argument passed for set appropriate log levels. To set the log levels above a set level you will need to manipulate GLogLevelFlags values as per your need. Hope the below code sample will provide some pointers #include <glib.h> #include <stdio.h> #include <string.h> #define G_LOG_DOMAIN ((gchar*) 0) static void _dummy(const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data ) { /* Dummy does nothing */ return ; } int main(int argc, char **argv) { /* Set dummy for all levels */ g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_MASK, _dummy, NULL); /* Set default handler based on argument for appropriate log level */ if ( argc > 1) { /* If -vv passed set to ONLY debug */ if(!strncmp("-vv", argv[1], 3)) { g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, g_log_default_handler, NULL); } /* If -v passed set to ONLY info */ else if(!strncmp("-v", argv[1], 2)) { g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_INFO, g_log_default_handler, NULL); } /* For everything else, set to back to default*/ else { g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_MASK, g_log_default_handler, NULL); } } else /* If no arguments then set to ONLY warning & critical levels */ { g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_WARNING| G_LOG_LEVEL_CRITICAL, g_log_default_handler, NULL); } g_warning("This is warning\n"); g_message("This is message\n"); g_debug("This is debug\n"); g_critical("This is critical\n"); g_log(NULL, G_LOG_LEVEL_INFO , "This is info\n"); return 0; } Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Removing a specific item from a BlockingCollection<> Is there a way to remove a specific item from a BlockingCollection, like this: IMyItem mySpecificItem = controller.getTopRequestedItem(); bool took = myBlockingCollection<IMyItem>.TryTake(out mySpecificItem); if(took) process(mySpecificItem); ..... in other words: I want to remove an item from a BlockingCollection<>, which is identified by some field (e.g. ID), not just the next item availible. Do I need to implement getHashCode() or an IComparer ? A: BlockingCollection<> won't help you here. I think you need ConcurrentDictionary<>. A: I think the answer to the straight question here is "no, there isn't". But I had the same underlying scenario problem. Below is how I solved it. TL;DR I used an array of BlockingCollections, with each array elements being for a different priority level. That seems like the simplest solution. It fits perfectly with the BlockingCollection methods available. I had the same challenge: a queue which occasionally gets higher priority elements added. When there are higher priority elements, they need to be handled before all the normal priority elements. Both higher priority elements, and normal priority elements need to respectively be handled in FIFO order within their priority buckets. For flexibility in how the processing is used, the priority levels should ideally not be a finite small set, but as you'll see below I ended up compromising on that need. The code I ended up with: In class declaration. This assumes we need 4 priority levels: BlockingCollection<ImageToLoad>[] imagesToLoad = new BlockingCollection<ImageToLoad>[4]; In class constructor (to create the 4 instances of BlockingCollection with fancy LINQ syntax - it's frankly easier to read when just written out as a 0->3 for loop :-) ): imagesToLoad = Enumerable.Repeat(0, 4).Select(bc => new BlockingCollection<ImageToLoad>()).ToArray(); When an element gets added to the work queue: imagesToLoad[priority].Add(newImageToLoad); The worker task, picking tasks with high prio (4 is higher prio than 3, etc.), and waking up from its no-work-queued block when work arrives in any of the 4 prio queues: while (true) { ImageToLoad nextImageToLoad = null; for (int i = 3; i >= 0; i--) if (imagesToLoad[i].TryTake(out nextImageToLoad)) break; if (nextImageToLoad == null) BlockingCollection<ImageToLoad>.TakeFromAny(imagesToLoad, out nextImageToLoad); if (nextImageToLoad != null) await LoadOneImage(nextImageToLoad); } BlockingCollection backed by a FIFO ConcurrentQueue is a great base for this. It lets you do a FirstOrDefault(Func predicate) to find items with higher priority. But, as mentioned in this question, it doesn't have a Remove(Func predicate) or a Take(Func predicate) method to get the higher priority items out of the queue when they have been processed out-of-order. I considered 4 solutions, in order of decreasing work and complexity: A. Writing my own version of BlockingCollection. This is the most elegant solution. I don't think it would be too bad in complexity when you only need Add, Take and Take(Func predicate), but it'll take time and there'll be at least some concurrency or lock bugs which will be hard to find. I would use a SemaphoreSlim to handle the blocking while waiting for new elements to arrive. I would probably use a OrderedDictionary to keep the elements in. B. Give up on BlockingCollection. Use a OrderedDictionary<> directly (similar to what David suggests above with a ConcurrentDictionary). The logic would be very similar to option A, just not encapsulated in a separate class. C. This is something of a hack: add a property to the elements which are getting queued, to indicate if the element has already been processed. When you process an element out-of-order due to it having higher priority, set this property to "already done with this one". When you later Take this element because it happens to become the one at the front of the queue, just discard it (instead of processing it, like you would do with elements you Take at the front of the queue, which haven't already been processed). This gets complex though, because: (1) you end up having to treat these elements which don't really belong in the BlockingCollection specially in many contexts. (2) confusing from a concurrency perspective, to rely partially on the locks inside BlockingCollection and BlockingCollection.Take(), and partially on the locks I need to add to do the logic around finding high-prio items and updating them. It'll be too easy to end up with deadlocks due to conflicts between the two separate locks. D. Instead of letting the number of priority levels be open-ended, lock it to just 2, or 3, or whatever I think I might need, and create that many separate BlockingCollections. You can then do the blocking with the TakeFromAny call. When not blocking (because there are elements already available when you're ready to process another one), you can inspect each BlockingCollection and Take from the highest priority one which isn't empty. I spent a fair bit of time trying to make option (C) work before realizing all the complexity it was creating. I ended up going with option (D). It would be straight forward to make the number of priority levels dynamic so it's set when the class is created. But making it completely run-time dynamic with priorities as any int is not practical with this approach, since there would be so many unused BlockingCollection objects created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Question about Unions and Memory Mgmt I'm confused about unions and how they allocate memory. Say I have: union Values { int ivalue; double dvalue; }; Values v; So I know the int uses 4 bytes and the double uses 8 bytes, so there are 8 bytes allocated in total (I think), with that said how much memory would v use? A: You've pretty much answered your own question: given a four-byte int and an 8-byte double, v would use 8 bytes of memory. If unsure, you could compile and run a simple program that'll print out sizeof(v). A: Given that int is 4 bytes and double is 8 bytes (which is not guaranteed by the language), sizeof (Values) is at least 8 bytes. Most commonly it will be exactly 8 bytes (more generally, sizeof (int) or sizeof (double), whichever is larger), but compilers are permitted to add unnamed padding to structs and unions. For structs, any such padding can be between any two mebers, or after the last one; for unions, it can only be at the end. The purpose of such padding is to allow for better alignment. For example, given: union u { char c[5]; int i; }; if int is 4 bytes and requires 4-byte alignment, the compiler will have to add padding to make sizeof (union u) at least 8 bytes. In your particular case, there's probably no reason to add any padding, but you shouldn't assume that there isn't any. If you need to know the size of the union, just use sizeof.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UTF-8 error with Cucumber feature I’m using Rails 3.0.7 and ruby 1.9.2 with cucumber and capybara. I just had this problem, and I can’t find a solution :( invalid byte sequence in US-ASCII (ArgumentError) :10:in synchronize' (eval):2:inclick_button' ./features/step_definitions/vouchers_company_steps.rb:25:in `/^I use it in my voucher UI$/' I think it has something to do with the form submission which is a GET and the famous utf8 tick. I don’t have this problem with my other forms. This one is using metasearch, I don’t know if it can help. A: add to the top of the file # encoding: utf-8 A: encoding: utf-8 didn’t help. I narrowed down the problem and found it occurs only within cucumber/capybara when submitting a form with a GET request. The error appears with the utf8=✓ parameter… EDIT: Found the culprit: I’m using escape_utils and removing it make capybara work again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem Implementing UIView Category For whatever reason, the following code isn't working: #import <Foundation/Foundation.h> @interface UIView (FindUIViewControllerParent) - (UIViewController *) firstAvailableUIViewController; - (id) traverseResponderChainForUIViewController; @end #import "UIView+FindUIViewControllerParent.h" @implementation UIView (FindUIViewControllerParent) - (UIViewController *) firstAvailableUIViewController { return (UIViewController *)[self traverseResponderChainForUIViewController]; } - (id) traverseResponderChainForUIViewController { id nextResponder = [self nextResponder]; if ([nextResponder isKindOfClass:[UIViewController class]]) { return nextResponder; } else if ([nextResponder isKindOfClass:[UIView class]]) { return [nextResponder traverseResponderChainForUIViewController]; } else { return nil; } } @end parentViewController = [self firstAvailableUIViewController]; The firstResponder is coming back as nil, instead of being the parent view controller (when I did it without the category it worked out fine). I've read some other threads that say to make some adjustments to Other Linking Options in project settings, and I've tried these and it still doesn't work. Can anyone see what I'm doing wrong here? (this code is copied nearly exactly from another thread that got a ton of up votes). A: I found my problem. I was looking for and storing the nextResponder in the init method my view, before the view had even been attached to a view controller. That's why it was correctly showing up null. I used my category method in the button action method instead and then it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring - Qualify injection candidates by designated environment Edit: Perhaps a more concise way to ask this question is: Does Spring provide a way for me to resolve ambiguous candidates at injection time by providing my own listener/factory/decision logic? In fact, arguably the @Environmental qualifier on the member field below is unnecessary: if an @Inject-ion is ambiguous... let me help? In fact, @ResolveWith(EnvironmentalResolver.class) would be alright too.. When Spring attempts to inject a dependency (using annotations) I understand that I need to @Qualifier an @Inject point if I am to have multiple components that implement that interface. What I'd like to do is something like this: class MyFoo implements Foo { @Inject @Environmental private Bar bar; } @Environmental(Environment.Production) class ProductionBar implements Bar { } @Environmental({Environment.Dev, Environment.Test}) class DevAndTestBar implements Bar { } I would expect that I need to create some kind of ambiguity resolver which would look something (vaguely) like this: class EnvironmentalBeanAmbiguityResolver { // set from configuration, read as a system environment variable, etc. private Environment currentEnvironment; public boolean canResolve(Object beanDefinition) { // true if definition has the @Environmental annotation on it } public Object resolve(Collection<Object> beans) { for (Object bean : beans) { // return bean if bean @Environmental.values[] contains currentEnvironment } throw new RuntimeException(...); } } One example of where this would be useful is we have a service that contacts end-users. Right now I just have a hacked together AOP aspect that before the method call to the "MailSender', checks for a "Production" environment flag and if it is not set, it sends the email to us instead of the users email. I'd like to instead of wrapping this in an AOP aspect specific to mail sending, instead be able to differentiate services based on the current environment. Sometime's it is just a matter of "production" or "not production" as I've demonstrated above, but a per-environment definition works too. I think this can be reused for region too... e.g. @Regional and @Regional(Region.UnitedStates) and so on and so forth. I'd imagine @Environmental would actually be a @Qualifier that way if you wanted to depend directly on something environmental you could (an @Environmental(Production) bean would likely depend directly on an @Environmental(Production) collaborator - so no ambiguity for lower level items --- same a @Regional(US) item would depend on other @Regional(US) items expiclitly and would bypass my yet-to-be-understood BeanAmbiguityResolver) Thanks. A: I think I solved this! Consider the following: public interface Ambiguity { public boolean isSatisfiedBy(BeanDefinitionHolder holder); } @Target({ METHOD, CONSTRUCTOR, FIELD }) @Retention(RUNTIME) public @interface Ambiguous { Class<? extends Ambiguity> value(); } @Target(TYPE) @Retention(RUNTIME) public @interface Environmental { public static enum Environment { Development, Testing, Production }; Environment[] value() default {}; } @Named public class EnvironmentalAmbiguity implements Ambiguity { /* This can be set via a property in applicationContext.xml, which Spring can use place holder, environment variable, etc. */ Environment env = Environment.Development; @Override public boolean isSatisfiedBy(BeanDefinitionHolder holder) { BeanDefinition bd = holder.getBeanDefinition(); RootBeanDefinition rbd = (RootBeanDefinition) bd; Class<?> bc = rbd.getBeanClass(); Environmental env = bc.getAnnotation(Environmental.class); return (env == null) ? false : hasCorrectValue(env); } private boolean hasCorrectValue(Environmental e) { for (Environment env : e.value()) { if (env.equals(this.env)) { return true; } } return false; } } @Named public class MySuperDuperBeanFactoryPostProcessor implements BeanFactoryPostProcessor, AutowireCandidateResolver { private DefaultListableBeanFactory beanFactory; private AutowireCandidateResolver defaultResolver; @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory arg) throws BeansException { if (arg instanceof DefaultListableBeanFactory) { beanFactory = (DefaultListableBeanFactory) arg; defaultResolver = beanFactory.getAutowireCandidateResolver(); beanFactory.setAutowireCandidateResolver(this); return; } throw new FatalBeanException( "BeanFactory was not a DefaultListableBeanFactory"); } @Override public Object getSuggestedValue(DependencyDescriptor descriptor) { return defaultResolver.getSuggestedValue(descriptor); } @Override public boolean isAutowireCandidate(BeanDefinitionHolder holder, DependencyDescriptor descriptor) { Ambiguity ambiguity = getAmbiguity(descriptor); if (ambiguity == null) { return defaultResolver.isAutowireCandidate(holder, descriptor); } return ambiguity.isSatisfiedBy(holder); } private Ambiguity getAmbiguity(DependencyDescriptor descriptor) { Ambiguous ambiguous = getAmbiguousAnnotation(descriptor); if (ambiguous == null) { return null; } Class<? extends Ambiguity> ambiguityClass = ambiguous.value(); return beanFactory.getBean(ambiguityClass); } private Ambiguous getAmbiguousAnnotation(DependencyDescriptor descriptor) { Field field = descriptor.getField(); if (field == null) { MethodParameter methodParameter = descriptor.getMethodParameter(); if (methodParameter == null) { return null; } return methodParameter.getParameterAnnotation(Ambiguous.class); } return field.getAnnotation(Ambiguous.class); } } Now if I have an interface MyInterface and two classes that implement it MyFooInterface and MyBarInterface like this: public interface MyInterface { public String getMessage(); } @Named @Environmental({ Environment.Testing, Environment.Production }) public class MyTestProdInterface implements MyInterface { @Override public String getMessage() { return "I don't always test my code, but when I do, I do it in production!"; } } @Named @Environmental(Environment.Development) public class DevelopmentMyInterface implements MyInterface { @Override public String getMessage() { return "Developers, developers, developers, developers!"; } } If I want to @Inject MyInterface I would get the same multiple bean definition error that one would expect. But I can add @Ambiguous(EnvironmentalAmbiguity.class) and then the EnvironmentalAmbiguity will tell which bean definition it is satisfied by. Another approach would have been to use a List and go through them all seeing if they are satisfied by a given bean definition, this would mean that the dependnecy wouldn't need the @Ambiguous annotation. That might be more "IoC-ish" but I also thought it might perform poorly. I have not tested that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is access token in facebook API? * *What is access token in Facebook API? *why I need it ? *What is its purpose ? *Do I need to store it persistently in my website ? A: For almost every request you make to facebook API you need to pass access token along to get the results. This token may expire depending on what kind it is, you might need to persist it in case your application need to access facebook API when user is offline. PS: Access token comes from user's request to your application. A: Facebook implementation of the OAuth 2.0 involves three different steps: user authentication, app authorization and app authentication. User authentication ensures that the user is who they say they are. App authorization ensures that the user knows exactly what data and capabilities they are providing to your app. App authentication ensures that the user is giving their information to your app and not someone else. Once these steps are complete, your app is issued an user access token that you enables you to access the user's information and take actions on their behalf. access token will be expired unless the user has granted to your app the "offline_access" permission. In other word, unless you have such a perm granted, you don't need to store it persistently in your website.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Progress bar and XML in Vb.Net Does anyone here know how to integrate a progress bar while loading an xml data into a treeview in VB.Net? Most xml data I am loading can reach upto 30MB so the form freezes while the xml data is loaded or when the nodes are added in the treeview. Here is the code for creating the nodes in the treeview: Private Sub AddNodes(ByRef parent As TreeNodeCollection, ByVal root As XmlNode) For Each child As XmlNode In root.ChildNodes Dim newNode As TreeNode = parent.Add(child.Name) AddNodes(newNode.Nodes, child) newNode.Collapse() Next child End Sub This is how I call the procedure: Private Sub LoadXMLData(ByVal filname As String, ByRef trv As TreeView) Dim xmlData As New XmlDocument xmlData.Load(filename) trv.Nodes.Clear() AddNodes(trv.Nodes, xmlData.DocumentElement) End Sub Any help is appreciated. Thanks. A: Take a look at the Background Worker. That should let you report loading progress, and when complete display the tree. You will have to do some refactoring (move some members to Private instead of locals), but it should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I implement Quartz.Net to schedule tasks for my MVC3 web app? I'm building a project to send messages to users. The client wants a way to schedule these messages to be sent out at a certain time, for example, he creates the message at 2am but wants it to be sent out at 10am without his intervention, where do I begin with this sort of thing? I'm using ASP.NET MVC3, any help is appreciated. Update Darin has suggested Quartz.net, I've finally gotten around to attempting to set it up. But I'm not really understanding how to implement it with my web app. I'm assuming I should be able to make an httprequest from my service to an action on my webapp, triggered by quartz. But I'm not sure how to communicate between the webapp and this service, such as sending instructions to the quartz server. So far, I've created a windows service, set up the installers, and added the Quartz.net server 2010 solution to my service project, am I on the right track? A: Using a managed Windows Service with Quartz.NET or a console application which you would schedule with the Windows task scheduler seems like a good approaches to achieve that. A: Welp, there are scheduled tasks... either make a localhost request at a specific time, or write an executable/service to be called. A possible alternative if you can't use scheduled tasks (but may be dependent upon the website being available to the Internet) is to make a remote request-maker program or use a website monitoring service. Have either of those make a request to a particular page/querystring on your site periodically. Then, make the web application perform a particular task (send an email) whenever that resource is requested. A few free monitoring services are limited to one request every hour or half-hour, or you can pay to have it checked more often. The resource's code could be made to record the message-sending event, (thus making them only get sent once, regardless of how often the request is made)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Mobile: How to customize button How do I change the <a data-role="button"> button's background to my image? Also how can I add my custom icons on top of a button at left side? A: Give the link a class and use CSS to change the background image. <a data-role="button" class="my-button"> ... .my-button { background-image: url('images/my-button.png') !important; } A: I would say that the recommended way to customize a jQuery Mobile button is adding a custom theme. <a data-role="button" data-theme="my-site">Button</a> That will give you more control over the different elements and states of the button. For instance, you can target different states of the button in CSS by writing the code for the class associated with your custom theme name (they are automatically added to the button): .ui-btn-up-my-site { /* your code here */ } .ui-btn-hover-my-site { /* your code here */ } .ui-btn-down-my-site { /* your code here */ } Keep in mind that the default buttons are made out of borders, shadows, and of course the background gradient. There also additional HTML elements inside the button that are automatically generated by the framework. Depending on what exactly you want to customize you might need to target other classes within the button (ui-icon, ui-btn-text, ui-btn-inner, etc). Here is a tutorial that explains how to do advanced customization of the jQuery Mobile buttons. The articles shows how to do some basic customization, how to reset the jQuery Mobile theme, and how to turn the default button into anything you want: http://appcropolis.com/blog/advanced-customization-jquery-mobile-buttons/
{ "language": "en", "url": "https://stackoverflow.com/questions/7518642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Delay email sending with php I'm using a FOR loop to send emails from an array[250]. for ($counter = 0; $counter <= 250; $counter ++){ // send email function[$counter] } I thought about the sleep() function but since the server have limit excute time isn't an option. Please help me with this! A: To delay sending emails in a loop, you can create your own wait() function with a loop inside it and call it before iterating. If the reason you want to wait is to avoid problems with an ISP then read this SO Answer: Sending mass email using PHP A: Without some kind of scheduler you're always going to hit your execution limit. You may want to store the emails in a database then have cron execute them. Or you can up your execution time: <?php //replace 600 without how many seconds you need ini_set('max_execution_time', 600); ... loop through emails ?> Why do you need to delay them anyways? A: Apparently (untested) the sleep function takes control away from php so the max execution time does not apply. From: http://www.hackingwithphp.com/4/11/0/pausing-script-execution "Note that the default maximum script execution time is 30 seconds, but you can use sleep() and usleep() to make your scripts go on for longer than that because technically PHP does not have control during the sleep operation." A: Use cron - almost all hosts let you use it (except the free-host ones) and they should be more than happy to help you set it up if you need assistance (if they don't help you, don't give them your money)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does XText require minimum versions of Eclipse or Java While I can just try and run it and see if it fails I may not know if some internals will fail at inopportune times does anyone know if specific versions of java or eclipse are needed? A: I'm sure, no special version of Java nor Eclipse is needed. It needs Java 1.5 and some Eclipse Modeling components (such as EMF); but they are already installed with Xtext.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I generate a keyup event with a specific keycode in IE8? I need to generate keyup events in IE 8 using native DOM functions (no jQuery). The following code generates, fires, and receives the event, but the keyCode is always 0. How do I properly pass the keyCode? <form><input id="me" type="submit" /></form> <script type="text/javascript"> var me = document.getElementById("me"); me.attachEvent("onkeyup", function(e) { alert(e.keyCode); // => 0 }); document.getElementById("me").fireEvent('onkeyup', 13); </script> A: Figured it out. The solution is to create an event object, assign the keycode, and fire it from the node. var e = document.createEventObject("KeyboardEvent"); e.keyCode = keyCode; node.fireEvent("onkeyup", e); A: e = e || window.event; keycode = e.keyCode || e.which; That will make events work in all browsers. Also, I prefer to use me.onkeyup = function(e) { ... }, but that' just personal preference (I know the drawbacks of this method, but I have clever ways to work around them)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Ruby gem environment issue - LoadError: no such file to load -- robots I'm attempting to write a crawler using the anemone gem, which requires the robots gem. For whatever reason, robots absolutely will not include. Here is some of my environment info: $ gem list -d robots *** LOCAL GEMS *** robots (0.10.1) Author: Kyle Maxwell Homepage: http://github.com/fizx/robots Installed at: /usr/local/lib/ruby/gems/1.9.1 Simple robots.txt parser $ gem env RubyGems Environment: - RUBYGEMS VERSION: 1.8.10 - RUBY VERSION: 1.9.2 (2011-02-18 patchlevel 180) [x86_64-darwin10.7.0] - INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/1.9.1 - RUBY EXECUTABLE: /usr/local/bin/ruby - EXECUTABLE DIRECTORY: /usr/local/bin - RUBYGEMS PLATFORMS: - ruby - x86_64-darwin-10 - GEM PATHS: - /usr/local/lib/ruby/gems/1.9.1 - /Users/ryan/.gem/ruby/1.9.1 - GEM CONFIGURATION: - :update_sources => true - :verbose => true - :benchmark => false - :backtrace => false - :bulk_threshold => 1000 - REMOTE SOURCES: - http://rubygems.org/ $ gem which robots /usr/local/lib/ruby/gems/1.9.1/gems/robots-0.10.1/lib/robots.rb Any ideas? All other gems load correctly, I've never had this problem before. Note that I am using ruby version 1.9, so rubygems is implicitly required. Adding require 'rubygems' ...to the front of a script returns false, since the file is already included, and does not help the situation. Any ideas? EDIT: Posting examples of failing code. Please note that rubygems returning false does not mean rubygems cannot load - rather that it has already been loaded. See this post: http://www.ruby-forum.com/topic/157442 $ irb irb(main):001:0> require 'rubygems' => false irb(main):002:0> require 'active_record' => true irb(main):003:0> require 'mechanize' => true irb(main):004:0> require 'robots' LoadError: no such file to load -- robots from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:59:in `require' from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:59:in `rescue in require' from /usr/local/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in `require' from (irb):4 from /usr/local/bin/irb:12:in `<main>' irb(main):005:0> A: It looks like the gem has been created with the wrong permissions; there's a bug opened for this on github. Changing the permissions with sudo chmod a+r /usr/local/lib/ruby/gems/1.9.1/gems/robots-0.10.1/lib/robots.rb should fix it, but watch out for other permission issues. You might be better with sudo chmod -R a+r /usr/local/lib/ruby/gems/1.9.1/gems/robots-0.10.1 to recursively make all the files in the gem readable. The robots.rb file (and some others) is being installed with the permissions -rw-rw----, so anyone using a local install of rvm or similar where gems are installed as the local user won't have been affected by this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I validate country and state/province names and postal codes? I am building an web app (with PHP) that requires users to subscribe. I would like for them to identify where they are from. So what is the best way to validate there country/state(or province)/city/postal code? Is there a DB with all the information? Which one is the best? A: There are many options for address validation. The main issue is how much traffic your website will receive and whether or not you need support. If you are relatively small, you can get away with the free services like the following: * *Google Maps API (example) (you may be breaking the TOS) *UPS Address Verification API (example) *USPS Address Web Tools If you need something more robust or customizable, it will probably be necessary to pay for a service. A: I know this is old, but to prevent others from going down the wrong path, the chosen answer to use Google API's may not have been aware of the google terms of service license (...the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited.) If you're not using a map... and your requirements do not require commercial grade data, this sums up some options and what to look for. however, if you need commercial data, greatdata.com and melissadata.com both sell real commercial level data products. This thread is also helpful: stackoverflow thread on zip code data A: Use the Google Geocoding API They allow 2,500 requests per day and you can pay for more. It will take an address and give you very detailed information on it and provide validation if you code it into your application. A: Use the USPS Address Information API. A: I've utilized data that can be purchased inexpensively from http://zipcodedownload.com/ to provide zip code validation/address correction in our applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Compile native c binaries for Android - Eg: dosfsck I am trying to compile the binary dosfsck and mkdosfs for Android, using Linux and Android NDK and SDK. I've setup NDK and SDK properly, the path to the NDK gcc is in my path. I've also downloaded the correct SDK for my device (HTC Desire). I first tried compiling the file with a simple make: make CROSS_COMPILE=/home/droidzone/android/android-ndk-r5b/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc I need to be able to run the binary from my device. As it is, the app compiles and runs on Ubuntu, but not my device. I get the error message from sh: Cannot run binary Could someone please explain how I can link libraries, where I should get them from (within the SDK) and what changes if any to make to the Makefile, and the final syntax to compile this properly for Android A: I found this was easiest to do using the agcc script script which you can use by exporting CC=agcc. Lots of projects will not properly support CROSS_COMPILE as you have tried. The agcc script is oriented around using the Android build tree files so I modified it to use the NDK tools. With this you should be able to build most things using make CC=agcc or CC=agcc ./configure
{ "language": "en", "url": "https://stackoverflow.com/questions/7518677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Declared but unset variable evaluates as true? I was doing a simple calculator with the following code. Right now it executes perfectly. When I tried to change things around, however, it doesn't work. I used BOOL program to check whether to continue asking for input from the person or finish the program. If I change the expression of while statement to just (program) and change YES/NO in the program statements, why does the code fail to do what is inside the while? // A simple printing calculator { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init] Calculator *deskCalc = [[Calculator alloc] init]; double value1; char operator BOOL program; [deskCalc setAccumulator: 0]; while (!program) { NSLog (@"Please type in your expression"); scanf (" %lf %c", &value1, &operator); program = NO; if (operator == '+') { [deskCalc add: value1]; } else if (operator == '-') { [deskCalc subtract: value1]; } else if (operator == '*' || operator == 'x') { [deskCalc multiply: value1]; } else if (operator == '/') { if (value1 == 0) NSLog (@"Division by zero!"); else [deskCalc divide: value1]; } else if (operator == 'S') { [deskCalc set: value1]; } else if (operator == 'E') { [deskCalc accumulator]; program = YES; } else { NSLog (@"Unknown operator"); } } NSLog (@"The result is %f", [deskCalc accumulator]); [deskCalc release]; [pool drain]; return 0; } A: You haven't set the initial value of program, so it defaults to a garbage value which just happens to be non-zero. Set the initial value of program when you declare it: BOOL program = NO; // or YES, whichever is appropriate A: It is always a good practice to initialize all your variables when you declare them. Also using scanf for input may be overdoing it, if I were you I would use fgets and then extract the information from the string using strtok. That way even if the user puts his elbow on the keyboard you will not have to worry. Alternatively if you are fond of scanf use sscanf on that string instead of strtok.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problems building Eclipse RCP application I'm trying to build a Eclipse RCP application with Maven/Tycho based on features. My application is a simple language with an editor (built within help of Xtext) and a few other plugins which are dependencies to the project. There are a few howtos which describe how to create a Eclipse RCP application, e.g. http://mattiasholmqvist.se/2010/03/building-with-tycho-part-2-rcp-applications/ or https://kthoms.wordpress.com/2010/11/12/setting-up-a-rcp-product-for-a-dsl/ So far, what have I done: * *Created a plug-in project which contains a feature.xml. The feature.xml consists of the language plug-ins and its dependencies *Created a plug-in project which contains a product definition. The product definition is named after the plug-in projects name (Mattias Homlqvist (first link in this post) emphasizes that Tycho makes assumptions about the product file name (in relation to the plug-in project name)). In the product definition I've created a new product and point to the 'org.eclipse.ui.ide.workbench' application. I've also added my feature plug-in and org.eclipse.pde and org.eclipse.rcp features to the dependencies tab in the editor. If I'm trying to run the product I get an exception: java.lang.RuntimeException: No application id has been found. at org.eclipse.equinox.internal.app.EclipseAppContainer. startDefaultApp(EclipseAppContainer.java:242) at org.eclipse.equinox.internal.app.MainApplicationLauncher. run(MainApplicationLauncher.java:29) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher. runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher. start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter. run(EclipseStarter.java:344) at org.eclipse.core.runtime.adaptor.EclipseStarter. run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl. invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl. invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577) at org.eclipse.equinox.launcher.Main.run(Main.java:1410) at org.eclipse.equinox.launcher.Main.main(Main.java:1386) Okay, something went terribly wrong. Now, I'm checking if all required plugins are added in the run configuration dialogue in the "Plug-ins" tab. So, the product and feature plugin are not selected. If I press 'add required plug-ins' the product plug-in is added, pressing 'validate plug-ins' just pop up and says 'no problems detected'. If I try again to run the product I get the same exception. Pressing 'synchronize' in the product definition editor reverts my changes I've made (product and feature are de-selected) - and I'm wondering why? The Maven/Tycho build itself seem to work. If I'm trying to build the project with mvn install zip files for the corresponding platforms are created. Unfortunately the problem still exists and the build is not executable. So, probably I've made a terrible mistake in my feature and/or product plug-in project. Maybe somebody has an idea or could point me into the right direction? Thanks in advance! A: I had a similar problem and for me it worked to check "Add new workspace plug-ins to this launch configuration automatically" in the run configuration, the "Plug-ins" tab. You might also check the Auto-Start (for me, "default" worked). Best regards. A: your product should be 'feature based' and in your feature, you should add the same plugins you added on your plugin.xml plus, in the 'included feature' tab, you should add org.eclipse.rcp feature
{ "language": "en", "url": "https://stackoverflow.com/questions/7518688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Php mail function error, mail sent from wrong address I would like to sent e-mail to registered users with the following code: $to = $ownerMail; $subject = 'SGKM - Online Ticket'; $message = 'SGKM - Online Ticket'; $headers = 'From: sgkm@ku.edu.tr' . "\r\n" . 'Reply-To: sgkm@ku.edu.tr' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); but unfortunately, in mail: "from sgkm@ku.edu.tr via venus.nswebhost.com" so, I still see venus.nswebhost.com in sender's mail part. Can't I delete that ? What should I do ? Thanks A: You need to use the 'additional_parameters' flag in the mail() call to specify an "envelope". $sent = mail($to, $subject, $message, $headers, "-f webmaster@example.com"); A: Unless I'm mistaken, you're not using the $headers variable in your mail() function. From: http://php.net/manual/en/function.mail.php <?php $to = 'nobody@example.com'; $subject = 'the subject'; $message = 'hello'; $headers = 'From: webmaster@example.com' . "\r\n" . 'Reply-To: webmaster@example.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $message, $headers); ?> mail($to, $subject, $message, $headers); A: You forgot to use the $headers variable you've set up! Try: $sent = mail($to, $subject, $message, $headers);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make MIN() return multiple rows? Is there a way to return more than one row based on the idea of this query: SELECT MIN(colname) AS value FROM table_name Thanks Dave A: No, there is no way to return more than 1 rows for this very query (the one you included in the example) If you want to be doubly sure, add a "LIMIT 1" at the end. (that would limit the result set to 1 row, but not required here) EDIT: To answer your question "Is there any other query that can return say 5 rows based on each row having MIN values in one column", yes there is. You need to use a 'group by' syntax, for example: SELECT category, MIN(price) AS value FROM table_name group by category A: If you're trying to select the rows with the N (say, 10) smallest values in some column, you could do something like: SELECT * FROM table_name ORDER BY colname ASC LIMIT 10; Apologies if I've misunderstood the question. A: To select multiple rows one solution is to find all rows with values that match the previously determined minimum value: SELECT * FROM tableA JOIN (SELECT MIN(colname) AS minvalue FROM tableA) B ON tableA.colname = B.minvalue This solution differs from GROUP BY in that it will not otherwise aggregate (or limit) the data in the resultset. In addition, this particular solution does not consider the case of NULL being the "minimum value". Happy coding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieve event handlers registered on input(type=button) click Is there a posibility to retrieve handlers registered on click event, if they have been registered via javascript ? I have an element with empty onclick atribute, but on input click event some js handler is executed, and I need to get the handler. A: First, check for an onsubmit handler on your form. That would fire when the button is clicked. Programatically, you can't discover event handlers registered via element.addEventListener() or element.attachEvent(), unless registered via a library that exposes such handlers. However, you can discover all event handlers in Google Chrome's DOM inspector. In Chrome, hit f12 to open up the developer tools. On the "Elements" tab, find your button and click to select it. Then on the right, click to expand the "Event Listeners" section. There you will find a list of all event listeners. Enjoy! I know of no such trick in FireBug or in IE's developer tools. You could also try the Visual Event Bookmarklet which works well unless, as I mentioned above, the event handlers are registered via element.addEventListener() or element.attachEvent(). If that's the case, and Chrome isn't good enough, your best bet would be to crack open your favorite JavaScript debugger, pause script execution and click the button. Hopefully, the script will break in the click handler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Linq is removing a value from my entity So, in a desperate attempt to wrangle EntityFramework into being usable. I am here.. private MyEntity Update(MyEntity orig) { //need a fresh copy so we can attach without adding timestamps //to every table.... MyEntity ent; using (var db = new DataContext()) { ent = db.MyEntities.Single(x => x.Id == orig.Id); } //fill a new one with the values of the one we want to save var cpy = new Payment() { //pk ID = orig.ID, //foerign key MethodId = orig.MethodId, //other fields Information = orig.Information, Amount = orig.Amount, Approved = orig.Approved, AwardedPoints = orig.AwardedPoints, DateReceived = orig.DateReceived }; //attach it _ctx.MyEntities.Attach(cpy, ent); //submit the changes _ctx.SubmitChanges(); } _ctx is an instance variable for the repository this method is in. The problem is that when I call SubmitChanges, the value of MethodId in the newly attached copy is sent to the server as 0, when it is in fact not zero if I print it out after the attach but before the submit. I am almost certain that is related to the fact that the field is a foreign key, but I still do not see why Linq would arbitrarily set it to zero when it has a valid value that meets the requirements of the constraint on the foreign key. What am I missing here? A: You should probably set Method = orig.Method, but I can't see your dbml, of course. A: I think you need to attach the foreign key reference var cpy = new Payment() { //pk ID = orig.ID, //other fields Information = orig.Information, Amount = orig.Amount, Approved = orig.Approved, AwardedPoints = orig.AwardedPoints, DateReceived = orig.DateReceived }; //create stub entity for the Method and Add it. var method = new Method{MethodId=orig.MethodId) _ctx.AttachTo("Methods", method); cpy.Methods.Add(method); //attach it _ctx.MyEntities.Attach(cpy, o); //submit the changes _ctx.SubmitChanges();
{ "language": "en", "url": "https://stackoverflow.com/questions/7518708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS: Can I intercept swipes on top of a UIWebView? I want the user to be able to swipe left, right, upward and downward on a UIWebview, but I don't want the HTML/Javascript to process those swipes-- I want to do that myself. Is that possible: To intercept just the swipes? I want the taps still to go through to the UIWebview. Thanks. A: Sure thing.Just attach UIGestureRecognizer subclass to that view and hold on for calls... UISwipeGestureRecognizer* leftSwipeRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(someAction)]; leftSwipeRecognizer.numberOfTouchesRequired = 1; leftSwipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft; leftSwipeRecognizer.cancelsTouchesInView = YES; [self.webView addGestureRecognizer:leftSwipeRecognizer]; there is some sample for left swipe gesture. You can set more with very similar approach...Hope that helps. A: If you add a UISwipeGestureRecognizer onto the UIWebview with addGestureRecognizer: it will allow you to get those events. I believe the default is to only allow one recognizer at a time, but I'm not sure if that applies to individual gesture types or across all gesture types, so this may only be the first step in solving your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PhraseQuery: can Lucene skip words from Query (not exact search) if nothing found Suppose I'm making request [hibernate-search] lucene phrase. The are 2 docs that satisfy exact phrase, but there are a lot of docs with [hibernate-search] lucene. How should I construct a query to display exact docs first and then docs without single word ([hibernate-search] phrase)? A: Just OR them: "my phrase" my phrase.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: XSLT display ALL XML tag contents I am new to using XSLT. I want to display all of the information in an xml tag in my xsl formatted page. I have tried using local-name, name, etc and none give me the result I want. Example: <step bar="a" bee="localhost" Id="1" Rt="00:00:03" Name="hello">Pass</step> I would like to be able to print out all of the information (bar="a", bee="localhost") etc as well as the value of <step> Pass. How can I do this with xsl? Thank you! A: If you want to return just the values, you could use the XPath //text()|@*. If you want the attribute/element names along with the values, you could use this stylesheet: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="*"> <xsl:apply-templates select="node()|@*"/> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="concat('&lt;',name(parent::*),'> ',.,'&#xA;')"/> </xsl:template> <xsl:template match="@*"> <xsl:value-of select="concat(name(),'=&#x22;',.,'&#x22;&#xA;')"/> </xsl:template> </xsl:stylesheet> With your input, it will produce this output: bar="a" bee="localhost" Id="1" Rt="00:00:03" Name="hello" <step> Pass A: <xsl:for-each select="attribute::*"> <xsl:value-of select="text()" /> <xsl:value-of select="local-name()" /> </xsl:for-each> <xsl:value-of select="text()" /> <xsl:value-of select="local-name()" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7518717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do we manage granular changesets in the central/shared repository? I've used Mercurial for years locally, but now we are doing a pilot of switching over from Subversion at my company. We're embracing the fact that developers will now be making more granular changesets--some of which may not even build. When developers push their changes to the central repository, all of these changesets will show up in the history - this is natural and expected. My question is: how do we deal with the fact that, because changesets are more granular, this makes it possible for developers to update to a revision that doesn't build? We are coming from a world where you can checkout anywhere in the repository and reasonably expect to be able to make a release from that point. With DVCS's, how do you tell where a "safe" revision is? This issue is somewhat addressed in this question, but I'm more interested in finding out how to deal with this using branch repos (and not named branches). I understand there are ways to modify history (e.g. the collapse extension) so that the changes get collapsed in the history of the repository, but we'd like to preserve the history. Looking at the mercurial and mozilla trees, I don't see a clear way to tell where safe revisions are to sync. Is this not as important as we think it is? A: Political solution may be "don't push crap into main repo", isn't it? Technical solution will be not tag, but one bookmark ("KnownAsGood"), applied to the last working HEAD of default branch and agreement between devs "Update not to tip, but to bookmark" Who'll test commits and move bookmark is another question from "project management" tag A: Do you really need to check out ANY old revision and expect it to build? I agree with you that you should be able to expect that the tip will always build. This can be easily achieved, like Lazy Badger already said, by some kind of "don't push unfinished work to the main repo" policy / mutual agreement. Concerning older revisions: * *if you want to build older official releases of your software again (like, you're at version 1.6 now and want to make an v1.2 executable), you can expect the 1.2 tag to build as well if everybody always sticked to the "don't push unfinished work" policy. *if you want to take ANY revision and build it...well, do you really need this? Any bugs in previous versions will probably refer to official releases (see the "1.2 tag" stuff above), and not to something in between. *if you really need a buildable version from in between the official releases (for whatever reason), you'll have to look at the commit messages and find the commit that says feature 'foo' finished (and not the one that says started implementation of feature 'foo'). Yes, this requires a bit of thinking / common sense, but I can't imagine that you will need this really often. A: If you're using feature branches and merging them without fast forward merges, you still have only stable builds on the mainline, but can see the unstable stuff on the feature branches if desired. A: You can always tag your commits. These could be major/minor releases, successful builds or however you like. You can see the mercurial and mozilla tags in their repos.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why are std::vector::data and std::string::data different? Vector's new method data() provides a const and non-const version. However string's data() method only provides a const version. I think they changed the wording about std::string so that the chars are now required to be contiguous (like std::vector). Was std::string::data just missed? Or is the a good reason to only allow const access to a string's underlying characters? note: std::vector::data has another nice feature, it's not undefined behavior to call data() on an empty vector. Whereas &vec.front() is undefined behavior if it's empty. A: In C++98/03 there was good reason to not have a non-const data() due to the fact that string was often implemented as COW. A non-const data() would have required a copy to be made if the refcount was greater than 1. While possible, this was not seen as desirable in C++98/03. In Oct. 2005 the committee voted in LWG 464 which added the const and non-const data() to vector, and added const and non-const at() to map. At that time, string had not been changed so as to outlaw COW. But later, by C++11, a COW string is no longer conforming. The string spec was also tightened up in C++11 such that it is required to be contiguous, and there's always a terminating null exposed by operator[](size()). In C++03, the terminating null was only guaranteed by the const overload of operator[]. So in short a non-const data() looks a lot more reasonable for a C++11 string. To the best of my knowledge, it was never proposed. Update charT* data() noexcept; was added basic_string in the C++1z working draft N4582 by David Sankel's P0272R1 at the Jacksonville meeting in Feb. 2016. Nice job David! A: Historically, the string data has not been const because it would prevent several common optimizations, like copy-on-write (COW). This is now, IIANM, far less common, because it behaves badly with multithreaded programs. BTW, yes they are now required to be contiguous: [string.require].5: The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size(). Another reason might be to avoid code such as: std::string ret; strcpy(ret.data(), "whatthe..."); Or any other function that returns a preallocated char array. A: Although I'm not that well-versed in the standard, it might be due to the fact that std::string doesn't need to contain null-terminated data, but it can and it doesn't need to contain an explicit length field, but it can. So changing the undelying data and e.g. adding a '\0' in the middle might get the strings length field out of sync with the actual char data and thus leave the object in an invalid state. A: @Christian Rau From the time the original Plauger (around 1995 I think) string class was STL-ized by the committee (turned into a Sequence, templatified), std::string has always been std::vector plus string-related stuff (conversion from/to 0-terminated, concatenation, ...), plus some oddities, like COW that's actually "Copy on Write and on non-const begin()/end()/operator[]". But ultimately a std::string is really a std::vector under another name, with a slightly different focus and intent. So: * *just like std::vector, std::string has either a size data member or both start and end data members; *just like std::vector, std::string does not care about the value of its elements, embedded NUL or others. std::string is not a C string with syntax sugar, utility functions and some encapsulation, just like std::vector<T> is not T[] with syntax sugar, utility functions and some encapsulation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Change secure http page content in a Firefox extension using Greasemonkey compiler I'm building a Firefox extension that alters the page content of a few select websites and I'm using the Greasemonkey compiler to do this (http://diveintogreasemonkey.org/advanced/compiler.html). The trouble I'm having though is with websites using secure http. Even if I list the https version of the site in my @includes, Greasemonkey still doesn't pick it up and change the scripted content. Any ideas on how I can still have the same effect on https sites? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is PL SQL really required? what all can be done in PL SQL can also be done by embedding sql statements in an application langauage say PhP. Why do people still use PL SQL , Are there any major advantages.? I want to avoid learning a new language and see if PHP can suffice. A: In addition to performing bulk operations on the DB end, certain IT setups have stringent security measures. Instead of allowing applications to have direct access to tables, they control access through PL/SQL stored procedures. This way they know exactly how the data is being accessed instead of applications maintained by developers which may be subject to security attacks. A: I suppose advantages would include: Tight integration with the database - Performance. Security Reduced network traffic Pre-compiled (and natively compiled) code Ability to create table triggers Integration with SQL (less datatype conversion etc) In the end though every approach and language will have its own advantages and disadvantages. Not learning PL/SQL just because you already know PHP would be a loss to yourself both personally and possibly career-wise. If you learn PL/SQL than you will understand where it has advantages over PHP and where PHP has advantages over PL/SQL but you will be in a better position to make the judgement. Best of luck. A: PL/SQL is useful when you have the opportunity to process large chunks of data on the database side with out having to load all that data in your application. Lets say you are running complex reports on millions of rows of data. You can simply implement the logic in pl/sql and not have to load all that data to your application and then write the results back to the DB - saves bandwidth, mem and time. It's a matter of being the right tool for the right job. It's up to the developer to decide when is a best time to use PL/SQL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Resizing a circle - Where is the bug sitting? I have the following code, the circle doesn't resize: HTML <div onMouseOver="mainOver();" onMouseOut="mainOut();" id="c"></div> JavaScript / jQuery function mainIn() { $('#c').animate({ border-radius: '100', webkit-border-radius: '100', moz-border-radius: '100', width: '200', height: '200', margin-left: '-100', margin-top: '-100' }); } function mainOut() { $('#c').animate({ border-radius: '50', webkit-border-radius: '50', moz-border-radius: '50', width: '100', height: '100', margin-left: '-50', margin-top: '-50' }); } Example The problem * *The circle does nothing, even when hovered. A: There are several issues in your code: You're using jQuery, so use it's handlers. You should instead using the handlers in jQuery, such as .hover() to handle the mouse over and mouse out. There are no dashes in JavaScript properties You can't do things like margin-top: "-50px" let alone margin - top: "-50px", instead, you should be using camelCase marginTop: "-50px" or to stringify your properties: "margin-top": "-50px". Vendor prefixes are not needed jQuery automatically handles the specific browser correct version. No need to animate -webkit-border-radius and the such. Example. A: * *you didn't include jQuery in your jsfiddle *Use border-radius:50% to make a square circle in anysize *Use jQuery to bind events, it's easier! *Animation need timing and callback function Look at fixed code: $('#c').hover(function(){ $(this).animate({ width: 200, height:200, 'margin-left':'-100px', 'margin-top':'-100px' }, 500, function(){}); },function(){ $(this).animate({ width: 100, height:100, 'margin-left':'-50px', 'margin-top':'-50px' }, 500, function(){}); }); http://jsfiddle.net/mohsen/9j795/16/ A: Don't add javascript: to onMouseOver and onMouseOut. Just mainOver() and mainOut() is all you need. EDIT: Also, you wrote mainOver() in one place, and mainIn() in the other. A: Quite a few things: * *border-radius is interpreted as border - radius. In jQuery, the properties camel case: borderRadius. *Don't do onmouseover, etc. jQuery provides this functionality. *No need to animate -webkit-..., etc. jQuery should take care of this. See this code for the fixes: http://jsfiddle.net/9j795/7/
{ "language": "en", "url": "https://stackoverflow.com/questions/7518737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fast query when executed individually, slow when nested I'm trying to find the most recent entry time at a bunch of specific dates. When I run select max(ts) as maxts from factorprice where ts <= '2011-1-5' It returns very quickly. EXPLAIN gives select_type SIMPLE and "Select tables optimized away". But when I run select (select max(ts) from factorprice where ts <= dates.dt) as maxts, dates.dt from trends.dates where dates.dt in ('2011-1-6'); It takes a long time to return (~10 seconds). Explain gives: * *select_type=PRIMARY table=dates rows=506 Extra=Using where *select_type=DEPENDENT SUBQUERY table=factorprice type=index possible_keys=PRIMARY key=PRIMARY keylen=8 rows=26599224 Extra=Using where; Using index This query also takes a long time (10 sec) select dt, max(ts) as maxts from factorprice as f inner join trends.dates as d where ts <= dt and dt in ('2011-1-6') group by dt; Explain gives: * *select_type=SIMPLE table=d type=ALL rows =509 Extra=Using where *select_type=SIMPLE table=f type=range possible_keys=PRIMARY key=PRIMARY keylen=8 rows=26599224 Extra=Using where; Using index I'd like to do this same operation on many different dates. Is there a way I can do that efficiently? A: It looks like this bug: http://bugs.mysql.com/bug.php?id=32665 Maybe if you create an index on dates.dt, it will go away. A: This part of your SQL is a dependent query select max(ts) from factorprice where ts <= dates.dt which is executed for each row in the resultset. So the total time is approximately the time of the standalone query times the rows in the result set. A: Judging from your EXPLAIN output. This query is visiting 506 rows in the dates table and then for each of those rows, over 26 million rows in the factorprice table. 10 seconds to do all of that isn't too bad. My guess is that you are inadvertently creating a CROSS JOIN situation where every row of one table is matched up with every row in another table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP move_uploaded_file() issue I have the PHP script (testupload.php): <?php error_reporting(E_ALL); ini_set('log_errors',1); ini_set('error_log','/root/work/inputs/log_file'); $target_path = "/work/inputs"; $target_path = $target_path . basename( $_FILES['frag3']['name']); echo "Received File: " . $_FILES['frag3']['name'] . " and moving it to " . $target_path . "<br>"; if(move_uploaded_file($_FILES['frag3']['name'], $target_path)) { echo "The file ". basename( $_FILES['frag3']['name']) . " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> And the HTML file to call it: <html xmlns="http://www.w3.org/1999/xhtml"> <body> <form action = "http://localhost:8081/testupload.php" method="post" enctype="multipart/form-data"> <span>Value : </span><input type="text" name="Value" value="Hello world"/><br /> <span>Fragment File : </span><input type="file" name="frag3" /><br /> <input type="submit" value="Send"/> </form> </body> </html> However, I continually recieve the response: There was an error uploading the file, please try again! So it's clear that move_uploaded_file() is not correctly functioning. Plus, it doesn't actually move the file. However, I can't seem to diagnose the issue. My first thought was that the directory was not writable. But my permissions for the folder are drwxrwxrwx (as determined by ls -l) Also, the line: ini_set('error_log','/root/work/inputs/log_file'); doesn't seem to write a log file to that location. Has anyone had any experience with this? How can I diagnose whats going on here? I am almost at a loss here, so any help would be greatly appreciated. I am using OpenSUSE 11.2, Apache 2.2, and PHP 5.3. Many thanks, Brett A: You should do move_uploaded_file($_FILES['frag3']['tmp_name'], $target_path) A: Here are some things to check: * *Ensure that your file upload and post limits are not reached by editing upload_max_filesize and post_max_size in your .htaccess or php.ini file. If you have error reporting on, you should see an error when they're reached. See this: http://drupal.org/node/97193 *Check for file upload error codes. See the documentation for these: http://www.php.net/manual/en/features.file-upload.errors.php *Ensure that your memory_limit has not been reached. Again, with error logging enabled, you should receive an error message about this. http://drupal.org/node/207036 *Check PHP's common pitfalls documentation and make sure there's nothing there that helps: http://www.php.net/manual/en/features.file-upload.common-pitfalls.php If none of this helps, enable error reporting and post what you receive so we can tailor our answers better to your situation. A: the php stores the file in server with temporary name which you can get by $_FILES['frag3']['tmp_name'] and not by $_FILES['frag3']['name'] A: I believe it's move_uploaded_file($_FILES['frag3']['tmp_name'], $target_path), as the files aren't actually stored by the name they're uploaded with (though you can, of course, rename them by setting their target path to such).
{ "language": "en", "url": "https://stackoverflow.com/questions/7518741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python + readline + auto-completion (tab): why are dashes and question-marks treated as word-separators? Hello coders and brave GNU-readline users, A few months ago I started using Python's (2.7.1) readline module for a shell-like application I've written. The application has nothing to do with files and file-systems - it's a tailored solution for proprietary management software. Yesterday I found that specific text causes unexpected auto-completion behavior, and haven't found a way to resolve this in the documentation. I'm desperately asking for your help here. I'll start with an example, and follow with a code snippet that reproduces the unwanted behavior. Providing the values for auto-completion are: aaa0 aaa1 aaa2 bbb_0 bbb_1 bbb_2 ccc-0 ccc-1 ccc-2 ddd?0 ddd?1 ddd?2 ...then the unexpected behavior is as follows (each action is followed by the resulting output, and a pipe | sign represents the cursor): * *Type 'b'. Input> b| *Press TAB (which in my configuration is bound to the auto-completion action). Input> bbb_| *Press TAB again. Your text will remain the same, but you will receive the following hint: bbb_0 bbb_1 bbb_2 Input> bbb_| *Type '0' and press TAB. bbb_0 bbb_1 bbb_2 Input> bbb_0 | Note the space between the '0' character and the cursor (the code snippet below shall explain this). So far so good, and trying the same with 'a' will result in similar output, only without an underscore (aaa0, aaa1, aaa2). *Start over and type 'c'. Input> c *Press TAB. Input> ccc- *Press TAB again. aaa0 aaa1 aaa2 bbb_0 bbb_1 bbb_2 ccc-0 ccc-1 ccc-2 ddd?0 ddd?1 ddd?2 Input> ccc-| This here is the first half of my problem. All values are displayed, instead of only values beginning with 'ccc-'. *Type '0', and press TAB. aaa0 aaa1 aaa2 bbb_0 bbb_1 bbb_2 ccc-0 ccc-1 ccc-2 ddd?0 ddd?1 ddd?2 Input> ccc-0| This here is the second half of my problem, you see, there's no space between the '0' character and the cursor (again, the snippet below shall explain why a space should be there). In fact, pressing TAB neither changed the text nor displayed a hint, and further TAB presses behave the same. In practice, what happens in step 7 is a misunderstanding. Readline "mistakes" the dash '-' character for a word-separator (and the same goes for the question-mark '?' character, if you try auto-completing 'ddd?'; other common word separators are, for example: space, tab, '='). So, since the current line buffer ends with a word separator, then it's time for a new word, right? Hence, in step 7 (that's where we are), all values are displayed upon pressing TAB. In step 8, once the line looks like this "Input> ccc-0|", pressing TAB has no effect because the dash, being a word-separator, separates the line into two words: 'ccc', and '0'. So, the word to be completed is '0', but alas, none of the possible values start with '0', so, no effect. Now, sadly, there's no right or wrong here. For instance, in my application, an equals-sign '=' actually is a word separator, but a dash '-' isn't. I suppose it must be a matter of configuration, but I haven't found a way to configure which characters separate words. That's what I need help with. I'm a man of my word, so here's the code snippet I promised: import readline values = ['aaa0', 'aaa1', 'aaa2', 'bbb_0', 'bbb_1', 'bbb_2', 'ccc-0', 'ccc-1', 'ccc-2', 'ddd?0', 'ddd?1', 'ddd?2'] def complete(text, state): matches = [v for v in values if v.startswith(text)] if len(matches) == 1 and matches[0] == text: # Add space if the current text is the same as the only match return "{} ".format(matches[0]) if state == 0 else None if state >= len(matches): return None return matches[state] readline.set_completer(complete) for line in ("tab: complete", "set show-all-if-unmodified on"): readline.parse_and_bind(line) raw_input("Input> ") Boys and girls, please - help! I promise to be very thankful, and even return the favor. :) Thanks very much in advance, Amnon G A: Just looking at the output of dir(readline), the functions get_completer_delims() and set_completer_delims() look like they might be useful. In fact, the documentation for the readline module includes: set_completer_delims(...) set_completer_delims(string) -> None set the readline word delimiters for tab-completion I think this describes exactly what you want. This is on Python 2.6.7; if you're running something earlier perhaps this functionality isn't available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Non member function can be declared multiple times while member function can only be declared once? Non mumber function can be delcared multiple times while member function can only be declared once? Is this right ? My example seems saying yes. But Why ? class Base{ public: int foo(int i); //int foo(int i=10); //error C2535: 'void Base::foo(int)' : member function already defined or declared }; //but it seems ok to declare it multiple times int foo(int i); int foo(int i=10); int foo(int i) { return i; } int main (void) { int i = foo();//i is 10 } A: From the Standard (2003), §8.3.6/4 says, For non-template functions, default arguments can be added in later declarations of a function in the same scope. Example from the Standard itself: void f(int, int); void f(int, int = 7); The second declaration adds default value! Also see §8.3.6/6. And an interesting (and somewhat related) topic: * *Default argument in the middle of parameter list? And §9.3/2, Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared. Hope that helps. A: You get the same result with this simplified version: int foo() ; int foo() ; // OK -- extern functions may be declared more than once class C { int foo() ; int foo() ; // Error -- member function may not be declared more than once } ; Perhaps the reason is historical -- lots of C code used redeclaration of extern functions, so they had to be allowed. A: It certainity works - but I think it is bad practice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to print user-defined datatypes in ocaml? I can't use print_endline because it requires a string, and I don't (think) I have any way to convert my very simple user-defined datatypes to strings. How can I check the values of variables of these datatypes? A: There are third-party library functions like dump in OCaml Batteries Included or OCaml Extlib, that will generically convert any value to a string using all the runtime information it can get. But this won't be able to recover all information; for example, constructor names are lost and become just integers, so it will not look exactly the way you want. You will basically have to write your own conversion functions, or use some tool that will write them for you. A: Along the lines of previous answers, ppx_sexp is a PPX for generating printers from type definitions. Here's an example of how to use it while using jbuilder as your build system, and using Base and Stdio as your stdlib. First, the jbuild file which specifies how to do the build: (jbuild_version 1) (executables ((names (w)) (libraries (base stdio)) (preprocess (pps (ppx_jane ppx_driver.runner))) )) And here's the code. open Base open Stdio type t = { a: int; b: float * float } [@@deriving sexp] let () = let x = { a = 3; b = (4.5,5.6) } in [%sexp (x : t)] |> Sexp.to_string_hum |> print_endline And when you run it you get this output: ((a 3) (b (4.5 5.6))) S-expression converters are present throughout Base and all the related libraries (Stdio, Core_kernel, Core, Async, Incremental, etc.), and so you can pretty much count on being able to serialize any data structure you encounter there, as well as anything you define on your own. A: In many cases, it's not hard to write your own string_of_ conversion routine. That's a simple alternative that doesn't require any extra libraries or non-standard OCaml extensions. For the courses I teach that use OCaml, this is often the simplest mechanism for students. (It would be nice if there were support for a generic conversion to strings though; perhaps the OCaml deriving stuff will catch on.) A: There's nothing in the base language that does this for you. There is a project named OCaml Deriving (named after a feature of Haskell) that can automatically derive print functions from type declarations. I haven't used it, but it sounds excellent. http://code.google.com/p/deriving/ Once you have a function for printing your type (derived or not), you can install it in the ocaml top-level. This can be handy, as the built-in top-level printing sometimes doesn't do quite what you want. To do this, use the #install-printer directive, described in Chapter 9 of the OCaml Manual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: JQuery click function and the -Tag horror i have the following table: <table id="list_table" class="global" border="0" cellpadding="4" cellspacing="0"> <thead> <tr> <th>Grund</th><th>Von</th><th>Bis</th><th>Beschreibung</th><th></th></tr> </thead> <tbody> <tr> <td><select name="grund[1][1]"> <option value="krank">Krankheit</option> <option value="urlaub" selected="selected">Urlaub</option> <option value="sonstiges">Sonstiges</option> </select></td><td><input name="von[1][1]" value="11.08.2011" onclick="displayDatePicker('von[1][1]')" type="text"></td><td><input name="bis[1][1]" value="16.09.2011" onclick="displayDatePicker('bis[1][1]')" type="text"></td><td><input name="beschreibung[1][1]" value="Blau machen" type="text"></td><td><a href="#" class="saveChangedEntry" uid="1" sid="1"><img src="images/save.png"></a> <a href="#" class="deleteEntry" uid="1" sid="1"><img src="images/delete.png"></a></td></tr> </tbody> </table> And my JQuery is: $('a[class*=saveChangedEntry]').click(function(event) { event.preventDefault(); alert('That's it!'); }); So if I click on the link nothing happens ;( And if i call the class in the more direct way ... even this does not work. Any hints? UPDATE: Ok, something I didn't think about it and you could not know. The table is generated as a result of a couple of events, so I think I need to add the live() function to these links. A: alert('That's it!'); is not properly escaped: alert('That\'s it!'); Example A: Make sure you wrap your code in a document.ready. Also the text you've placed inside the alert contains an unescaped quote: $(function() { $('a[class*="saveChangedEntry"]').click(function(evt) { evt.preventDefault(); alert('That\'s it!'); }); }); A: Ok, perhaps I'm not getting the problem here too well, but I think that the issue is with the selector... $(document).ready(function(){ $("a.saveChangedEntry").click(function(evt){ evt.preventDefault(); alert("foo!"); }); }); Hope I can help
{ "language": "en", "url": "https://stackoverflow.com/questions/7518756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SEF url from module in joomla I am making a module and trying to figure out how to get the Search engine friendly url to articles from this module this is the helper class today public function getItems($amount) { $db = &JFactory::getDBO(); $query = 'SELECT * FROM `#__content`, `#__content_frontpage` WHERE `#__content_frontpage`.content_id = `#__content`.id AND `#__content`.state = 1 ORDER BY `#__content`.publish_up DESC LIMIT ' . $amount . ''; $db->setQuery($query); $items = ($items = $db->loadObjectList())?$items:array(); return $items; } //end getItems And this is the default.php to display stuff <ul class="frontpage_news"> <?php foreach ($items as $item) { ?> <li> <div class="frontpage_date"><?php echo JText::sprintf('DATE_FRONTNEWS', $item->publish_up); ?></div> <div id="ffTitle" class="frontpage_title"><a href="#"><?php echo JText::sprintf('TITLE_FRONTNEWS', $item->title); ?></a></div> <div id="ffRead" class="frontpage_readmore"><a href="#"><?php echo JText::sprintf('READ_MORE_FRONTNEWS'); ?></a></div> </li> <?php } ?> </ul> So how do I get the correct link to each article displayed in SEF format? Thanks for any help! A: For Joomla 1.5: echo JRoute::_(ContentHelperRoute::getArticleRoute($article_id_and_alias, $category_id_and_alias, $section_id)); For Joomla 1.6/1.7: echo JRoute::_(ContentHelperRoute::getArticleRoute($article_id_and_alias, $category_id));
{ "language": "en", "url": "https://stackoverflow.com/questions/7518758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing the focused window in windows xp from java-based web application using JNA and Windows sendMessage API I'm wondering if anyone has any experience using JNA to call windows sendMessage API from a java web application running in a browser to change the focus from the browser to another program that is already running on the computer. I'm building out a Parts catalog that once the user has chosen the parts they want to sell to the customer, I need to automatically open the Point of Sale system so that the employee can tender the transaction. They want this to happen on some event in the parts catalog, not just an ALT-Tab or something similar. I believe the registers run some sort of kiosk version of XP and the browser (Probably going to be Firefox 5), so some of the functionality, like the task bar and start menu, etc. are not there. Maybe JNA and the windows API is the wrong way completely. Any help or direction would be greatly appreciated! A: A straightforward method would be to enumerate the extant windows until you find the one you're looking for, and then invoke the appropriate win32 method to activate/focus that window directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sim number and serial number in windows phone 7 How can i fetch SIM number or phone serial number in windows phone 7? In Android I use this code and it works: / Get the SIM country ISO code String simCountry = telephonyManager.getSimCountryIso(); // Get the operator code of the active SIM (MCC + MNC) String simOperatorCode = telephonyManager.getSimOperator(); // Get the name of the SIM operator String simOperatorName = telephonyManager.getSimOperatorName(); // -- Requires READ_PHONE_STATE uses-permission -- // Get the SIM’s serial number String simSerial = telephonyManager.getSimSerialNumber(); A: There is no API available for 3rd party developers to access the phone or SIM number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Flurry Analytics I've used a previous version of Flurry SDK with xCode 3.2.5 in my mobile application. Recently, I upgraded to Mac OSX Lion and xCode 4.1. However, I'm finding it hard to integrate the Flurry SDK 3.0.0 with xCode 4.1. I copied the FlurryAnalytics directory to my project directory, then added it in my xCode project. I changed every occurrence of FlurryAPI with FlurryAnalytics. The ERROR that I get is: "*No such file or directory FlurryAnalytics.h" when I try to add import "FlurryAnalytics/FlurryAnalytics.h" in my Plugins/Flurry.m file or Classes/MyApplicationAppDelegate.m I'd really appreciate some instructions to add FlurryAnalytics SDK 3.0.0 to my Xcode 4 project. A: Well, the solution was simple. I just had to add [drag and drop the folder] the Flurry SDK library/folder with the option "Create groups for any added folder". So that the folder gets added as a yellow folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC 3 StackOverflowException w/ @Html.Action() I've looked over a bunch of other reports of this, but mine seems to be behaving a bit differently. I am returning PartialViewResults for my child actions, so that's not the source of the recursion. Here's a dumbed down version of what I have. // The Controller [ChildActionOnly] public ActionResult _EditBillingInfo() { // Generate model return PartialView(model); } [HttpPost] public ActionResult _EditBillingInfo(EditBillingInfoViewModel model) { // Update billing informatoin var profileModel = new EditProfileViewModel() { PartialToLoad = "_EditBillingInfo" }; return View("EditProfile", profileModel); } [ChildActionOnly] public ActionResult _EditUserInfo() { // Generate model return PartialView(model); } [HttpPost] public ActionResult _EditUserInfo(EditUserInfoViewModel model) { // Update user informatoin var profileModel = new EditProfileViewModel() { PartialToLoad = "_EditUserInfo" }; return View("EditProfile", profileModel); } public ActionResult EditProfile(EditProfileViewModel model) { if (String.IsNullOrEmpty(model.PartialToLoad)) { model.PartialToLoad = "_EditUserInfo"; } return View(model); } // EditProfile View @model UPLEX.Web.ViewModels.EditProfileViewModel @{ ViewBag.Title = "Edit Profile"; Layout = "~/Views/Shared/_LoggedInLayout.cshtml"; } <div> <h2>Edit Profile</h2> <ul> <li class="up one"><span>@Ajax.ActionLink("Account Information", "_EditUserInfo", new AjaxOptions { UpdateTargetId = "EditProfileDiv", LoadingElementId = "LoadingImage" })</span></li> <li class="up two"><span>@Ajax.ActionLink("Billing Information", "_EditBillingInfo", new AjaxOptions { UpdateTargetId = "EditProfileDiv", LoadingElementId = "LoadingImage" })</span></li> </ul> <img alt="Loading Image" id="LoadingImage" style="display: none;" src="../../Content/Images/Misc/ajax-loader.gif" /> <div id="EditProfileDiv"> @Html.Action(Model.PartialToLoad) </div> </div> The partial views are both forms for updating either the user information or billing information. I debugged through this and found what is happening, but cannot figure out why. When a user browses to EditProfile, it load up with the _EditUserInfo partial and the form is there for editing. When you change some info and submit the form it hangs and you get a StackOverflowException in the EditProfile view on the call to @Html.Action(). What happens is on the initial visit to EditProfile, the @Html.Action calls the HttpGet version of _EditUserInfo. You make some changes to the user info and click submit. Once the information is updated the EditProfile view is returned again, but this time @Html.Action calls the HttpPost version of _EditUserInfo which updates the user information again, returns the EditProfile view again and the @Html.Action calls the HttpPost version of _EditUserInfo... You get where this is going. Why after form submission does it call the post version and not the get version like it did for the initial visit to EditProfile? Thanks for any help! A: I might be getting this a bit wrong, it's been a long day so, but in EditProfile you set PartialToLoad (if it's empty) to "_EditUserInfo", then in _EditUserInfo you set it again to _EditUserInfo, won't this create a loop that behaves as what you are experiencing?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WinForms: ListBox item updates case insensitive? I have a Windows Forms ListBox data-bound to a BindingList of business objects. The ListBox's displayed property is a string representing the name of the business object. I have a TextBox that is not data-bound to the name property but instead is populated when the ListBox's selected index changes, and the TextBox, upon validation, sets the business object's name property and then uses BindingList.ResetItem to notify the BindingList's bound control (the ListBox) to update itself when the TextBox's text value is changed by the user. This works great unless the name change is only a change in case (i.e. "name" to "Name"), in which case the ListBox doesn't get updated (it still says "name", even though the value of the underlying business object's name property is "Name"). Can anyone explain why this is happening and what I should do instead? My current workaround is to use BindingList.ResetBindings, which could work for me but may not be acceptable for larger datasets. Update 9/27/2011: Added a simple code example that reproduces the issue for me. This is using INotifyPropertyChanged and binding the textbox to the binding list. Based on How do I make a ListBox refresh its item text? using System; using System.ComponentModel; using System.Windows.Forms; namespace WinformsDataBindingListBoxTextBoxTest { public partial class Form1 : Form { private BindingList<Employee> _employees; private ListBox lstEmployees; private TextBox txtId; private TextBox txtName; private Button btnRemove; public Form1() { InitializeComponent(); FlowLayoutPanel layout = new FlowLayoutPanel(); layout.Dock = DockStyle.Fill; Controls.Add(layout); lstEmployees = new ListBox(); layout.Controls.Add(lstEmployees); txtId = new TextBox(); layout.Controls.Add(txtId); txtName = new TextBox(); layout.Controls.Add(txtName); btnRemove = new Button(); btnRemove.Click += btnRemove_Click; btnRemove.Text = "Remove"; layout.Controls.Add(btnRemove); Load += new EventHandler(Form1_Load); } private void Form1_Load(object sender, EventArgs e) { _employees = new BindingList<Employee>(); for (int i = 0; i < 10; i++) { _employees.Add(new Employee() { Id = i, Name = "Employee " + i.ToString() }); } lstEmployees.DisplayMember = "Name"; lstEmployees.DataSource = _employees; txtId.DataBindings.Add("Text", _employees, "Id"); txtName.DataBindings.Add("Text", _employees, "Name"); } private void btnRemove_Click(object sender, EventArgs e) { Employee selectedEmployee = (Employee)lstEmployees.SelectedItem; if (selectedEmployee != null) { _employees.Remove(selectedEmployee); } } } public class Employee : INotifyPropertyChanged { private string name; private int id; public string Name { get { return name; } set { name = value; OnPropertyChanged("Name"); } } public int Id { get { return id; } set { id = value; OnPropertyChanged("Id"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion } } Update 9/28/2011: The problem seems to be internal to the ListBox control, specifically the way it decides (not) to update an item if its string representation is equivalent to the new value, ignoring case differences. As far as I can tell this is hard coded into the control with no way to override it. A: Think I found the problem: A: I just hope this concept will be helpfull to solve your problem I have a TextBox, the user input is compared to string "Name". My button click event is: private void btn_Click(object sender, EventArgs e) { if(txt.Text == "Name") MessageBox.Show("Value is Same"); } If you write "name" in textbox, condition will be false. If you type type "Name" in textbox, condition will be true. Now try changing the btn click: using System.Globalization; private void btn_Click(object sender, EventArgs e) { TextInfo ChangeCase = new CultureInfo("en-US", false).TextInfo; string newText = ChangeCase.ToTitleCase(txt.Text); if (newText == "Name") MessageBox.Show("Value is Same"); } now you type "name" or "Name" condition is true. Remember it will just capaitalize the first letter of the string suplied. "my name" will outputted as "My Name". And if your condition says: if(txt.Text == "name") MessageBox.Show(Value is Same); Then you can try something like string newText = (txt.Text).ToLower(); if(newText == "name") MessageBox.Show(Value is Same); Here the supplied string will outputted in the lower case always. Hope it helps. A: This really is the same problem as when renaming files or directories while only case is different. I suggest the same work-around that I found earlier: if (oldValue.ToUpper() == newValue.ToUpper()){ ListBox1.Items[i] = newValue + "_tmp"; // only adding stuff to force an update ListBox1.Items[i] = newValue; // now the new value is displayed, even only case has changed } Now for your question, I suggest you try to check if the setter is changing a value only in lower/upper case (a.ToUpper() == b.ToUpper()). If true, then first give a extra change, before the intended change, something like: name = value + "_tmp"; OnPropertyChanged("Name"); name = value; OnPropertyChanged("Name"); Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }