text
stringlengths
8
267k
meta
dict
Q: How to fetch Java version using single line command in Linux I want to fetch the Java version in Linux in a single command. I am new to awk so I am trying something like java -version|awk '{print$3}' But that does not return the version. How would I fetch the 1.6.0_21 from the below Java version output? java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b06) Java HotSpot(TM) 64-Bit Server VM (build 17.0-b16, mixed mode) A: * *Redirect stderr to stdout. *Get first line *Filter the version number. java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}' A: I'd suggest using grep -i version to make sure you get the right line containing the version string. If you have the environment variable JAVA_OPTIONS set, openjdk will print the java options before printing the version information. This version returns 1.6, 1.7 etc. java -version 2>&1 | grep -i version | cut -d'"' -f2 | cut -d'.' -f1-2 A: Since (at least on my linux system) the version string looks like "1.8.0_45": #!/bin/bash function checkJavaVers { for token in $(java -version 2>&1) do if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]] then export JAVA_MAJOR=${BASH_REMATCH[1]} export JAVA_MINOR=${BASH_REMATCH[2]} export JAVA_BUILD=${BASH_REMATCH[3]} return 0 fi done return 1 } #test checkJavaVers || { echo "check failed" ; exit; } echo "$JAVA_MAJOR $JAVA_MINOR $JAVA_BUILD" ~ A: You can use --version and in that case it's not required to redirect to stdout java --version | head -1 | cut -f2 -d' ' From java help -version print product version to the error stream and exit --version print product version to the output stream and exit A: Here's my variation (with thanks/acknowledgements to many answers prior to this). My goal is to produce a "Major Version" in line with JEP 223. Assumption are made; I don't know if it works across the board for all released (or to be released) versions of java. java -version 2>&1 | fgrep -i version | cut -d'"' -f2 | sed -e 's/^1\./1\%/' -e 's/\..*//' -e 's/%/./' Version Results 1.6.0_65 1.6 1.8.0_282 1.8 11.0.10 11 15.0.2 15 A: This is a slight variation, but PJW's solution didn't quite work for me: java -version 2>&1 | head -n 1 | cut -d'"' -f2 just cut the string on the delimiter " (double quotes) and get the second field. A: This way works for me. # java -version 2>&1|awk '/version/ {gsub("\"","") ; print $NF}' 1.8.0_171 A: java -version 2>&1 | head -1 | awk -F '_|"' '{print $2}' Output 1.8.0 Or java -version 2>&1 | head -1 | awk -F '_|"' '{print $2}' | cut -c 1-3 Output 1.8 A: Getting only the "major" build #: java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print $3}'
{ "language": "en", "url": "https://stackoverflow.com/questions/7596454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: What does absolute parameter do in DateTime::diff(DateTime [, bool absolute = false]) Here is the sample code $c = new DateTime(); $o = clone $c; $o->modify('-60 days'); $diff = $c->diff($o); $diff2 = $c->diff($o, TRUE); var_dump($diff, $diff2); which outputs object(DateInterval)#3 (8) { ["y"]=> int(0), ["m"]=> int(1), ["d"]=> int(29), ["h"]=> int(0), ["i"]=> int(0), ["s"]=> int(0), ["invert"]=> int(1), ["days"]=> int(60) } object(DateInterval)#4 (8) { ["y"]=> int(0), ["m"]=> int(1), ["d"]=> int(29), ["h"]=> int(0), ["i"]=> int(0), ["s"]=> int(0), ["invert"]=> int(0), ["days"]=> int(60) } as I see, only the "invert" property changes. What does this mean? A: The absolute property will return the absolute difference between two DateTime objects. This will change the result to positive when a negative difference is returned. A: From php.net Absolute parameter determines whether to return absolute difference. LOI datetime.diff
{ "language": "en", "url": "https://stackoverflow.com/questions/7596456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Condition, Block, Module - which way is the most memory and computationally efficient? There are always several ways to do the same thing in Mathematica. For example, when adapting WReach's solution for my recent problem I used Condition: ClearAll[ff]; SetAttributes[ff, HoldAllComplete]; ff[expr_] /; (Unset[done]; True) := Internal`WithLocalSettings[Null, done = f[expr], AbortProtect[If[! ValueQ[done], Print["Interrupt!"]]; Unset[done]]] However, we can do the same thing with Block: ClearAll[ff]; SetAttributes[ff, HoldAllComplete]; ff[expr_] := Block[{done}, Internal`WithLocalSettings[Null, done = f[expr], AbortProtect[If[! ValueQ[done], Print["Interrupt!"]]]]] Or with Module: ClearAll[ff]; SetAttributes[ff, HoldAllComplete]; ff[expr_] := Module[{done}, Internal`WithLocalSettings[Null, done = f[expr], AbortProtect[If[! ValueQ[done], Print["Interrupt!"]]]]] Probably there are several other ways to do the same. Which way is the most efficient from the point of view of memory and CPU use (f may return very large arrays of data - but may return very small)? A: Both Module and Block are quite efficient, so the overhead induced by them is only noticable when the body of a function whose variables you localize does very little. There are two major reasons for the overhead: scoping construct overhead (scoping constructs must analyze the code they enclose to resolve possible name conflicts and bind variables - this takes place for both Module and Block), and the overhead of creation and destruction of new symbols in a symbol table (only for Module). For this reason, Block is somewhat faster. To see how much faster, you can do a simple experiment: In[14]:= Clear[f,fm,fb,fmp]; f[x_]:=x; fm[x_]:=Module[{xl = x},xl]; fb[x_]:=Block[{xl = x},xl]; Module[{xl},fmp[x_]:= xl=x] We defined here 4 functions, with the simplest body possible - just return the argument, possibly assigned to a local variable. We can expect the effect to be most pronounced here, since the body does very little. In[19]:= f/@Range[100000];//Timing Out[19]= {0.063,Null} In[20]:= fm/@Range[100000];//Timing Out[20]= {0.343,Null} In[21]:= fb/@Range[100000];//Timing Out[21]= {0.172,Null} In[22]:= fmp/@Range[100000];//Timing Out[22]= {0.109,Null} From these timings, we see that Block is about twice faster than Module, but that the version that uses persistent variable created by Module in the last function only once, is about twice more efficient than Block, and almost as fast as a simple function invokation (because persistent variable is only created once, and there is no scoping overhead when applying the function). For real functions, and most of the time, the overhead of either Module or Block should not matter, so I'd use whatever is safer (usually, Module). If it does matter, one option is to use persistent local variables created by Module only once. If even this overhead is significant, I'd reconsider the design - since then obviously your function does too little.There are cases when Block is more beneficial, for example when you want to be sure that all the memory used by local variables will be automatically released (this is particularly relevant for local variables with DownValues, since they are not always garbage - collected when created by Module). Another reason to use Block is when you expect a possibility of interrupts such as exceptions or aborts, and want the local variables to automatically be reset (which Block does). By using Block, however, you risk name collisions, since it binds variables dynamically rather than lexically. So, to summarize: in most cases, my suggestion is this: if you feel that your function has serious memory or run-time inefficiency, look elsewhere - it is very rare for scoping constructs to be the major bottleneck. Exceptions would include not garbage-collected Module variables with accumulated data, very light-weight functions used very frequently, and functions which operate on very efficient low-level structures such as packed arrays and sparse arrays, where symbolic scoping overhead may be comparable to the time it takes a function to process its data, since the body is very efficient and uses fast functions that by-pass the main evaluator. EDIT By combining Block and Module in the fashion suggested here: Module[{xl}, fmbp[x_] := Block[{xl = x}, xl]] you can have the best of both worlds: a function as fast as Block - scoped one and as safe as the one that uses Module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to implement permanent, regular, background location updates? The app needs an underlying feature that picks up locations and sends them to a server. This must happen regularly (approx every 1-5mins) but most importantly it must happen all the time, never stopping, protected against the OS shutting processes down to reclaim memory, and when the app itself is not running. The following solutions have been suggested to me. I'm familiar with handling Android locations, the issue here is to ensure they continue, even if the app is not in memory, and to persist through memory reclaims. * *SERVICE. Use a service to collect location events and handle them. Use the boot and screen-on broadcasts to ensure the service is always running (and possibly also increase the service priority to protect from memory reclaims). *ALARMS. I gather these can be shut down when memory is short. How would I protect against that? This seems an ugly solution as the locations will arrive on a schedule anyway, so it seems unnecessary to have another time-based component. *LOCATIONS VIA BROADCAST. Locations delivered via a broadcast intent would mean I can then handle the location events in a broadcast receiver. Will these location alerts continue indefinitely? Will anything other than device shutdown or the app turning them off cause them to stop? What's the most durable approach? A: This must happen regularly (approx every 1-5mins) but most importantly it must happen all the time, never stopping, protected against the OS shutting processes down to reclaim memory, and when the app itself is not running. This is not strictly possible, on a variety of fronts. Let's take them one piece at a time: This must happen regularly (approx every 1-5mins) You may not be able to get locations, period, let alone every 1-5 minutes. The user might have all location providers disabled. The user might have the device in airplane mode. The user might be in a large building (blocking GPS) with poor connectivity (making the network provider unreliable). never stopping The user can always get rid of you via the Manage Services screen in Settings or a task killer. If they do so, particularly on Android 3.1+, your app will never run again for any reason until the user starts an activity of yours (e.g., via the launcher). The user could also uninstall your app, of course. protected against the OS shutting processes down to reclaim memory You cannot guarantee against this. You can reduce the odds, but that is it. Now, let's look at your various solutions: Use a service to collect location events and handle them. From the way you phrase this (and subsequent sentences), you mean an everlasting service, one that is designed to run 24x7. By definition, this means that your app is running, which violates one of your rules. Assuming you relax this rule, this solution massively increases the odds that the user will get rid of your service, and it increases the odds that Android will get rid of your service. You can minimize the latter by use of startForeground(). ALARMS. I gather these can be shut down when memory is short. Not that I am aware of. However, if the user gets rid of you, your alarms will be removed. This seems an ugly solution as the locations will arrive on a schedule anyway No, they will not. The time parameter on requestLocationUpdates() does not mean that "locations will arrive on a schedule anyway". Locations delivered via a broadcast intent would mean I can then handle the location events in a broadcast receiver. No, you cannot. You have indicated that part of your work will be to send this data to a server. You cannot reliably do that on the main application thread, as it may take too long. A getService() PendingIntent, pointing to an IntentService would be more reliable. Will these location alerts continue indefinitely? No. See below. Will anything other than device shutdown or the app turning them off cause them to stop? The user can get rid of your app (uninstall, task killer, Manage Services). The user can disable location providers. The user may enter an area where the location cannot be determined. Etc. Also, the device may fall asleep, AFAIK. It's possible the system keeps a WakeLock for the duration of your registered request for updates. It's even possible that the system will use AlarmManager internally to arrange to wake itself up on your supplied period, so it does not have to keep the device awake continuously. However, you will want to test this thoroughly. What's the most durable approach? If the concerns in my previous paragraph are handled by the OS, your third option is probably the most robust. Use startForeground() in your IntentService() and call stopForeground() just before exiting onHandleIntent() -- even short-lived services started by AlarmManager may get killed off due to low memory, much to my surprise. That being said, your desired behavior seems like it may consume more battery life than the user might want. Please allow the user to control the polling period, including an option for "never poll, I'll update things manually".
{ "language": "en", "url": "https://stackoverflow.com/questions/7596462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: In WritableBitmap. How can i use Unlockbit,Stride in silverlight? Can i use Bitmap, Bitmapdata object in silverlight. And as i am using WritableBitmap. How can i use Unlockbit,Stride, bitmapdata.Scan0,Methods for Writable bitmap class. My goal is to do following in Silverlight , bitmap = new Bitmap(image); bitmapdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = bitmapdata.Stride; IntPtr ptr = bitmapdata.Scan0; byte* numPtr = (byte*) ptr; int width = bitmap.Width; numPtr = (byte*) ptr; A: Those methods don't exist on the Silverlight WritableBitmap class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using WCF, surely REST and SOAP should work in harmony? REST Only accepts String..? So What I do is make a string exposed contract and convert it server side, and pass it to my method which SOAP was directly calling. Which works. ( I can call REST from firefox) BUT now, I cannot expose my SOAP OperationContract with out causing a problem with the error: Operation 'GetServices' of contract 'IServices' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped. Below are my 3 exposed methods. Only when I hide the 3rd will REST work. Removing my SOAP connection.. ( I belive it wants REST setup on the 3rd method and as its not been defined, fails to understand it) // REST [OperationContract] [WebGet(UriTemplate = "GET/Services/{CostCentreNo}/{Filter}")] List<Services> RestGetServices(String CostCentreNo, String Filter); // REST [OperationContract] [WebGet(UriTemplate = "GET/ServiceDetails/{CostCentreNo}/{ServiceCode}/{Recurring}")] List<ServiceDetails> RestGetServiceDetails(String CostCentreNo, String ServiceCode, String Recurring); // SOAP [OperationContract] List<Services> GetServices(Int32 CostCentreNo, Int32 Filter); Surely I can make just one contract method, which allows me to call either SOAP OR REST. A: As mentioned in Can I pass non-string to WCF RESTful service using UriTemplate? : UriTemplate variables in the path always resolve to strings when using WebGet or WebInvoke. You can only bind UriTemplate variables to int, long, etc. when they are in the query portion of the UriTemplate. This is taken from the answer ( Can I pass non-string to WCF RESTful service using UriTemplate? ), bold formatting is mine... So an example of a REST and SOAP accessable method: // REST AND SOAP [OperationContract] [WebGet(UriTemplate = "/Services?CostCentreNo={CostCentreNo}&Filter={Filter}")] List<Services> GetServices(Int32 CostCentreNo, Int32 Filter); Which is accessible by http://localhost:1337/WCF.IService.svc/rest/Services?CostCentreNo=1&Filter=1 A: REST only accepts string No that is not true. Parameters mapped to URL template can be any basic type. WCF will make conversion for you. If you use WebInvoke instead of WebGet and you will use PUT or POST method you can even pass whole serializable objects inside requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Video Player for Agile Toolkit I'm looking for an add-on implementing a basic video player for Agile Toolkit. Does anyone have anything to contribute? Here is the code I'd expect to write to use it: $player = $video->add('VideoPlayer_YouTube'); $player->setSource($url); But should also be capable of playing .mp4 videos or with MediaElementJS $player = $video->add('VidoPlayer_HTML5'); $player->setSource($url); $player->js(true) ->_load('mediaelement-and-player.min') ->_css('mediaelementplayer') ->mediaelementplayer(); (p.s. is code interface looks good?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7596480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android application loading issue I am developing an application on Android 2.2 . Mainly what it does , is that it grab data from the internet and then it shows it on the device's screen. I have finished an Activity , but , it is too slow , it takes too much to get the web content . I would like to make it run faster . I guess that Async Task would be the most appropriate method that I should use . I've tried to change the code , to insert the Async Task but I cant figure out how to do it right . This is my code : package com.nextlogic.golfnews; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Bundle; import android.text.Html; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class Activity1 extends Activity { View vw; ImageView im; Bitmap bmp; URL url = null; //ImageView t; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); String s=""; String pag=""; String aux1=""; ArrayList<String> pg; ArrayList<String> links; ArrayList<String> sbt; TableLayout tableView = (TableLayout) findViewById(R.id.tableView); String q=""; String tt=""; pag=getPage(); aux1=pag.substring(pag.indexOf("\">Annonse<"),pag.indexOf("<!-- START articleListBullets -->")); pg=title(aux1); links=urls(aux1); sbt=subtitle(aux1); /////////////////////////////////////////////////////////////////////////// for(int i=0; i<pg.size(); i++) { s = "http://www.golfnews.no/" +links.get(i); q=pg.get(i); tt=sbt.get(i); // create a new TableRow TableRow row = new TableRow(this); row.setBackgroundColor(Color.WHITE); row.setTag(i); row.setClickable(true); row.setClickable(true); row.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent myIntent = new Intent(view.getContext(), News.class); startActivityForResult(myIntent, 0); } }); // create a new TextView TextView fin = new TextView(this); vw = new View(this); im = new ImageView(this); //////////////////////////////////// bmp=getbmp(s); im.setImageBitmap(bmp); vw.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1)); vw.setBackgroundColor(Color.LTGRAY); row.addView(im, new TableRow.LayoutParams(70,30)); q=titleEdit(q); tt=subtitleEdit(tt); ////////////////////////////////////// fin.setText(Html.fromHtml("<b>" + q + "</b>" + "<br />" + "<small>" + tt + "</small>")); row.addView(fin); tableView.addView(vw); tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } } public Bitmap getbmp(String s) { Bitmap bmp = null; try{ url = new URL(s); } catch(MalformedURLException e) { e.printStackTrace(); } try{ HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bmp = BitmapFactory.decodeStream(is); } catch (IOException e) { e.printStackTrace(); } return bmp; } public String titleEdit(String q) { if(q.length()>33) { String q1 = q.substring(0,33); String q2 = q.substring(33); q =q1 + "<br />" +q2; } return q; } public String subtitleEdit(String tt) { if(tt.length()>40) { String tt1 = tt.substring(0,40); String tt2 = tt.substring(40); if(tt2.length()>42) { String z1 = tt2.substring(0,40); String z2 = tt2.substring(40); if(z2.length()>42) { String z21 = z2.substring(0,40); String z22 = z2.substring(40); z2=z21+"<br />"+z22; } tt2=z1+"<br />"+z2; } tt = "<br />"+tt1 + "<br />" +tt2; } return tt; } private ArrayList<String> title (String trax) { ArrayList<String> result= new ArrayList<String>(); int ok=1; int s1,s2; while(ok==1) { //System.out.println("INDEX = "+trax.indexOf("alt=")); ok=0; if((trax.indexOf("alt=")!=-1&&trax.indexOf("\"/>")!=-1)&&((trax.indexOf("alt=")<trax.indexOf("\"/>")))) { ok=1; s1 =trax.indexOf("alt="); s2 = trax.indexOf("\"/>"); //System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length()); result.add(trax.substring(s1+5,s2)); // i++; trax = trax.substring(s2 + 3); } } return result; } private ArrayList<String> subtitle (String trax) { ArrayList<String> result= new ArrayList<String>(); int ok=1; int s1,s2; while(ok==1) { ok=0; if(trax.indexOf("<p>")!=-1) { ok=1; s1 =trax.indexOf("<p>"); s2 = trax.indexOf(")"); //System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length()); result.add(trax.substring(s1+3,s2+1)); trax = trax.substring(s2+1 ); } } return result; } private ArrayList<String> urls (String trax) { ArrayList<String> result= new ArrayList<String>(); int ok=1; int s1,s2; while(ok==1) { //System.out.println("INDEX = "+trax.indexOf("alt=")); ok=0; if((trax.indexOf("<img src")!=-1&&trax.indexOf("alt=\"")!=-1)&&((trax.indexOf("<img src")<trax.indexOf("alt=\"")))) { ok=1; s1 =trax.indexOf("<img src"); s2 = trax.indexOf("alt=\""); // System.out.println("s1= "+s1+" s2 = "+s2+" length="+trax.length()); result.add(trax.substring(s1+10,s2-2)); // i++; trax = trax.substring(s2 + 6); } } return result; } private String getPage() { String str = "***"; try { HttpClient hc = new DefaultHttpClient(); HttpPost post = new HttpPost("http://golfnews.no/nyheter.php"); HttpResponse rp = hc.execute(post); if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { str = EntityUtils.toString(rp.getEntity()); } }catch(IOException e){ e.printStackTrace(); } return str; } } The Activity takes too much time to load .(About 10 seconds) . So please , can you help me figure out where and how to insert the Async Task ? Or maybe you can suggest me something else to make the application run faster ? Something like a handler for example ? I don't really know much since I am new to Android programming . Any advice would be much appreciated . Thanks. A: 1) You need improve your code style 2) For such purposes you must use AsynchTask or Handler+Separate Thread 1,2
{ "language": "en", "url": "https://stackoverflow.com/questions/7596483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Positive look ahead regex confusing I'm building this regex with a positive look ahead in it. Basically it must select all text in the line up to last period that precedes a ":" and add a "|" to the end to delimit it. Some sample text below. I am testing this in gskinner and editpadpro which has full grep regex support apparently so if I could get the answers in that for I'd appreciate it. The regex below works to a degree but I am unsure if it is correct. Also it falls down if the text contains brackets. Finally I would like to add another ignore rule like the one that ignores but includes "Co." in the selection. This second ignore rule would ignore but include periods that have a single Capital letter before them. Sample text below too. Thanks for all the help. ^(?:[^|]+\|){3}(.*?)[^(?:Co)]\.(?=[^:]*?\:) 121| Ryan, T.N. |2001. |I like regex. But does it like me (2) 2: 615-631. 122| O' Toole, H.Y. |2004. |(Note on the regex). Pages 90-91 In: Ryan, A. & Toole, B.L. (Editors) Guide to the regex functionality in php. Timmy, Tommy& Stewie, Quohog. * Produced for Family Guy in Quohog. A: I don't think I understand what you want to do. But this part [^(?:Co)] is definitely not correct. With the square brackets you are creating a character class, because of the ^ it is a negated class. That means at this place you don't want to match one of those characters (?:Co), in other words it will match any other character than "?)(:Co". Update: I don't think its possible. How should I distinguish between L. Co. or something similar and the end of the sentence? But I found another error in your regex. The last part (?=[^:]*?\:) should be (?=[^.]*?\:) if you want to match the last dot before the : with your expression it will match on the first dot. See it here on Regexr A: This seems to do what you want. (.*\.)(?=[^:]*?:) It quite simply matches all text up to the last full stop that occurs before the colon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dojo: event indicating that widgets are rendered I have a widget on page and javascript code: <script type="text/javascript"> dojo.ready(function() { dijit.byId("widgetId"); // oops, widget is not rendered yet, so this code can't find it. }) </script> So what event should I listen to which indicates that widget is rendered? A: Since you are using a framework which appears to hide most of the dojo related configurations, the simplest solution to this would be to call the dojo.parser.parse() before accessing any widgets. This will ensure that all widgets are created and started. <script type="text/javascript"> dojo.ready(function() { dojo.parser.parse(); dijit.byId("widgetId"); }) </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reason for "Cannot resolve dependency to assembly" error When would the following message be shown? Error 1 Unknown build error, 'Cannot resolve dependency to assembly 'Infragistics2.Win.v10.3, Version=10.3.20103.2015, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.' I have added few DLLs to an existing working project. I know it's difficult to pin point the reason without the details on the code-base, but what I would like to know the general cause for such error messages to appear? Note: Just created a fresh WPF project and added the bunch of new DLLs. The issue is present there also. Therefore, it's highly likely that the issue is due to organization and content of the DLLs. A: This can happen if your xaml file statically references a view model class and that view model class has a dependency which may not be recognised as missing in the xaml file. You will need to add that dependency to the offending project. Because it is referenced in the xaml file compile time errors aren't clear on the source of the problem. A: Proper version of Infragistics DLL was missing and adding it resolved the issue. Note: The problem is too localized and hence this solution is useful at local system only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: android listen for app launch I need to develop a service which listen for every activity start. Must I do something like this? ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses(); for (int i = 0; i < runningAppProcessInfo.size(); i++) { Log.v("Proc: ", runningAppProcessInfo.get(i).processName); } And do I need to do it every X seconds? Does it affect battery consumption? A: As far as I know there is a class IActivityController.Stub in android.app package. But this is an {@hide} interface (as someone said there have some method to access @hide api). We can set a Listener to listen Activity switch like this: mAm = ActivityManagerNative.getDefault(); try { mAm.setActivityController(new ActivityController()); } catch (RemoteException e) { System.err.println("** Failed talking with activity manager!");} and Class ActivityManagerNative is @hide also. ActivityController is a class extends IActivityController.Stub . How to access @hide Api: * *you can get the android source code to build an have-@hide-api Android.jar to use. *by reflection. A: As far as I know there is currently no way to listen to an app's launch, Unless it is the first time that it is launching. ACTION_PACKAGE_FIRST_LAUNCH (Broadcast Action: Sent to the installer package of an application when that application is first launched (that is the first time it is moved out of the stopped state). So I guess your solution is the best for this right now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Index was outside on the bounds of array error on c# log in with SQL Hi i have a login which connects to a server string and executes this when the login button is pushed. It returns the invalid error if the user and password is not stored on the database but it throws a "Index was outside on the bounds of array" error if they are on the database. How would i fix this?? Thanks My connection string is located in my appconfig file, could the problem be in there? ##########FORM WINDOWS AFTER LOGIN BUTTON CLICK private void btnOK_Click(object sender, EventArgs e) { SqlConnection con = Program.GetConnection; SqlDataReader dr = null; try { SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE UserName='" + txtName.Text + "'AND Password='" + textpassword.Text + "'", con); dr = cmd.ExecuteReader(); if (dr.Read()) { Program.UserLoginName = dr.GetString(3); this.Close(); } else MessageBox.Show("Invalid Username & Password!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } #######PROGRAM.CS FILE Using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Data.SqlClient; using System.Configuration; namespace FrontEndV1 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Login()); } public static SqlConnection GetConnection { get { string ConnectionString = ConfigurationManager.ConnectionStrings["FrontEndV1Connection"].ConnectionString; SqlConnection con = new SqlConnection(ConnectionString); con.Open(); return con; } } public static string UserLoginName { get; set; } } } A: This is your problem: Program.UserLoginName = dr.GetString(3); You're getting a field whose index is greater than returned fields count. You must use an index between 0 and dr.FieldCount-1. Or you can use dr.GetString(dr.GetOrdinal(desired_field_name)): this is better (even if it needs more instructions) because you could swap returning order (maybe you need to change your query) without losing functionality. A: I think that mistake lays here: dr.GetString(3); try to change 3 to 2. Numeration begins from 0 in arrays. A: You don't say where the error is thrown, but I suspect this line: Program.UserLoginName = dr.GetString(3); Would throw the error if the query returns any fewer than 4 columns. Also, this is vulnerable to Sql injection. Use a stored proc or parameterised query. A: i think you only have three columns. The index of the 3rd column is 2, so change this line Program.UserLoginName = dr.GetString(3); to Program.UserLoginName = dr.GetString(2);. A: Can you not debug the application? If you can do then try to locate from where the exception is being thrown. As suggested by Marco and other user if you notice exception when executing dr.GetString(3) then problem lies there. Try using correct column ordinal, or use SELECT Column1, Column2, ..., ColumnN FROM Table so that you know exactly which ordinal to specify. A: Bad coding: * *using select *, you should use the names of the columns *using indexes to retrieve values in a row, you should use the actual column name returned If the above would have been applied there would be no problem. A: I had The Same error using SQL Server Express 2014 with Login Stored Procedure from 3 different tables, I was really confused what was goin on, but finally found that I had more columns Selected from One Table then other two sometimes its the logic behind it
{ "language": "en", "url": "https://stackoverflow.com/questions/7596497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send Key Event to a Child Window I'm developing an application in python which sends keyboard events to another external application. I use the pywin32 package to set the external application and send the desired key: import win32com.client as w32 shell = w32.Dispatch("WScript.Shell") shell.AppActivate(desired_application) shell.SendKeys("{ENTER}") The external application I'm using has a virtual keyboard and a text area which receives the events of the keyboard. I want to send the key event (in this case, an 'ENTER') to the keyboard area (because the keyboard is making a scan through the letters and will select the desired letter with an Enter). However, my application is sending the key events to the text area instead of the keyboard. I tried to get the handle of the window I want with FindWindow and EnumChildWindow from win32gui... So, is there a way to send the keys to the specific child window of the external application? A: I manage to choose the specific handle with EnumChildWindow (to enumerate all the handles of the application) and send the message with PostMessage. import win32api win32api.PostMessage(handler, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7596502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autocomplete data retrived via http request (not hardcded) when user type in textbox I will like to know if it's visible to use Autocomplete in such away it call some service via HTTP for fetching results and displaying it in Autocomplete list. I have one screen with the text box and I need it to work in such away when user starts entering in that textbox the autocomplete should get filled with the data. The data will not be hardcoded and will be retrived through http connection. A: 1) Create below class in your activity private class CostomTextWatcher implements TextWatcher { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() > 0) { //Make HTTP connection and retrives autocomplete strings from webservice } } } 2) set this above class to edittext using below way etSearch.addTextChangedListener(new CostomTextWatcher()); You have to make http connection using Background Thread best is AsyncTask
{ "language": "en", "url": "https://stackoverflow.com/questions/7596508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: turn on xml.vim ftplugin in vim I downloaded xml.vim plugin and copied it into /usr/share/vim/vim73/ftplugin (I replaced the existing one as the one I've downloaded was more up to date). Next I've checked :set runtimepath and made sure that the directory is listed. Then I created an emtpy xml file bla.xml outside of vim and opened this file with vim. Then I typed :filetype plugin on According to the instructions at http://www.vim.org/scripts/script.php?script_id=1397 (that's the plugin I've downloaded) I should now have tag completion. I tried it by typing <hello>. According to the manual this should automatically create the closing tag as soon as I enter '>' and place the cursor between the tags. But it's not happening. What did I miss? Syntax highlight works for xml files but this feature doesn't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save the window.URL.createObjectURL() result for future use? I'm making an application in HTML5 where you choose a video file, and then the application plays it with the HTML5 video tag and the window.URL.createObjectURL(). The problem is that I want to save the data about this video in localStorage and play it again when the user uses my application, but as Mozilla MDN states about the results of this method: Browsers will release these automatically when the document is unloaded So is it possible to do what I'm trying to do? Or do the same thing without the window.URL.createObjectURL() but with something else? A: I haven't used createObjectURL(), but if I understand correctly, it's essentially a temporary reference to a file or an in-memory object. If you want to save the actual video, it won't be useful, because the video itself will no longer be referenced by this pointer the next time the user visits the application. I think you might be able to do this with a data: URL instead, as that URL actually includes the full data from the file. This example demonstrates using a FileReader to generate a data URL. I think you should be able to do this: var reader = new FileReader(); reader.onload = function(e) { var myDataUrl = e.target.result; // do something with the URL in the DOM, // then save it to local storage }; reader.readAsDataURL(file); Update: If you want to go up to 1GB, as you note in your comment, you'd probably be better served by the FileSystem API. This would require you to get the local file, save a copy of the file to persistent filesystem storage, and then use createObjectURL() to get a URL for the file copy. You still have a problem with disk space - you just added 1GB of duplicative file content to the user's filesystem - but I don't think it's possible to keep a persistent reference to a file outside of the browser sandbox otherwise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: how to use regular expression in javascript to extract value? I want to use regular expression in javascript to extract values. The string is in this pattern "title{position}", how should i get title and position in this example? A: Assuming that's all there is too it (no nesting of '{}'s or anything) (\w+)\{(\w+)\} will match that instance and group the results as groups 1 and 2. Do you need anything more complicated like a collection of many of these per string or is that enough? A: Is that string everything? If so there's no need for matching. Just split the string! var str = "foo{bar}"; var pieces = str.split(/\{|\}/); var title = pieces[0]; var position = pieces[1]; alert("Title: " + title + "\nPosition: " + position); Demonstrated here A: If you did want to add results to a structure - var arr = []; var text = 'title{position}'; text.replace(/(\w+){(\w+)}/g, function(m, key, value){ //alert('title is-'+key); //alert('position is-'+value); arr.push({"title":key,"position":value}); }); console.log(arr); Demo - http://jsfiddle.net/Sr6Ed/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7596516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I can change the content of my site's page after a couple of minutes? So, I need to change the data representation after a couple of minutes since user did something (e.g. uploaded an image) What I need is to change some div in page after some time? How I can do it? What to use like a tool? PHP or JavaScript? Thanks, But how does imgur do it after image upload? A: You could take a look at ajax, and use that so the image is uploaded, and then displayed, or, you can use it to make calls to a page every x seconds, whatever takes your fancy. A: You'll have to use JavaScript for this. An example is this: function timeout_trigger() { window.alert('Hello!'); } function timeout_init() { setTimeout('timeout_trigger()', 120000); // 2 minutes } setTimeout uses miliseconds. So 1 minute is 60.000. Call the timeout_init() function on an event you like. So could be done onclick A: You'd need to use Ajax. Here's an example of how to use Ajax with Jquery: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <script type="text/javascript"> $(function() { setInterval('load_stuff()', (1000 * 60 * 60 * 2)); // 2 minutes }); function load_stuff() { $.ajax({ url : 'http://www.yourdomain.com/ajax.php', success:function(data) { $('div#reload_conent').html(data); } }); } </script> Read more here about ajax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CoreData - ManageObject invalid after save Have been using coreData for a short while and have not had any issues with the data model at all. However, I have an managed object that appears to have become invalid after a save and any modification to it after the save causes exceptions. This entity is a parent in a 1-m relationship. For the first save (selecting child items from a table and saving each time to preserve data between views), all is working as expected. On the next addition of children to the NSSet (in the parent), it throws the exception. I have tried to reload the entity from a fetch and saving it again, A: Are you doing a retain of that object? Are you removing some reference from the object? Check this article and try to find a more exactly problem: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdTroubleshooting.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7596530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the download and installation order of the prerequisites in ClickOnce I need to postpone the download of some prerequisite in ClickOnce to be downloaded and installed at the last of the other prerequisites? A: Find and edit the product.xml file for your bootstrapper package. The bootstrapper packages are located under the Microsoft SDKS folder. For example, this is the path on my machine... C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages See this question for a little more detail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can a windows domain logon include more than 1 '\' char? As per title, can there ever be more than 1 \ char in a windows logon name? e.g. mydomain\ghostJago Can this ever become somedomain\mydomain\ghostJago under any circumstance. I'm asking as I want to split an incoming userstring in C# on \ and get exactly 2 elements. A: Im not aware that you ever login to a domain of masterdomain\subdomain\user, its always domain\user be aware, of course, some nice thoughtful people will type domain/user A: I don't believe so. I also have applications which rely on the splitting of '\' and have never encountered an issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Deserialize Json to class object using restsharp I have checked out the documentation for restsharp and also googled for a solution, but unable to find a solution for this problem: I have an asp.net mvc3 app and need to connect to quizlet.com to access public flashcards. I have added a reference to restsharp and created the following classes: public class QuizletObject { public string response_type { get; set; } public int total_results { get; set; } public int page { get; set; } public int total_pages { get; set; } public int sets_with_images { get; set; } public Set[] sets { get; set; } } public class Set { public int id { get; set; } public string title { get; set; } public string url { get; set; } public string creator { get; set; } public int created { get; set; } public int term_count { get; set; } public bool has_images { get; set; } public int last_modified { get; set; } } I have a class and method that calls the web service like this: public class Quizlet { private string _baseUrl = "http://api.quizlet.com/1.0/sets"; private const string DevKey = "my dev key"; public QuizletObject GetQuizletSets() { _baseUrl = _baseUrl + "?dev_key=" + DevKey + "&q=" + "geography"; RestClient client = new RestClient(); client.BaseUrl = _baseUrl; RestRequest request = new RestRequest(Method.GET); request.RequestFormat = DataFormat.Json; RestResponse<QuizletObject> response = client.Execute<QuizletObject>(request); return response.Data; } } When I try to access the method using the below code in the view, I get a NullReference exception (Object reference not set to an instance of an object). @{ QuizletObject quizletObject = quizlet.GetQuizletSets(); } @foreach (Set quizletSet in quizletObject.sets) { @quizletSet.id.ToString() <br /> @quizletSet.title <br /> @quizletSet.creator <br /> @quizletSet.created <br /> @Html.Encode(quizletSet.url) <br /> <br /> } If the same method is executed as below, it returns the complete json object without any problem RestResponse response = client.Execute(request); Stack trace: [NullReferenceException: Object reference not set to an instance of an object.] ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Users\Girish\Documents\Visual Studio 2010\Projects\RestSharpPoC\RestSharpPoC\Views\Home\Index.cshtml:18 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81 System.Web.WebPages.StartPage.RunPage() +19 System.Web.WebPages.StartPage.ExecutePageHierarchy() +65 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260 System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 A: I have seen the same issue. I haven't figured it out in RestSharp, but what I do to work around it is get the json text back then deserialize it myself. For your code maybe something like this would work: response = client.Execute(request); var quizletObject = Newtonsoft.Json.JsonConvert.DeserializeObject<QuizletObject>(response.Content); As an aside, it looks like you have a problem in your GetQuizletSets() call - each time you call it, it appends _baseUrl to itself so it will continually get longer and longer. You should keep the base url the same and use request.Resource to specify the parameters, this case it would be: request.Resource = "?dev_key=" + DevKey + "&q=" + "geography" If there are multiple available calls you want to make besides "sets" I might set it up like this: private string _baseUrl = "http://api.quizlet.com/1.0"; ... request.Resource = "sets?dev_key=" + DevKey + "&q=" + "geography"; Edit: Just thought of something else - try using List instead of Set[], maybe RestSharp will have an easier time with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign db query value to t-sql variable in dynamic query I have this requirement to be implemented in a stored procedure. Dynamically query the database to get the count of a table, store it in a t-sql variable and then take some decisions based on that. This is the stored procedure that i am working on . This is throwing some errors as i don't think there is a simple way of assigning the result of a tsql dynamic query to a variable. CREATE PROCEDURE test AS BEGIN DECLARE @sql VARCHAR(255) DECLARE @cnt int SET @sql = 'SELECT COUNT(1) FROM myTable' SET @cnt = EXEC(@sql) IF (@cnt > 0) PRINT 'A' ELSE PRINT 'B' END GO Could someone tell me if there is a simpler way of achieving this using T-SQL ? Thanks. A: alternative: declare @tablename varchar(512) = 'sometable' declare @sql nvarchar(512) = 'set @count = (select count(*) from ' + @tablename + ')' declare @count int execute sp_executesql @sql, N'@count int output', @count=@count output select case when @count > 0 then 'A' else 'B' end A: Try this: SET @sql = 'SELECT @cnt = COUNT(1) FROM myTable' EXEC(@sql)
{ "language": "en", "url": "https://stackoverflow.com/questions/7596551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MongoDB stable? So i am starting to make this new app that will be a software as a service (SAAS), I have been looking at MongoDB but after reading some posts i get the impression that its not stable where you have to run the repair command alot and its easy to lose data. So with the release of 2.0 are these issues still about? To note: the app is not a forum but it will do simler sort of things that the database is needed for like users, posts, and others sorts of information, is a NoSQL the right type of DB for me or should i just go with MySQL? its also coded in PHP. A: I think you should write "simple" "helloworld" application(blog with user registration) with Mongo. It's very different from relational DB, so you will see the difference yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse's DDMS is not detecting device (Emulator) I am using Ubuntu (Linux) machine. DDMS in my eclipse is not detecting Emulator (Gingerbread) as devices. Gingerbread emulator is working fine. When I run "ddms" in cammand prompt, its working properly, it will launch ddms which will show emulator as device with running processes BUT when I try to do the same in Eclipse its not detecting. Because of that I am not able to do debugging. Please help. Regards Rke A: you have to start the adb server to get the service of the emulator or any device, if you using ubuntu then you have to kill the adb server and start it again, then it will work fine
{ "language": "en", "url": "https://stackoverflow.com/questions/7596561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSP page not populating the formBean property associated with <html:select property="fileLocation"> <% ArrayList uploadLocationLookUp = null; uploadLocationLookUp = (ArrayList) request.getSession().getAttribute("uploadLocation"); if (uploadLocationLookUp.size() != 0) { for (int i = 0; i < uploadLocationLookUp.size(); i++) { LookUpBean lookUpBeanItems = (LookUpBean) uploadLocationLookUp.get(i); %> <html:option value="<%=lookUpBeanItems.getLookUpCode()%>"> <%= lookUpBeanItems.getLookUpCode() %> </html:option> <% }} %> </html:select> I'm using the LookUpBean to populate the options in the select tag which is associated with a formBean with property fileLocation. While all other properties are populating property in the formBean this one is not. I also tried getting to it using request.getParameter("fileLocation") in my action class but it just wont work. Can anyone eyeball this chunk of code and point out any silly mistake that might have been missed? Are there other areas/issues that I might have run into? A quick response would be much appriciated. Thanks It worked :) Don't know why though :( All I did was refactor my code and rearranged the input elements on my form. Once I placed the rogue <html:select> after a piece of java code on my jsp, it worked like a charm. Can anyone give pointers to something wrong that I did and why it worked after I rearranged my form elements? A: I don't see anything obviously wrong with this code, provided that both the fileLocation and lookUpCode properties are Strings. One tip, you should be able to eliminate the scriptlet code by using the html:options tag: <html:select property="fileLocation"> <html:options collection="uploadLocation" property="lookUpCode" labelProperty=""lookUpCode"/> </html:select>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is JSONP supported in the new Flickr OAuth API? I searched for the JSONP usages of Flickr's OAuth. Let me know whether it's supported. A: There are only 2 supported methods, you cannot use OAuth for a whole login process using JSONP. But, even if it's deprecated, the old API still exists, is usable and supports JSONP: deprecated flickr auth API. A: Well, yes: http://www.flickr.com/services/api/explore/flickr.auth.oauth.getAccessToken JSONP is JSON with padding, meaning wrapped in a function. Flicker oauth's looks like this: jsonFlickrApi({ "auth": { "access_token": { "oauth_token": "", "oauth_token_secret": "" } }, "stat": "ok" }) Edit (since I was downvoted): This is the proper use of the flickr oauth API: http://www.flickr.com/services/api/auth.oauth.html everything is covered on signing and access token and how to get that token from a request token. If someone is serious about implementing the oauth process what you would get back as JSONP is the snippet I posted above. You can test it all from this link http://www.flickr.com/services/api/explore/flickr.auth.oauth.getAccessToken
{ "language": "en", "url": "https://stackoverflow.com/questions/7596563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: "The value for the useBean class attribute user.UserData is invalid" - why? Attempting to create a selection of webpages that take some information, and then display it on a later page, Works up to the retrieving and displaying stage, where I get the following error, The value for the useBean class attribute user.UserData is invalid I am using the following tutorial: http://www.jsptut.com/Forms.jsp I know there is probably 40 billion different questions aanswering this, but I literally picked up JSP at 9.13am this morning. So I need a tailormade answer! I'm using Eclipse IDE and Tomcat 6.0.33 Thanks P.S. Some google research keeps mentioning compile.class. Some mention they compiled the bean, but it thought JavaScript was a script meaning it didn't need to be compiled? Rev: Right, so apparently, i need to compile the bean and then use JSP to execute it? Can anybody advise me on how to compile my Bean? A: http://download.oracle.com/javase/tutorial/ is a good place to start. You might want to jump into http://download.oracle.com/javase/tutorial/getStarted/cupojava/win32.html. It's a step-by-step on how to write, compile and run using command-line tools and then work your way down the tutorial list. When you're a little familiar with that, you can set yourself up with a good development environment, like netbeans or eclipse
{ "language": "en", "url": "https://stackoverflow.com/questions/7596567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: facebook update: How to provide an SSL certificate You must provide an SSL certificate in the Dev App settings to avoid having your app disabled. https://developers.facebook.com/roadmap/ Do I have to upload my certificates anywhere? Where? A: You need to add your certificate to your web server. For more information about installing certificates, visit this link: https://knowledge.rapidssl.com/support/ssl-certificate-support/index?page=content&id=SO16226 Find out what kind of web server you're using and follow the instructions. You may need to contact your web hosting administrator for help. A: Once the certificate is installed on your web server, you need to enter the https url in the dev app settings, I believe it's called "Secure Canvas URL". That's all that facebook requires of you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show Toast on SplashScreen Android I am stuck with following problem.I want my application to exit if it detects no network connection.My application starts with splash screen.Is it possible to show splash screen followed by toast if no network connection is on device.and then terminate the application I have something like this in my splash screen code : Inside onCreate() ConnectivityManager connectivitymanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo(); connected = networkinfo != null && networkinfo.isAvailable() && networkinfo.isConnected(); Log.v("Network state : ", connected + ""); Thread splashThread = new Thread() { @Override public void run() { try { int waited = 0; while (waited < 5000) { sleep(100); waited += 100; } } catch (InterruptedException e) { // do nothing } finally { Looper.prepare(); if (connected == false) { Toast.makeText( splashscreenActivity.this, "No Network Connection is available on device.", Toast.LENGTH_LONG).show(); finish(); System.exit(0); } else { finish(); startActivity(new Intent(splashscreenActivity.this, mainActivity.class)); } Looper.loop(); } } }; splashThread.start(); 1.Please see my code and guide me how can i show up that toast. 2.Or suggest me some other better way to do this Thanks EDIT : Thank you everybody for replying : I opted Dharmendra's way of showing toast via splashscreen activity : The code that worked for is : if (connected == false) { splashscreenActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(splashscreenActivity.this, "No Internet Connection.", 3000).show(); } }); finish(); } else { //migrate to main activity from splashscreen } A: You can do it like this, use Handler .Put the following code in the else condition Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.post(new Runnable() { public void run() { Toast.makeText(Splash.this, "Network error", Toast.LENGTH_LONG).show(); finish(); } }); Or ,I am doing this in my application : if(status.equals("CONNECTED")) { startActivity(new Intent(Splash.this,Activity.class)); finish(); }else { startActivity(new Intent(Splash.this,NetworkError.class)); finish(); } where NetworkError class shows another layout with the image like "No Network,,,,"(or whatever you want to show instead of splash...) A: You are creating and showing Toast from Thread so it may be not called You have to write this code splashscreenActivity.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(c, "Internet connection not currently available.", 3000).show(); } }); A: Just add a if else block.(using ur connection network info) if(connected){ //put the splash thread here }else{ finish(); } A: A finally block is used if you do not wish to catch any exceptions. In your code, place all your code in a else loop, If time of 5000 lapses then, go to else statement and execute it. If you are adding catch you can remove finally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Matlab dynamic fieldnames structure with cell arrays How can i access the following structure path with dynamic fieldnames: var = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text'; fields = textscan(var,'%s','Delimiter','.'); refxtree.(fields{:}) does not work because MaterialStreamObjects contains a cell array of which I want to access the 8th cell and then continue down the structure path. In the end I want to get and set the fieldvalues. A: You need to build the appropriate input to subsref, possibly using substruct. Look at the MATLAB help. A: You can define an anonymous function to navigate this particular kind of structure of the form top.field1.field2.field3{item}.field4.field5.field6.field7 (as an aside: is it really necessary to have such a complicated structure?). getField = @(top,fields,item)top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}).(fields{7}) setField = @(top,fields,item,val)subsasgn(top.(fields{1}).(fields{2}).(fields{3}){item}.(fields{4}).(fields{5}).(fields{6}),struct('type','.','subs',fields{7}),val); You use the functions by calling fieldValue = getField(refxtree,fields,8); setField(refxtree,fields,8,newFieldValue); Note that fields is required to have seven elements. If you want to generalize the above, you will have to dynamically create the above functions A: In this case, it is easier to just use EVAL: str = 'refxtree.CaseDefinition.FlowSheetObjects.MaterialStreamObjects{8}.MaterialStreamObjectParams.Pressure.Value.Text'; %# get x = eval(str) %# set evalc([str ' = 99']);
{ "language": "en", "url": "https://stackoverflow.com/questions/7596575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: no such file to load -- rack/openid I am working on a rails gem which depends on rack/openid. But when I require it and fire up my application I get this error no such file to load -- rack/openid The gem is installed $ gem list | grep openid rack-openid (1.3.1, 1.2.0) ruby-openid (2.1.8) I've seen this question but it did NOT helped a lot. Problem with require rack/openid in Rails 3 [native require work properly] PS: I can require it from Irb just fine A: It looks like you haven't added your Gem to the Gemfile, or you haven't added rack-openid as a dependency to your gem. When Rails starts up, it uses bundler to set up the load path to match the Gemfile.lock file, so even a gem is installed locally you won't be able to require it if it isn't listed there. Gemfile.lock is created by bundler based on the gems listed in Gemfile and their dependencies. Make sure the gem you're working on specifies rack-openid as a dependency in its .gemspec, and then add gem 'my-gem-name' to your applications Gemfile (replace my-gem-name with whatever your gem is actually named).
{ "language": "en", "url": "https://stackoverflow.com/questions/7596577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how add a form in views I created a views showing user details, and i would like to show this views by date-wise. I want to create a starting date and ending date (January 1 2011 to February 25 2011), then click submit. It show only the user join between January 1 to February 25. Is it not possible to do in views, if so please tell me the other methods to do. A: For this you can use the Filter area in views. You select the User Join date as a filter, then you click the Expose button. Then in the radio list choose the one where it says something like "is between". Then you should have a form where you can select a start and end date for the users on the page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: QTreeView draw drop indicator I need to implement rows moving via drag-n-drop in QTreeView and show the drop indicator between rows. I am wondering if there is a way to override indicator drawing, so it is displayed for all levels of hierarchy between rows only (not the rectangle around the item), the line must be as wide as the entire row (not as the one column). A: It is possible by modyfing style used to draw widget. My attempt seemed to work well, but it's a bit of cheating the qt's style system, so i cannot guarante that it will work under all possible styles on all platforms. So here it is: class myViewStyle: public QProxyStyle{ public: myViewStyle(QStyle* style = 0); void drawPrimitive ( PrimitiveElement element, const QStyleOption * option, QPainter * painter, const QWidget * widget = 0 ) const; }; myViewStyle::myViewStyle(QStyle* style) :QProxyStyle(style) {} void myViewStyle::drawPrimitive ( PrimitiveElement element, const QStyleOption * option, QPainter * painter, const QWidget * widget) const{ if (element == QStyle::PE_IndicatorItemViewItemDrop && !option->rect.isNull()){ QStyleOption opt(*option); opt.rect.setLeft(0); if (widget) opt.rect.setRight(widget->width()); QProxyStyle::drawPrimitive(element, &opt, painter, widget); return; } QProxyStyle::drawPrimitive(element, option, painter, widget); } myView::myView(QWidget *parent) : QTreeView(parent) { setStyle(new myViewStyle(style())); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Why does 'this' in a function display window object where as 'this' in an argument displays the object from the function was invoked? Why does 'this' in a function display window object where as 'this' in an argument displays the object from the function was invoked? function show(x){ alert(x)//displays [object HTMLDivElement] alert(this)//displays [object Window] } <div onClick="show(this)">123</div> A: Because the function is defined in the global scope, so "this" will refer to the window object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: simple oracle stored procedure example for updating two tables in one go Could anyone give a simple example of an Oracle stored procedure for updating two tables in a single go. A: CREATE OR REPLACE PROCEDURE update_2_tables IS begin update t1 set c1 = 1; update t2 set c1 = 2; end; / A: I supposed that you update tables a and b with values from c. This is PL/SQL create or replace procedure update_one_scan as cursor c is select a.rowid r1, b.rowid r1, c.value_to_get from a join b on (join conditions) join c on (join conditions) where conditions; begin for r in c loop update a set col_to_update=r.value_to_get where rowid=r1; update b set col_to_update=r.value_to_get where rowid=r2; end loop; end; You have the advantage of single scan of source tables. UPDATE: You can do it even in oracle SQL, but is more restrictive(you'll see when you try). But this can be faster. Is a UPDATE SELECT statement: Create or replace Procedure update_select AS BEGIN update (select a.col_to_update as c1, b.col_to_update as c2, c.value_to_get v1 from a join b on (join conditions) join c on (join conditions) where conditions) set c1 = v1, c2 = v2; END;
{ "language": "en", "url": "https://stackoverflow.com/questions/7596593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails devise user function How do I execute a particular function after a user has signed up. (I wanted to add to one of my associations, I already have it coded in a non-devise rails but now I need it here) A: Device has provided helper action 'after_sign_in_path_for' you can override it within your application controller. def after_sign_in_path_for(resource_or_scope) .... #write your customize code or call any method end A: For sign up it would look like: def after_sign_up_path_for(resource_or_scope) if resource_or_scope.is_a? User # and perhaps other conditions #... do something, go somewhere else super end end Ofc. Assuming that your Devise user model is called User. A: You can use the after_create callback in your User model. The following guide has tons of examples: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7596595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get values in a tableview cell I have a tableview cells containing bible verses one by one in each cell,my need is when the user tap the cell i have to get the verse inside the tapped cell in a string formate.this is for sharing functionality. Please help me. A: To add the verse, you likely used - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; To get the verse back from a tapped cell, you use - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath; When filling the tableView, you used indexPath to get the right verse - thats what you want to do now again. Assuming you have a NSArray called 'verses': - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *verse = [verses objectAtIndex:indexPath.row]; NSLog(@"The selected verse is: %@",verse); } A: If verse is already in a standard UITableViewCell, you can access it via UITableViewCell property, like cell.textLabel.text or cell.detailTextLabel.text. Examine UITableViewCell class reference. A: use the same array to get the string.... In didSelectRowAtIndexPath delegate have a code like this NSLog(@"%@",[NSString stringWithFormat:"%@",[yourArray ObjectAtIndex:indexPath.row]); You can also use the above code to get the string in a NSString variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ANTLR and Android is there any guide how to use ANTLR on Android? I have found some ANTLR portation for Android but it looks like being without any tutorial or manual. Do you know where to find some? (and yes, I have been googling...) Thx A: After reading the README from this ANTLR port: AntlrJavaRuntime - Earlence Fernandes, The CRePE Project, VU Amsterdam ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Runtime is available as an external library against which apps can link. It provides the necessary mechanisms to execute Lexer/Parser code generated by the ANTLR tool. The model is offline, in the sense that the parser/lexer is generated off the mobile phone on a desktop computer. The resulting files are transferred to an Android project which then uses this library. Building ~~~~~~~~ * *lunch the appropriate target *make AntlrJavaRuntime *verify that AntlrJavaRuntime.xml was placed in /system/etc/permissions and AntlrJavaRuntime.jar was placed in /system/framework *after this, you can run a normal make It seems to me that the only difference is when you want to run your parser on an Android device (or -emulator) you must include the AntlrJavaRuntime in your Android project/app. So, writing the grammar, generating a parser and lexer from said grammar would be the same as on a "normal" machine. Here's a previous Q&A that shows how to write a simple expression parser: ANTLR: Is there a simple example? EDIT Also see this Q&A: android ANTLR make not working properly A: I'm not sure what "using ANTLR" means to you. Here's what it means to me: I'm assuming that you will create a grammar, generate the parser/lexer Java classes, compile them, deploy them in your Android app, and then let them parse whatever your app sends into an AST. If you want to know how to do that, there's no better place than the ANTLR documentation or the book you can buy from Amazon. A: There is an Android Studio (actually IntelliJ) plug-in for this, called "ANTLR v4 grammar plugin". This tutorial worked for me. In short, simply copy grammar (a .g4 file) into your project, right-click on it > Configure ANTLR... From there you can select to generate Java or Kotlin files, which will compile and run once you added the runtime in your dependencies: implementation 'org.antlr:antlr4-runtime:4.7'
{ "language": "en", "url": "https://stackoverflow.com/questions/7596609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Benchmarking (python vs. c++ using BLAS) and (numpy) I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate. I have, so to speak, three contestants and want to test their performance with a simple matrix-matrix multiplication. The contestants are: * *Numpy, making use only of the functionality of dot. *Python, calling the BLAS functionalities through a shared object. *C++, calling the BLAS functionalities through a shared object. Scenario I implemented a matrix-matrix multiplication for different dimensions i. i runs from 5 to 500 with an increment of 5 and the matricies m1 and m2 are set up like this: m1 = numpy.random.rand(i,i).astype(numpy.float32) m2 = numpy.random.rand(i,i).astype(numpy.float32) 1. Numpy The code used looks like this: tNumpy = timeit.Timer("numpy.dot(m1, m2)", "import numpy; from __main__ import m1, m2") rNumpy.append((i, tNumpy.repeat(20, 1))) 2. Python, calling BLAS through a shared object With the function _blaslib = ctypes.cdll.LoadLibrary("libblas.so") def Mul(m1, m2, i, r): no_trans = c_char("n") n = c_int(i) one = c_float(1.0) zero = c_float(0.0) _blaslib.sgemm_(byref(no_trans), byref(no_trans), byref(n), byref(n), byref(n), byref(one), m1.ctypes.data_as(ctypes.c_void_p), byref(n), m2.ctypes.data_as(ctypes.c_void_p), byref(n), byref(zero), r.ctypes.data_as(ctypes.c_void_p), byref(n)) the test code looks like this: r = numpy.zeros((i,i), numpy.float32) tBlas = timeit.Timer("Mul(m1, m2, i, r)", "import numpy; from __main__ import i, m1, m2, r, Mul") rBlas.append((i, tBlas.repeat(20, 1))) 3. c++, calling BLAS through a shared object Now the c++ code naturally is a little longer so I reduce the information to a minimum. I load the function with void* handle = dlopen("libblas.so", RTLD_LAZY); void* Func = dlsym(handle, "sgemm_"); I measure the time with gettimeofday like this: gettimeofday(&start, NULL); f(&no_trans, &no_trans, &dim, &dim, &dim, &one, A, &dim, B, &dim, &zero, Return, &dim); gettimeofday(&end, NULL); dTimes[j] = CalcTime(start, end); where j is a loop running 20 times. I calculate the time passed with double CalcTime(timeval start, timeval end) { double factor = 1000000; return (((double)end.tv_sec) * factor + ((double)end.tv_usec) - (((double)start.tv_sec) * factor + ((double)start.tv_usec))) / factor; } Results The result is shown in the plot below: Questions * *Do you think my approach is fair, or are there some unnecessary overheads I can avoid? *Would you expect that the result would show such a huge discrepancy between the c++ and python approach? Both are using shared objects for their calculations. *Since I would rather use python for my program, what could I do to increase the performance when calling BLAS or LAPACK routines? Download The complete benchmark can be downloaded here. (J.F. Sebastian made that link possible^^) A: Given the rigor you've shown with your analysis, I'm surprised by the results thus far. I put this as an 'answer' but only because it's too long for a comment and does provide a possibility (though I expect you've considered it). I would've thought the numpy/python approach wouldn't add much overhead for a matrix of reasonable complexity, since as the complexity increases, the proportion that python participates in should be small. I'm more interested in the results on the right hand side of the graph, but orders of magnitude discrepancy shown there would be disturbing. I wonder if you're using the best algorithms that numpy can leverage. From the compilation guide for linux: "Build FFTW (3.1.2): SciPy Versions >= 0.7 and Numpy >= 1.2: Because of license, configuration, and maintenance issues support for FFTW was removed in versions of SciPy >= 0.7 and NumPy >= 1.2. Instead now uses a built-in version of fftpack. There are a couple ways to take advantage of the speed of FFTW if necessary for your analysis. Downgrade to a Numpy/Scipy version that includes support. Install or create your own wrapper of FFTW. See http://developer.berlios.de/projects/pyfftw/ as an un-endorsed example." Did you compile numpy with mkl? (http://software.intel.com/en-us/articles/intel-mkl/). If you're running on linux, the instructions for compiling numpy with mkl are here: http://www.scipy.org/Installing_SciPy/Linux#head-7ce43956a69ec51c6f2cedd894a4715d5bfff974 (in spite of url). The key part is: [mkl] library_dirs = /opt/intel/composer_xe_2011_sp1.6.233/mkl/lib/intel64 include_dirs = /opt/intel/composer_xe_2011_sp1.6.233/mkl/include mkl_libs = mkl_intel_lp64,mkl_intel_thread,mkl_core If you're on windows, you can obtain a compiled binary with mkl, (and also obtain pyfftw, and many other related algorithms) at: http://www.lfd.uci.edu/~gohlke/pythonlibs/, with a debt of gratitude to Christoph Gohlke at the Laboratory for Fluorescence Dynamics, UC Irvine. Caveat, in either case, there are many licensing issues and so on to be aware of, but the intel page explains those. Again, I imagine you've considered this, but if you meet the licensing requirements (which on linux is very easy to do), this would speed up the numpy part a great deal relative to using a simple automatic build, without even FFTW. I'll be interested to follow this thread and see what others think. Regardless, excellent rigor and excellent question. Thanks for posting it. A: UPDATE (30.07.2014): I re-run the the benchmark on our new HPC. Both the hardware as well as the software stack changed from the setup in the original answer. I put the results in a google spreadsheet (contains also the results from the original answer). Hardware Our HPC has two different nodes one with Intel Sandy Bridge CPUs and one with the newer Ivy Bridge CPUs: Sandy (MKL, OpenBLAS, ATLAS): * *CPU: 2 x 16 Intel(R) Xeon(R) E2560 Sandy Bridge @ 2.00GHz (16 Cores) *RAM: 64 GB Ivy (MKL, OpenBLAS, ATLAS): * *CPU: 2 x 20 Intel(R) Xeon(R) E2680 V2 Ivy Bridge @ 2.80GHz (20 Cores, with HT = 40 Cores) *RAM: 256 GB Software The software stack is for both nodes the sam. Instead of GotoBLAS2, OpenBLAS is used and there is also a multi-threaded ATLAS BLAS that is set to 8 threads (hardcoded). * *OS: Suse *Intel Compiler: ictce-5.3.0 *Numpy: 1.8.0 *OpenBLAS: 0.2.6 *ATLAS:: 3.8.4 Dot-Product Benchmark Benchmark-code is the same as below. However for the new machines I also ran the benchmark for matrix sizes 5000 and 8000. The table below includes the benchmark results from the original answer (renamed: MKL --> Nehalem MKL, Netlib Blas --> Nehalem Netlib BLAS, etc) Single threaded performance: Multi threaded performance (8 threads): Threads vs Matrix size (Ivy Bridge MKL): Benchmark Suite Single threaded performance: Multi threaded (8 threads) performance: Conclusion The new benchmark results are similar to the ones in the original answer. OpenBLAS and MKL perform on the same level, with the exception of Eigenvalue test. The Eigenvalue test performs only reasonably well on OpenBLAS in single threaded mode. In multi-threaded mode the performance is worse. The "Matrix size vs threads chart" also show that although MKL as well as OpenBLAS generally scale well with number of cores/threads,it depends on the size of the matrix. For small matrices adding more cores won't improve performance very much. There is also approximately 30% performance increase from Sandy Bridge to Ivy Bridge which might be either due to higher clock rate (+ 0.8 Ghz) and/or better architecture. Original Answer (04.10.2011): Some time ago I had to optimize some linear algebra calculations/algorithms which were written in python using numpy and BLAS so I benchmarked/tested different numpy/BLAS configurations. Specifically I tested: * *Numpy with ATLAS *Numpy with GotoBlas2 (1.13) *Numpy with MKL (11.1/073) *Numpy with Accelerate Framework (Mac OS X) I did run two different benchmarks: * *simple dot product of matrices with different sizes *Benchmark suite which can be found here. Here are my results: Machines Linux (MKL, ATLAS, No-MKL, GotoBlas2): * *OS: Ubuntu Lucid 10.4 64 Bit. *CPU: 2 x 4 Intel(R) Xeon(R) E5504 @ 2.00GHz (8 Cores) *RAM: 24 GB *Intel Compiler: 11.1/073 *Scipy: 0.8 *Numpy: 1.5 Mac Book Pro (Accelerate Framework): * *OS: Mac OS X Snow Leopard (10.6) *CPU: 1 Intel Core 2 Duo 2.93 Ghz (2 Cores) *RAM: 4 GB *Scipy: 0.7 *Numpy: 1.3 Mac Server (Accelerate Framework): * *OS: Mac OS X Snow Leopard Server (10.6) *CPU: 4 X Intel(R) Xeon(R) E5520 @ 2.26 Ghz (8 Cores) *RAM: 4 GB *Scipy: 0.8 *Numpy: 1.5.1 Dot product benchmark Code: import numpy as np a = np.random.random_sample((size,size)) b = np.random.random_sample((size,size)) %timeit np.dot(a,b) Results: System | size = 1000 | size = 2000 | size = 3000 | netlib BLAS | 1350 ms | 10900 ms | 39200 ms | ATLAS (1 CPU) | 314 ms | 2560 ms | 8700 ms | MKL (1 CPUs) | 268 ms | 2110 ms | 7120 ms | MKL (2 CPUs) | - | - | 3660 ms | MKL (8 CPUs) | 39 ms | 319 ms | 1000 ms | GotoBlas2 (1 CPU) | 266 ms | 2100 ms | 7280 ms | GotoBlas2 (2 CPUs)| 139 ms | 1009 ms | 3690 ms | GotoBlas2 (8 CPUs)| 54 ms | 389 ms | 1250 ms | Mac OS X (1 CPU) | 143 ms | 1060 ms | 3605 ms | Mac Server (1 CPU)| 92 ms | 714 ms | 2130 ms | Benchmark Suite Code: For additional information about the benchmark suite see here. Results: System | eigenvalues | svd | det | inv | dot | netlib BLAS | 1688 ms | 13102 ms | 438 ms | 2155 ms | 3522 ms | ATLAS (1 CPU) | 1210 ms | 5897 ms | 170 ms | 560 ms | 893 ms | MKL (1 CPUs) | 691 ms | 4475 ms | 141 ms | 450 ms | 736 ms | MKL (2 CPUs) | 552 ms | 2718 ms | 96 ms | 267 ms | 423 ms | MKL (8 CPUs) | 525 ms | 1679 ms | 60 ms | 137 ms | 197 ms | GotoBlas2 (1 CPU) | 2124 ms | 4636 ms | 147 ms | 456 ms | 743 ms | GotoBlas2 (2 CPUs)| 1560 ms | 3278 ms | 116 ms | 295 ms | 460 ms | GotoBlas2 (8 CPUs)| 741 ms | 2914 ms | 82 ms | 262 ms | 192 ms | Mac OS X (1 CPU) | 948 ms | 4339 ms | 151 ms | 318 ms | 566 ms | Mac Server (1 CPU)| 1033 ms | 3645 ms | 99 ms | 232 ms | 342 ms | Installation Installation of MKL included installing the complete Intel Compiler Suite which is pretty straight forward. However because of some bugs/issues configuring and compiling numpy with MKL support was a bit of a hassle. GotoBlas2 is a small package which can be easily compiled as a shared library. However because of a bug you have to re-create the shared library after building it in order to use it with numpy. In addition to this building it for multiple target plattform didn't work for some reason. So I had to create an .so file for each platform for which i want to have an optimized libgoto2.so file. If you install numpy from Ubuntu's repository it will automatically install and configure numpy to use ATLAS. Installing ATLAS from source can take some time and requires some additional steps (fortran, etc). If you install numpy on a Mac OS X machine with Fink or Mac Ports it will either configure numpy to use ATLAS or Apple's Accelerate Framework. You can check by either running ldd on the numpy.core._dotblas file or calling numpy.show_config(). Conclusions MKL performs best closely followed by GotoBlas2. In the eigenvalue test GotoBlas2 performs surprisingly worse than expected. Not sure why this is the case. Apple's Accelerate Framework performs really good especially in single threaded mode (compared to the other BLAS implementations). Both GotoBlas2 and MKL scale very well with number of threads. So if you have to deal with big matrices running it on multiple threads will help a lot. In any case don't use the default netlib blas implementation because it is way too slow for any serious computational work. On our cluster I also installed AMD's ACML and performance was similar to MKL and GotoBlas2. I don't have any numbers tough. I personally would recommend to use GotoBlas2 because it's easier to install and it's free. If you want to code in C++/C also check out Eigen3 which is supposed to outperform MKL/GotoBlas2 in some cases and is also pretty easy to use. A: I've run your benchmark. There is no difference between C++ and numpy on my machine: Do you think my approach is fair, or are there some unnecessary overheads I can avoid? It seems fair due to there is no difference in results. Would you expect that the result would show such a huge discrepancy between the c++ and python approach? Both are using shared objects for their calculations. No. Since I would rather use python for my program, what could I do to increase the performance when calling BLAS or LAPACK routines? Make sure that numpy uses optimized version of BLAS/LAPACK libraries on your system. A: Here's another benchmark (on Linux, just type make): http://dl.dropbox.com/u/5453551/blas_call_benchmark.zip http://dl.dropbox.com/u/5453551/blas_call_benchmark.png I do not see essentially any difference between the different methods for large matrices, between Numpy, Ctypes and Fortran. (Fortran instead of C++ --- and if this matters, your benchmark is probably broken.) Your CalcTime function in C++ seems to have a sign error. ... + ((double)start.tv_usec)) should be instead ... - ((double)start.tv_usec)). Perhaps your benchmark also has other bugs, e.g., comparing between different BLAS libraries, or different BLAS settings such as number of threads, or between real time and CPU time? EDIT: failed to count the braces in the CalcTime function -- it's OK. As a guideline: if you do a benchmark, please always post all the code somewhere. Commenting on benchmarks, especially when surprising, without having the full code is usually not productive. To find out which BLAS Numpy is linked against, do: $ python Python 2.7.2+ (default, Aug 16 2011, 07:24:41) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import numpy.core._dotblas >>> numpy.core._dotblas.__file__ '/usr/lib/pymodules/python2.7/numpy/core/_dotblas.so' >>> $ ldd /usr/lib/pymodules/python2.7/numpy/core/_dotblas.so linux-vdso.so.1 => (0x00007fff5ebff000) libblas.so.3gf => /usr/lib/libblas.so.3gf (0x00007fbe618b3000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbe61514000) UPDATE: If you can't import numpy.core._dotblas, your Numpy is using its internal fallback copy of BLAS, which is slower, and not meant to be used in performance computing! The reply from @Woltan below indicates that this is the explanation for the difference he/she sees in Numpy vs. Ctypes+BLAS. To fix the situation, you need either ATLAS or MKL --- check these instructions: http://scipy.org/Installing_SciPy/Linux Most Linux distributions ship with ATLAS, so the best option is to install their libatlas-dev package (name may vary). A: Let me contribute to a somewhat weird finding My numpy is linked to mkl, as given by numpy.show_config(). I have no idea what kind of libblas.so C++/BLAS was used. I hope someone can tell me a way to figure it out. I think the results strongly depend on the library was used. I cannot isolate the efficiency of C++/BLAS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "116" }
Q: how can i change listing order of my ul li list for each page load using jquery hi i am using prevnext jquery slider . Now on each page load the sliding starting from the first list. Is there any way to list items in random order A: If I were to do this I'd probably use a query string idea i.e. http://www.mysite.com/index.html?1 , so I'd do: var windowLocation = window.location.split("?"); if(windowLocation[1] === 1){ //show 1 slide }else if(windowLocation[1] === 2){ //show another slide first } And so on...
{ "language": "en", "url": "https://stackoverflow.com/questions/7596616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Errors on importing my oracle 10g database I am running my oracle on a debian machine. Today I decided to create a new user and a new tablespace. Then I export a database with the user System which on the same machine. I got some error when I try to import to my new user account. here is what I've done: ./imp mynewuser/passwrdb@orcl file=newdump_sept.dmp system/tomynewuser Import: Release 10.2.0.1.0 - Production on Thu Sep 29 18:06:23 2011 Copyright (c) 1982, 2005, Oracle. All rights reserved. Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production With the Partitioning, OLAP and Data Mining options Export file created by EXPORT:V10.02.01 via conventional path Warning: the objects were exported by SYSTEM, not by you import done in US7ASCII character set and AL16UTF16 NCHAR character set import server uses WE8ISO8859P1 character set (possible charset conversion) IMP-00085: multiple input files specified for unbounded export file IMP-00000: Import terminated unsuccessfully Any suggestion to my problem? A: From http://www.error-code.org.uk/view.asp?e=ORACLE-IMP-00085 : Oracle Error :: IMP-00085 multiple input files specified for unbounded export file Cause You specified multiple file names for the FILE parameter when doing an import, but the header in the export file indicates that that the export operation could create only one file. Specifying multiple file names is valid for an import operation only if the export files were created by an export operation in which the user specified a non-zero value for the FILESIZE parameter. Action If you believe the export contains multiple files, verify that you have specified the correct files. If you believe the export should be in only one file then try the import operation again, but specify only one value for the FILE parameter. You should probably use: ./imp mynewuser/passwrdb@orcl file=newdump_sept.dmp fromuser=system touser=tomynewuser For help: imp help=y A: In my case I solved the error by importing the dump file by using SYS user instead of SYSTEM user and import working without errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MongoDB: order by two fields sum SELECT (a+b) as c FROM my_table ORDER BY c ASC; How can I order by two columns sum in Mongo? A: You can't do it easy without an extra action. To sort on any computed value you need to store it in a document first or in other worlds you need to create extra field 'c', and store a + b in it with each update/insert and only then sort on 'c' as usual. A: You can achieve like this query: db.mycol.aggregate( [{$match:{tag:"xxx"}}, {$project:{tag:1, count_a:1, count_b:1, factor:{$add: ["$count_a", "$count_b"]}}}, {$sort:{factor:-1}}] )
{ "language": "en", "url": "https://stackoverflow.com/questions/7596620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is the best way to share/distribute Excel macro? I wrote the macro in Excel and want to distribute it to the users. Once opened I want the macro to add itself as a toolbar and then to be always visible whenever the Excel is opened. So the macro can be conveniently accessed used from all workbooks. A: IMHO, the easiest way is to create an add-in with your code and give it to the users. See this link on ozgrid to learn how to build addins. A: For Sub's tied to toolbars an Addin - as said by JMax - would be my choice. For formulae specific to your business a regular empty Excel file with one or more modules containing Function Xxx(), placed in the Autostart folder would be sufficient. A server directory which is added to the user's path of Autostart folders is an easy way to auto-distribute formulae. I am using the latter for instance for IP address calculations
{ "language": "en", "url": "https://stackoverflow.com/questions/7596623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Strip the path to the pdb Per default, when compiling a Visual Studio project in release mode, the complete path to the pdb is put into the image file, e.g.: c:\myprojects\demo\release\test.pdb Using an undocumented linker switch (/pdbpath:none) one can force Visual Studio 2008 to reduce the full qualified name of the pdb, e.g: test.pdb I need to do the same with a project which is still built using VC6. I tried the "/pdbpath:none" switch at the project settings level, but the linker complains about this unknown switch. Does anyone knows a method (or a tool) to accomplish this either when linking a VC6 project or afterwards directly at the image level? A: Your best bet is to use pdbstr.exe from MS directly. It allows for direct extraction, update, and misc other functions directly, independent of compiler version (up to the last supported version, which I think is VS2013 right now). We use it to add SVN linkings directly to PDBs which we then store in local symbol stores using srctool. A: For newer link.exe versions, the syntax changed. The option you want is now /pdbaltpath:%_PDB% It is documented on MSDN: https://msdn.microsoft.com/en-us/library/dd998269.aspx %_PDB% expands to the file name of the actual .pdb file without any path information For VC6, you might want to continue using the same compilers but a new version of link.exe. The Windows Driver Kits also come with a tool named binplace.exe which can modify this information post-build.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Character set encoding issue All, Im having the age old problem with character encoding... I have a mySQL DB with a field set to utf8_unicode_ci. My PHP page as the header entry <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />. When I use a simple form to POST data with Cyrillic characters to the DB, e.g. 'гыдлпоо', the characters display correctly in the textarea, and are added to the DB where they display correctly. When fetching the characters from the DB, my page only displays a series of question marks. I've used mb_detect_encoding($content, "UTF-8,ISO-8859-1", true); and the content is UTF-8, however the characters do not display. I've searched around (including on SO) and tried any number of solutions, to no avail- any help would be much appreciated. Many thanks A: Do this right after mysql_connect() and mysql_select_db(): mysql_query("SET NAMES 'utf8'"); A: did you try to use the form with enctype="multipart/form-data" ? this might help.. it's not necessary for the text to be readable in your database.. when they are saved they should be utf8 encoded.. you need them to look fine when you output the string again A: Try using mysql_set_charset() function before fetching data from database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Merging programs of different languages I have three programs (one in C++ + WinAPI, another one in C# .NET and the last one in Java) with different functions. I am about to choose one and implement functions of the other two. Is it possible to somehow merge them? I need to have them in one GUI, under one process (at least visually). IPC isn't a problem. Thanks for anything A: I think the best/easiest thing you could do is make the GUI only in C#, in windows clients you could use Windows Forms or WPF, in web based you can use ASP.NET WebForms or ASP.NET MVC. in all these cases except MVC (Razor) you have really good tools for designing and customizing the GUI within Visual Studio. Your C++ code can be wrapped in a class library or as you say accessed via some kind of IPC if it has to run as application, same for Java but if you are 100% free to write and re-write things you could also imagine to port the Java code to C++, this could be easy, difficult or impossible depending on what the java code does. at last resort if both C++ and Java applications must stay separated and must run in background on same or another machine and you still want to consume their services or methods from your C# GUI, as you mentioned, IPC is probably the way, not sure what you can do in Windows with Java and IPC, surely java can expose or consume XML web services. A: The problem you will find is that each has its own process model, and you either need to get the process models to coexist or you'll need several communicating processes (though the user need not see them). With Java, eg, it can be "king", or you can set up a sort of sub-process in another process, or you can have it set up/take down its process model on every call. Which approach is best depends in part on the complexity of the operations you'll be doing in the "guest" language. The one main thing, though, is that only one language can control the UI -- in general different language UIs don't coexist, and I doubt that you can have eg, a Java UI object in a C# GUI, at least not without treating it as a foreign window. A: If you're talking about the best language to rewrite the programs in, that depends entirely on the primary function. If you mainly need it to integrate with Windows nicely, C# would be the obvious choice. If your main idea is to make it cross-platform, it'd make most sense in Java. If you're talking about running them together and using IPC then yes, that's possible too - you could use anything from a fully blown IPC framework to a custom protocol over sockets on localhost. There shouldn't be too much of an issue there, though remember depending on how big the parts in other languages are, it may cost just as much in terms of time to rewrite them (and there's less of a maintenance burden that way too.) There's also complexities with controlling GUIs from other processes, it can be done ish by passing native canvas IDs around cross process, but it's hard to get working properly, may not be particularly safe and makes it quite difficult to work out what's going on from a maintenance perspective.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search in NSMutableDictionary only with partial key I want to know if there is a possibility to search in an NSMutableDictionary with a partial key. For Eg.: Let key be 2345 and partialkey can be 2 or 23 or 234,etc Thanks A: You can use the allKeys method to get an array of all the keys and then filter them based on your partial key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When calling TransformProcessType(), the app menu doesn't show up If you call TransformProcessType() like this : ProcessSerialNumber psn = { 0, kCurrentProcess }; (void) TransformProcessType(&psn, kProcessTransformToForegroundApplication); Then the cocoa app menu doesn't show up unless you call this early enough in your app (eg. in applicationWillFinishLaunching). A: Here is how I made it working. BOOL MakeAppForeground() { BOOL bSuccess = TranformAppToState(kProcessTransformToForegroundApplication); if(bSuccess) { bSuccess = (SetSystemUIMode(kUIModeNormal, 0) == 0); [NSApp activateIgnoringOtherApps:YES]; } return bSuccess; } BOOL MakeAppBackground() { return TranformAppToState(kProcessTransformToBackgroundApplication); } BOOL TranformAppToState(ProcessApplicationTransformState newState) { ProcessSerialNumber psn = { 0, kCurrentProcess }; OSStatus transformStatus = TransformProcessType(&psn, newState); if((transformStatus != 0)) { NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:transformStatus userInfo:nil]; NSLog(@"TranformAppToState: Unable to transform App state. Error - %@",error); } return (transformStatus == 0); } A: I asked Apple for help and they helped me very well. Quote : The reason why the menu bar isn't show when you call TransformProcessType is that your app is already the active app (that is, [[NSRunningApplication currentApplication] isActive] returns YES) and the menu bar for an app is shown when the app is activated This is their workaround : - (void)transformStep1 { for (NSRunningApplication * app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.finder"]) { [app activateWithOptions:NSApplicationActivateIgnoringOtherApps]; break; } [self performSelector:@selector(transformStep2) withObject:nil afterDelay:0.1]; } - (void)transformStep2 { ProcessSerialNumber psn = { 0, kCurrentProcess }; (void) TransformProcessType(&psn, kProcessTransformToForegroundApplication); [self performSelector:@selector(transformStep3) withObject:nil afterDelay:0.1]; } - (void)transformStep3 { [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps]; } A: Here is my solution, which is triggered on checkbox click in Preferences window. The only side effect is short flashing of the app's windows: - (void) hideDockIcon:(bool) hide { ProcessSerialNumber psn = { 0, kCurrentProcess }; ProcessApplicationTransformState state = hide ? kProcessTransformToUIElementApplication : kProcessTransformToForegroundApplication; OSStatus err = TransformProcessType(&psn, state); if (err) { NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]; NSLog(@"TransformProcessType failed: %@", error); } } - (void) toggleDockIcon { [NSApp hide:self]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self hideDockIcon:self.preferences.hideDockIcon]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [NSApp activateIgnoringOtherApps:YES]; }); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Unable to get Events with specific location using restFB I am unable to fetch all sports events happening in the state of Georgia. Is this the right way to use this, since its currently retrieving all events across the country. FacebookClient publicFbClient = new DefaultFacebookClient(); Connection<Event> events = publicFbClient.fetchConnection( "search", Event.class, Parameter.with("category", "Sports"), Parameter.with("location", "Georgia"), Parameter.with("type", "event")); A: There's no mention in the doc of the ability to limit results geographically except center (latlong) and distance (radius) when the type place is defined. You can set the radial search variables for events but doing so doesn't appear to change the results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ignore with CSS? I'm working on a site which has line breaks inserted as <br> in some of the headings. Assuming I can't edit the source HTML, is there a way with CSS I can ignore these breaks? I'm mobile optimising the site so I don't really want to use JavaScript. A: You can use span elements instead of the br if you want the white space method to work, as it depends on pseudo-elements which are "not defined" for replaced elements. HTML <p> To break lines<span class="line-break">in a paragraph,</span><span>don't use</span><span>the 'br' element.</span> </p> CSS span {white-space: pre;} span:after {content: ' ';} span.line-break {display: block;} span.line-break:after {content: none;} DEMO The line break is simply achieved by setting the appropriate span element to display:block. By using IDs and/ or Classes in your HTML markup you can easily target every single or combination of span elements by CSS or use CSS selectors like nth-child(). So you can e.g. define different break points by using media queries for a responsive layout. And you can also simply add/ remove/ toggle classes by Javascript (jQuery). The "advantage" of this method is its robustness - works in every browser that supports pseudo-elements (see: Can I use - CSS Generated content). As an alternative it is also possible to add a line break via pseudo-elements: span.break:before { content: "\A"; white-space: pre; } DEMO A: With css, you can "hide" the br tags and they won't have an effect: br { display: none; } If you only want to hide some within a specific heading type, just make your css more specific. h3 br { display: none; } A: For me looks better like this: Some text, Some text, Some text br { display: inline; content: ''; } br:after { content: ', '; display: inline-block; } <div style="display:block"> <span>Some text</span> <br> <span>Some text</span> <br> <span>Some text</span> </div> A: If you add in the style br{ display: none; } Then this will work. Not sure if it will work in older versions of IE though. A: This is how I do it: br { display: inline; content: ' '; clear:none; } A: Note: This solution only works for Webkit browsers, which incorrectly apply pseudo-elements to self-closing tags. As an addendum to above answers it is worth noting that in some cases one needs to insert a space instead of merely ignoring <br>: For instance the above answers will turn Monday<br>05 August to Monday05 August as I had verified while I tried to format my weekly event calendar. A space after "Monday" is preferred to be inserted. This can be done easily by inserting the following in the CSS: br { content: ' ' } br:after { content: ' ' } This will make Monday<br>05 August look like Monday 05 August You can change the content attribute in br:after to ', ' if you want to separate by commas, or put anything you want within ' ' to make it the delimiter! By the way Monday, 05 August looks neat ;-) See here for a reference. As in the above answers, if you want to make it tag-specific, you can. As in if you want this property to work for tag <h3>, just add a h3 each before br and br:after, for instance. It works most generally for a pseudo-tag. A: For that you can just do like this: br{display: none;} and if it is inside some PRE tag, then you can and if you want the PRE tag to behave like a regular block element, you can use this CSS : pre {white-space: normal;} Or you can follow the style of Aneesh Karthik C like : br {content: ' '} br:after {content: ' '} I think you got it A: As per your question, to solve this problem for Firefox and Opera using Aneesh Karthik C approach you need to add "float" right" attribute. Check the example here. This CSS works in Firefox (26.0) , Opera (12.15), Chrome (32.0.1700) and Safari (7.0) br { content: " "; float:right; } I hope this will answer your question!! A: While this question appears to already have been solved, the accepted answer didn't solve the problem for me on Firefox. Firefox (and possibly IE, though I haven't tried it) skip whitespaces while reading the contents of the "content" tag. While I completely understand why Mozilla would do that, it does bring its share of problems. The easiest workaround I found was to use non-breakable spaces instead of regular ones as shown below. .noLineBreaks br:before{ content: '\a0' } Have a look. A: Yes you can ignore this <br>. You may need this especially in case of responsive design where you need to remove breaks for mobile devices. HTML <h2> Where ever you go <br class="break"> i am there. </h2> CSS for mobile example /* Resize the browser window to check */ @media (max-width: 640px) { .break {display: none;} } Check out this Codepen: https://codepen.io/fluidbrush/pen/pojGQyM A: You can usedisplay:contents br { display:contents; } see https://developer.mozilla.org/en-US/docs/Web/CSS/display-box [display:contents;] These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes [...] most browsers will remove from the accessibility tree any element with a display value of contents. [...] no longer be announced by screen reading technology. A: You can simply convert it in a comment.. Or you can do this: br { display: none; } But if you do not want it why are you puting that there?
{ "language": "en", "url": "https://stackoverflow.com/questions/7596647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: how to clear an NSMutableArray of custom objects without creating memory leaks? If I have an NSMutableArray of custom objects, how can I must easily clear the array without causing any memory issues? Assume that the custom object class has a dealloc method in it which correctly released an instance variables etc. For example is it ok to use the NSArray "removeAllObjects" method? * *If yes - how does this work - does "removeAllObjects" call the "dealloc" method on each object as it removes them *If no - what would be the easiest approach to use? EDIT (after 4 replies) - One last question of clarification after the great replies - I'm still not quite sure about the instance variables/properties in my custom object that I have set to retain? These seem to be only released via the the "dealloc" method in my custom object class, where we do this manually along with [super release]. So if, re clearing an array, if I do a removeAllObjects, and then NSArray issues a "release" to my custom objects, but doesn't call "dealloc", then how do my instance variables get released? A: removeAllObjects will remove the object from the array. This process will send a release message to the object and this will decrease its reference count. When the reference count reaches zero the object will be deallocated. don't do it like this, because it will leak. NSObject *object = [[NSObject alloc] init]; + 1 [array addObject:object]; + 1 [array removeAllObjects]; - 1 ======= = + 1 -> Leak this is the correct way: NSObject *object = [[[NSObject alloc] init] autorelease]; + 1 (from alloc) - 1 (from autorelease) [array addObject:object]; + 1 [array removeAllObjects]; - 1 ======= = 0 -> Object will be deallocated Instead of calling removeAllObjects you could just release the array. If an array is deallocated everything that's inside of it gets released and if there is no other reference to the object it will be deallocated. A: Yep, just call removeAllObjects. Just to be sure, you don't call retain when you add an object to an array or when you create an array with objects. That's done for you automatically. Regarding dealloc, again that will be done automatically, and you can't predict when. The only thing you need to have in the dealloc is the array object itself. That is, assuming it's an instance variable or ivar? To check everything is good, run the Analyzer using Product -> Analyze. And then give the app a profile in Instruments using the Leaks instrument to check that none of your code is causing any memory leaks. A: The dealloc method is never called directly. Everything is done thru the retain/release mechanism (and the reference counting principle). So this is the release method that gets called, not the dealloc directly. The dealloc method is only called by the runtime if the last release call causes the reference counting (retainCount) of the object reaches zero, meaning that the object really is deallocated from memory as noone uses it anymore. NSArray and all container classes in Cocoa (NSDictionary, NSSet, ...) do retain their values. So when you add an objet to a container like NSArray, it will retain that value. And when you remove that value (including when you call removeAllObjects") it will release it. Memory Mgmt rules are easy to follow: but the only rule that matters it that you only have to call release or autorelease if you called alloc, retain or copy methods. That's always the responsability of the objet which did the alloc/retain/copy to call the release/autorelease. Never leave a alloc/retain/copy without a pending release/autorelease call to balance it (or you will have leaks), but on the other hand never call release/autorelease if you didn't do the alloc/retain/copy call yourself. Good example 1: MyClass* obj = [[MyClass alloc] init]; // here you do an alloc [myArray addObject:obj]; // the NSArray "myArray" retains the object obj // so now you can release it, the array has the responsability of the object while it is held in the array [obj release]; // this release balance the "alloc" on the first line, so that's good [myArray removeAllObjects]; // there the object held by the array receive a release while being removed from the array. As nobody retains it anymore, its dealloc method will be called automatically. Good example 2: MyClass* obj = [[MyClass alloc] init]; // here you do an alloc [myArray addObject:obj]; // the NSArray "myArray" retains the object obj // so now you can release it, the array has the responsability of the object while it is held in the array [myArray removeAllObjects]; // there the object held by the array receive a release while being removed from the array. But your own code still retains a reference to it (because of the "alloc" on first line) so it won't be removed from memory right now [obj release]; // this release balance the "alloc" on the first line, and as nobody retains the object anymore, its dealloc method will be called and it will be deallocated from memory Good example 3: MyClass* obj = [self getSomeObjectFromAnotherMethod]; // here you don't have an "alloc" on this line [myArray addObject:obj]; // the array retains the object [myArray removeAllObjects]; // the array release the object while it removes it from the array // no need to call "release" here as there is no "alloc" done in the scope of this code Bad example: MyClass* obj = [self getSomeObjectFromAnotherMethod]; // here you don't have an "alloc" on this line [myArray addObject:obj]; // the array retains the object [myArray removeAllObjects]; // the array release the object while it removes it from the array [obj release]; // Crash here! obj does not exists anymore and has been deallocated from memory before this line! A: Basically removeAllObjects method sends release message to all the objects. The release method decrements the objects reference count. And if the reference count of an object reaches 0 then the dealloc message will be sent to the object. The answer to your question is calling [array removeAllObjects] is completely safe. By the way if you don't want the array anymore you can directly call [array release] which releases all its objects as well as the array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Bash Substring File Completion Does bash partial/substring file completion similar to what zsh does? That is, instead of requiring the user to enter a prefix of the filename, then tab; the user can also enter a substring of the filename, then tab. Say a directory contains a file abcdef, then not only would ab<tab> complete to this filename, but also bc<tab> and cd<tab> and so on. A: If a directory contains the file abcdef, then you can enter *bc* and then hit the TAB key, and it will complete. Of course, zsh can do it without the *, so it's not the same thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: can we override alloc and dealloc in objective C? I know that this is rarely required to override the alloc or dealloc methods,but if required is it possible in iPhone programming? A: In general, overriding alloc is only done when you wish to, eg, allocate an object from a pool of available instances, or perhaps allocate a variable amount of storage for the object based on some external parameter. (In C++ you can access the new parameters and allocate based on them, but Objective-C does not give you access to the initXXX parameters.) I've never attempted any of this, and I suspect that its a bit of a minefield -- you need to study up on the structures and be pretty careful. As Adam said, you should ALWAYS (in a reference counted environment) override dealloc if there are any retained objects held by your object. Update: An interesting thing you can do ... in RedClass or a superclass of it code something like: +(id)alloc { if (self == [RedClass class]) { return [BlueClass alloc]; } else { return [super alloc]; } } The net result is that whenever you execute [RedClass alloc] a BlueCLass object will be returned. (NB: Presumably BlueClass is a subclass of RedClass, or things will get seriously mucked up shortly after the object is returned.) Not saying that it's a good idea to do this, but it's possible (and I don't offhand know of any cases where it wouldn't work reliably for vanilla user-defined classes). And it does have a few possible uses. Additional note: In some cases one might want to use [self isSubclassOf:[RedClass class]] rather than == (though that has some serious pitfalls). A: You can and indeed, you should (if using manual memory management) override dealloc to release any resources you hold (not forgetting to call [super dealloc] when finished). Overriding alloc is possible but, as you say, rarely needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: google checkout digital products Basically I want a functionality to download code mywebsite. I checked following link for google checkout digital products. https://checkout.google.com/support/sell/bin/answer.py?answer=39011 I created buy now button for digital product from sandbox using this link.HTML code redirects me to google checkouts as usual. But it does not give me any download link anywhere after payment. ?? <form action="https://sandbox.google.com/checkout/api/checkout/v2/checkoutForm/Merchant/859574590497884" id="BB_BuyButtonForm" method="post" name="BB_BuyButtonForm" target="_top"> <input name="item_name_1" type="hidden" value="mycode"/> <input name="item_description_1" type="hidden" value="this item is all about my code"/> <input name="item_quantity_1" type="hidden" value="1"/> <input name="item_price_1" type="hidden" value="1251.0"/> <input name="item_currency_1" type="hidden" value="USD"/> <input name="shopping-cart.items.item-1.digital-content.description" type="hidden" value="Please read this instructions.."/> <input name="shopping-cart.items.item-1.digital-content.url" type="hidden" value="http://www.xxxxxxxx.in/xxxxxxxx/xxxxxx/20110929034224791156.pdf"/> <input name="_charset_" type="hidden" value="utf-8"/> <input alt="" src="https://sandbox.google.com/checkout/buttons/buy.gif?merchant_id=859574590497884&amp;w=117&amp;h=48&amp;style=white&amp;variant=text&amp;loc=en_US" type="image"/> A: You need to use continue_url <input type="hidden" name="continue_url" value="http://www.example.com/download"/> A: Google Checkout offer a digital delivery solution, with various options for providing access to the digital content. Please be aware that credit card transactions are authorized and charged AFTER the user places the order. Depending on how valuable the content is, you may want to hold off providing the URL to the download content until payment is guaranteed. More details in this doc: http://code.google.com/apis/checkout/developer/Google_Checkout_Digital_Delivery.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7596658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Permissions in SQL Server 2008 I have created 10 database of 'Northwind' for training purpose. Suppose I have 10 students, so databases are Northwind_Student1,Northwind_Student2 etc. I would like to create separate login for each pupil, so that Student1 can only see(or can access) the data base 'Northwind_Student1'. How can I accomplish this using T-SQL or SSMS 2008 ? A: You can create different users for different databases and assign permissions like below. It's for SQL 2008, but it will be same for 2005 also : A: Create 10 different logins and assign each to the database it can access. A: In SSMS, expand the Security tree of the server in Object Explorer and right-click Logins to choose New Login..., then add as many as needed. Then in the Security tree of each individual database, add the login as a user of that db and grant appropriate rights. A: CREATE LOGIN yourloginname WITH PASSWORD = 'yourpassword'
{ "language": "en", "url": "https://stackoverflow.com/questions/7596663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Regex for wrapping digits with curly braces? I am trying to using Python's re.sub() to match a string with an e character and insert curly braces immediately after the e character and after the lastdigit. For example: 12.34e56 to 12.34e{56} 1e10 to 1e{10} I can't seem to find the correct regex to insert the desired curly braces. For example, I can properly insert the left brace like this: >>> import re >>> x = '12.34e10' >>> pattern = re.compile(r'(e)') >>> sub = z = re.sub(pattern, "\1e{", x) >>> print(sub) 12.34e{10 # this is the correct placement for the left brace My problem arises when using two back references. >>> import re >>> x = '12.34e10' >>> pattern = re.compile(r'(e).+($)') >>> sub = z = re.sub(pattern, "\1e{\2}", x) >>> print(sub) 12.34e{} # this is not what I want, digits 10 have been removed Can anyone point out my problem? Thanks for the help. A: re.sub(r'e(\d+)', r'e{\1}', '12.34e56') returns '12.34e{56}' or, the same result but different logic (don't replace e with e): re.sub(r'(?<=e)(\d+)', r'{\1}', '12.34e56') A: Your brace placement is incorrect. Here's a solution ensuring the that there's a number with optional decimal place before the e: import re samples = ['12.34e56','1e10'] for s in samples: print re.sub(r'(\d+(?:\.\d+)?)e([0-9]+)',"\g<1>e{\g<2>}",s) Yields: 12.34e{56} 1e{10}
{ "language": "en", "url": "https://stackoverflow.com/questions/7596667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XCode compiles entire project each time I run On a new project I have started, XCode has decided that it will compile every file in the project every time I run it, rather than just compiling files that change (and files dependent on those). As there are getting to be more and more files in the project, this becomes a bigger and bigger burden in both time and battery life. It is possible that I have changed a setting somewhere that affected this; or, maybe not. What are some project settings that I should be looking at? A: If Xcode recompiles most or all of your source files whenever you do a build, that usually means that those files are all directly or indirectly dependent on some header file that has changed. Here are some things to look for: * *Do your source files tend to #import some top-level header file that itself recursively imports a bunch of lower-level header files? If any file in that tree of dependent headers is modified, it will force recompilation of any .m file that imports the top-level header file. You may be able to reduce these dependencies by importing headers for lower level submodules, or better yet, for just the specific headers you need for each file. (Note: Some libraries that aren't designed to be used this way can make this approach challenging or impossible in some cases.) *Some third party development tools and static libraries run scripts that generate or modify code as part of their build process. If your source files are dependent on a header file that's generated by a script, they'll be recompiled every time the script regenerates that header file. Even if the code generated by the script doesn't change, dependent source files will be recompiled if the last-modified date of the header file changes. It may take some clever hacking to eliminate redundant compilation if this is your issue. *Don't forget to check your precompiled header (.pch) file to see what's being imported there. The contents of that file are effectively injected at the top of every .m file in your project at compile time. *Try to minimize dependencies by moving as many #import statements as possible out of your .h files and into your .m files. You can generally get away with just importing the headers for your class's superclass and any protocols your class implements in its .h file. You can use forward declarations instead of #import statements for any other classes, data types, or protocols you use in your class's @interface. A: I realize this question is over a month old, but I had a similar problem in moving an old project to Xcode 4. After much hair-rending, I discovered that Xcode 4 (4.2 in my case) has a bug where, if there are any non-ASCII characters in the full path either of a source file, or in the full path of any headers the source file includes, it will be recompiled every time you build. This includes the prefix header, in which case a full compile will be triggered every time. In my case, the previous programmer had appended 'ƒ' to several folder names, and once I removed those, it worked perfectly. Anyway, I stumbled upon this question during my (unsuccessful) attempts to Google an answer and thought I'd share my solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Month cannot be altered in Silverlight DatePicker when custom CalendarStyle is specified I've taken a DatePicker and customised the style for usage on a tablet. I'm finding that while days can be selected the month cannot be changed. Neither clicking the previous/next button or on the month name has any affect, although the mouseover style is applied. I've taken the default Calendar style and inserted a Viewbox to increase the size, as suggested by Mike Taulty: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2010/11/17/touched-part-5-touch-ready-controls.aspx <Style TargetType="controls:Calendar" x:Key="TabletCalendar"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="controls:Calendar" xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"> <StackPanel x:Name="Root" HorizontalAlignment="Center" > <Viewbox Width="480" Height="440"> <controlsPrimitives:CalendarItem x:Name="CalendarItem" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" xmlns:controlsPrimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls" /> </Viewbox> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style TargetType="controls:DatePicker" x:Key="TabletDatePicker"> <Setter Property="CalendarStyle" Value="{StaticResource TabletCalendar}" /> ..... </Style> A: Fixed by moving the Viewbox up a level in the visual tree, not sure why there was a fault here but is working fine now!
{ "language": "en", "url": "https://stackoverflow.com/questions/7596672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: camera problems in android in my app i am capturing video and save it to sdcard. my below code is working fine since api level 8. but if i run my app below api level 8(from 7) it get crashed. it says java.lang.NoClassDefFoundError: android.media.CamcorderProfile. how to run my app with the all version/level supported? what is the alternative for CamcorderProfile class. my code is .............. mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); // NoClassDefFoundError: android.media.CamcorderProfile error occur here. mediaRecorder.setProfile(camcorderProfile_HQ); mediaRecorder.setOutputFile("/sdcard/myvideo.mp4"); mediaRecorder.setMaxDuration(60000); mediaRecorder.setMaxFileSize(5000000); ..................... please help me. Thanks in advance. my Logcat details: 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): java.lang.NoClassDefFoundError: android.media.CamcorderProfile 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at com.exercise.AndroidVideoCapture.AndroidVideoCapture.initMediaRecorder(AndroidVideoCapture.java:84) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at com.exercise.AndroidVideoCapture.AndroidVideoCapture.onCreate(AndroidVideoCapture.java:28) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.os.Handler.dispatchMessage(Handler.java:99) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.os.Looper.loop(Looper.java:123) 09-29 16:44:06.971: ERROR/AndroidRuntime(7800): at android.app.ActivityThread.main(ActivityThread.java:4363) ............................ A: You can use the code below if you are not using CamcorderProfile because CamcorderProfile has been introduced since API level 8. mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
{ "language": "en", "url": "https://stackoverflow.com/questions/7596674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS: dynamic width of child elements to be fit the parent width When writing CSS, I always find myself missing auto child width feature of floated child elements, to fit their total width to the parent's width. In fact I find it hard to phrase in Google search box, so you may consider this example: A ul contains four li li has float: left; list-style: none; and because there are four li elements, each has width: 25%; What if I want to make the number of li elements variable, instead of fixed four, so li gets width of 20% when they are five, or gets width of 10% if they are ten, or width of 50% when they are two etc..? Given that the ul has an explicit fixed width always. A: Try display: table; Here's a fiddle with it: http://jsfiddle.net/7D5cM/ A: You might be able to use css3's flex-box. ul{display:box;} li{box-flex:1;} Here's a jsfiddle to demonstrate(you may need to change -webkit to -moz or -o) http://jsfiddle.net/wKKte/
{ "language": "en", "url": "https://stackoverflow.com/questions/7596681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "unable to start debugging on the web server" MSVSMON.EXE failed to start. VS2010 error having a real problem getting VS2010 to debug IIS. I've searched on the internet for a few days now and tried every single solution I can. VS2008 works perfectly but I've installed VS2010 and when trying to debug an IIS site (by pressing F5 on a project that uses IIS) I get the error message "unable to start debugging on the web server. Microsoft Visual Studio Debugging Monitor (MSVSMON.EXE) failed to start. If this problem persists, please repair your Visual installation via "add or remove programs" in the control panel." when i try attaching the process manually, i get the same message. I've tried repairing the software. I tried it, it failed, so I uninstalled using the Microsoft Visual Studio 2010 Uninstall Utility (http://archive.msdn.microsoft.com/vs2010uninstall/Release/ProjectReleases.aspx?ReleaseId=4321), then reinstalled and it still has the same problem. With the SP1 update this still happens. I can run the website fine when running "start without debugging" and it runs fine. I've gone through all the guides I can and all tried all the settings on IIS I can and still no luck. I'm using Windows 7 64bit if that means anything. I can detail much more about all the things i've tried. also have a laptop and have done the same, installing VS2010 and TFS (also on win7 64bit), and this works perfectly for debugging. Didn't have to mess around at all. I can't see any difference between this and my PC with the problem. I'm scratching my head here and thinking I might have to format my PC and try again from a fresh install (which would be seriously annoying!) Thanks to anyone that reads this, Dan Gent A: I had a HOSTS file entry resolving the project URL to a DEV server instead of local machine. Changing the entry to point to 127.0.0.1 fixed the problem. A: Are you installing from a purchased disc or did you download it? Either way, you need to download a fresh copy and install that (sounds like original is corrupted). Also, make sure you have all the IIS & Web components installed on your machine. Is your OS home or basic? http://technet.microsoft.com/en-us/library/cc731911.aspx A: i've fixed it now. ended up formatting machine, reinstalling windows 7, and then taking backups everytime i installed a new program so i could roll back. installed VS2010 first, F5 worked. then installed VS2008 & everything else and debugging still works on VS2010. not sure what happened as the above problem happened on a fresh install. something must have corrupted something somewhere thanks for all your help and narrowing this problem down to something that was worth formatting my PC to fix. cheers, Buswell A: This can also be caused if you are using a host name in IIS and make a mistake in your hosts file. Check that the hosts ip is set to the local machine 127.0.0.1 and not somewhere else. In my case I had accidentally set it to the development server. A: Have you tried starting MSVSMON manually? I had the same problem you are and found the service was stopped. So I tried enabling the service and made sure that it was using the correct credentials. I hope this helps! Thanks! Don A: The only thing that worked for me after I tried practically every solution on the Web is to right-click the project on the solution explorer, and select Debug->Debug as Administrator. A: Right click on Project, "Use Custom web server" checkbox will be selected, select check box "Use local IIS web server". I resolved this issue with this and its working. A: Managed to resolve this error by At solution explorer-> right click the project->select Debug->Start new instance. I think it was because i had copied the project folder from another server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Star plugins for Symfony I use Symfony 1.4.12 . If i install http://www.symfony-project.org/plugins/sfWidgetFormJqueryRatingPlugin or http://www.symfony-project.org/plugins/mpStarRatingPlugin i have error: You try to install a symfony 1.0 plugin. Please read the help message of this task to know how to install a plugin for the current version of symfony. previously without a problem i installed sfGuardDoctrinePlugin. How can i fix it? A: It seems that the package was not updated. Did you tried to use the svn trunk version?
{ "language": "en", "url": "https://stackoverflow.com/questions/7596696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF service taking userPincipleNname instead of passed in string as argument This is a weird issue. I am passing in strings into my service, and that string would be the username of the person logged into my website (via windows authorization). I get the string from my website using HttpContext.User.Identity.Name.ToString() I parse it from the domain and just get the user Identity. And then I call a wcf service whose contract is similar to this... generalWCFContractImplementation(string userID); Now, you would think it would pass in the string that I sent it... However, that is indeed not the case. After doing some debugging, I found out that the string that is being passed in is the userPrincipleName that I am using to setup the WCF connection! Now why on earth would it do that? I am checking all throughout my code to see if accidentally change the userID in some way, but I check as soon as I enter the function what the value of the ID is, and it is the userPrincipleName! I am extremely confused about what is going on here. Does anybody have any idea why that would occur? and how can I remedy that? Thanks. UPDATED with code public string GetOwnedPopulations(string userID) { Log.TraceEvent(System.Diagnostics.TraceEventType.Information, string.Format("Entered Method GetOwnedPopulations() CallerNameOnly: {0}, userID: {1} CallerNameOnly==userID {2}", CallerNameOnly, userID, CallerNameOnly == userID), "General"); this.CallerFullDomain = userID; this.CallerNameOnly = userID;// this.CallerFullDomain.Substring(this.CallerFullDomain.IndexOf('\\') + 1); string ans; Log.TraceEvent(System.Diagnostics.TraceEventType.Information, string.Format("Entered Method GetOwnedPopulations() CallerNameOnly: {0}, userID: {1} CallerNameOnly==userID {2}", CallerNameOnly , userID, CallerNameOnly==userID), "General"); searchPopulationbyOwner oReq = new searchPopulationbyOwner(); oReq.ownerName = this.CallerNameOnly; try { StringBuilder sbBuffer = new StringBuilder(); PopulationManagementClient client = UPMC.ISD.EADIS.PopulationManagement.PopManSvc.Utils.GetClient(this.CallerNameOnly); searchPopulationbyOwnerResponse resp = client.searchPopulationbyOwner(oReq); Log.TraceEvent(System.Diagnostics.TraceEventType.Information, string.Format("Getting Null Values?: {0}", (resp == null ? ans="yes" : ans="no")), "General"); XmlSerializer xs = new XmlSerializer(typeof(Population[])); System.IO.StringWriter sw = new System.IO.StringWriter(sbBuffer); xs.Serialize(sw, resp.populationList); string sPopulationtXML = sbBuffer.ToString(); return sPopulationtXML;// client.searchPopulationbyOwner(oReq); } catch { throw; } } As you can see, I pass in the username, and I then set the object that I am going to pass in equal to the user ID. The thing is, userID is either the applicationPoolID, but I am guessing more than likely it is the userPrincipleName (which would happen to be the same as the applicationPoolIdentity... I am not sure if they have to be the same or not). But this is very weird. I have know idea why on earth that would be passed in and not the actual username... And yes, I have looked at my site to see what is being passed in, and it is indeed, the userID... When it hits the service however, it is the userPrincipleName. Confused?????
{ "language": "en", "url": "https://stackoverflow.com/questions/7596698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can i move an element within a list of images? with JQuery i have a list of images <img src="image-1.jpg" /> <img src="image-2.jpg" /> <img src="image-3.jpg" /> <img src="image-4.jpg" /> <img src="image-5.jpg" /> whats the best way to reorder them such that image-1 is at the bottom? (but not necessarily image-1) Edit: Preferably without using anything like the JQuery UI. I would like this to be done with as little code as possible. A: Simple and easy $(function(){ var parent=$("img").parent(); $("img:first").appendTo(parent); }); A: You can achieve this by using the jQuery UI: http://jqueryui.com/demos/sortable/ (Supposing you want this to be dynamic, if not you should further explain the exact situation) A: If you are not trying to create a dynamic sortable list and are just looking for a way to re-order images. You could try the following. $("img[src$='image-1.jpg']").insertAfter("img[src$='image-5.jpg']"); This will allow you to find images and move them around based on the src of the image. http://api.jquery.com/category/manipulation/ Look at the different methods that are available for DOMinsertion. A: Then you want like something this? It sorts 1,2,3,4,5 to 5,4,3,2,1 <div id="reorder"> <img src="http://www.google.com.tr/images/srpr/logo3w.png" /> <img src="http://l.yimg.com/a/i/ww/met/logo/20100909/yahoo_logo_tr.png" /> <img src="http://www.rev2.org/wp-content/uploads/2009/06/bing-logo.png" /> <img src="http://a.l.yimg.com/a/i/us/sch/yhs4/altavista_logo.png" /> <img src="http://searchcdn.infospace.com/Dogpile-8.0.1.353/Content/Img/img_trans.gif?av=1353" /> </div> <script> $(function() { $('#reorder').click(function() { $("#reorder").randomize("img"); }); }); (function($) { var onerandom = Math.random(); $.fn.randomize = function(childElem) { return this.each(function() { var $this = $(this); var elems = $this.children(childElem); elems.sort(function() { return (Math.round(onerandom)-0.5); }); $this.remove(childElem); for(var i=0; i < elems.length; i++) $this.append(elems[i]); }); } })(jQuery); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to bind multiple events with .live in jQuery? I have an input text with two events and dinamically I clone it several times. To bind this elements correctly I use: NOTE: This input text has the focusin and focusout events. $('[selector_input]').die().live( 'focusin', function() { alert( 'You focused me' ); }); $('[selector_input]').die().live( 'focusout', function() { alert( 'Bye!' ); }); The final result is that all inputs only executes: focusout event. If I don't use .die(), I will get repeated call the same events. Now the solution could be: $('[selector_input]').die().live( 'focusout focusin', function(event) { if (event.type == "focusin") alert( 'You focused me' ); else alert( 'Bye!' ); }); But I like and independence like the first code. A: Just specify the event type for the call to die() $('[selector_input]').die('focusin').live( 'focusin', function() { alert( 'You focused me' ); }); $('[selector_input]').die('focusout').live( 'focusout', function() { alert( 'Bye!' ); }); I'm not quite sure why you need the die() call though, are you binding the events repeatedly? A: You could do something like $('path to your input').live({ focusin: function() { $('some output div').html('Focus!'); }, focusout: function() { $('some output div').html('Bye!'); } }); or you could just remove the .die() -- its very purpose is to remove the previous event handlers for that selector. If you're playing with alert boxes, i wouldn't mess with focus events at the same time -- the alert box becomes the active thingie when it appears, causing focused stuff to unfocus (and then possibly refocus), and causing your event handler to get called sometimes infinitely. BTW, see http://jsfiddle.net/9pjWa/ for an example of how to use .live() -- it sounds like you're doing it wrong. The very point of .live() is that you do not need to re-bind the events every time you add an element; the event handler is on the document, not the elements, and each element that matches the selector can trigger the event whether they were added before or after .live(). In fact, every time you re-bind, you add another event handler that handles all of the matching elements, which is another reason why you're seeing the event handler called a bunch of times.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: technical comparison between the differences in html of jquery mobile and webapp-net I am trying to build an application for smart phone devices. I have searched a lot over the web and I found some good toolkits, These are the toolkits I am considering to work with. Jquery Mobile and webapp-net. The only problem is I need to kknow about the technical differences in html of these two toolkits. so if you please help me. BTW this is my second account here, with my previous account i cant not ask any questions here, I want to know what are the reasons to close someones account, I am only here because I need help, and I dont want to waste anyones time. I come here to ask a question and then, some one comes and just does something to my account and I dont even know why they do that. So what is the point of this website if you close some ones account??? A: When consider Jquery Mobile and webapp-net, JM is elder and is coming from rich and stable family, that never ment webapp is poor, but you have much recourses and help from the net if u start ur work with JM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash games should I use MP3 or WAV file format? I'm developping a flash game and I'm wondering what audio format is more suitable (MP3 or WAV)? I understand that MP3 is much smaller but it has worst audio quality when is compared to WAV files. Thank you for your opinion. A: From Adobe's Programming AS3 (Chapter Working with sound --> Basics of working with sound), Although there are various sound file formats used to encode digital audio, ActionScript 3.0, Flash Player and AIR support sound files that are stored in the mp3 format. They cannot directly load or play sound files in other formats like WAV or AIFF. If you embed any other format in fla, then that will be converted to mp3 during publish. A: You should try OGG: http://en.wikipedia.org/wiki/Ogg And also, WAV would be far too big. MP3 with 320 kbps should be sufficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Matlab `imagesc`: how to display with smooth colors? I have a matrix which I display with imagesc. Now I'm asked to make an "interpolated" version (i.e. display with smoother colors). While I could compute a larger interpolated matrix, I seem to remember that there was a command to switch between two such display modes, either a little command in the style of axis equal or some Property - but I just cannot find it. A: You may want to use pcolor instead of imagesc and set the shading properties to interp. Note that pcolor and imagesc will not display your data in the same way but the shading property is only available for faceted plots. However this is only a display solution, you will have to interpolate your data if you want to work with it afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to print the value for the Node of xml on console in blackberry I have created the NODES for parsing but i dont know how to display the values within that NODE. hear is my NODE for that i want t\o print the value in console of eclipse. enter code here for(int j=0; j<tempList.getLength(); j++){ if(tempList.item(j).getNodeName().equalsIgnoreCase("btitle")){ tempNode = tempList.item(j); tempNode2 = ((NodeList)tempNode.getChildNodes()).item(0); bean.setTitle(tempNode2.getNodeValue().trim()); // System.out.println("Node Value or title" +bean.getTitle() ); } A: Have a look here for pretty printing an XML: XML Writer class The code sample at the top of the page shows you how you can pretty print an xml given an output stream. To get a pretty-printed output stream using DOM, see the answer here by Ted_Hopp: DOM Printing
{ "language": "en", "url": "https://stackoverflow.com/questions/7596707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How could I be notified of a new Facebook comment on any of my site's pages? I've a site, say, example.com with many individual pages that are created dynamically (example.com/a/, example.com/b/ etc), each of which has its own Facebook Comment box. Is it possible for me to be notified whenever a user comments in any one of those pages? A: Looking at the facebook-graph-api documentation about the "Subscription" object which looks like it should be possible to set up callbacks that you need when posts are made to a particular page. http://developers.facebook.com/docs/reference/api/subscription/ However you ask in particular about comments, and there's a comment on this page about exactly this point - it leads you over to this post - http://facebook.stackoverflow.com/questions/5957007/facebook-graph-api-subscription-to-posts-notes Here @bigtallbill just seems to be suggesting that the subscription and callback is not giving a complete or reliable feed of the comments and he talks about doing polling instead (and then links to batchapi presumably to manage the number of queries needed. http://facebook.stackoverflow.com/questions/5957007/facebook-graph-api-subscription-to-posts-notes
{ "language": "en", "url": "https://stackoverflow.com/questions/7596708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Visual Studio (2010) updates IDL file automatically upon change in my code? When I make a change in my ATL class (e.g. adding new interface or implementing a new method), do I need to update the IDL file or the Visual Studio (2010) does it automatically (when not using wizards) ? [Sorry.. somewhat NOOBie question..] EDIT: Rephrasing: the only way to evade updating the IDL file manually every time is using the Visual Studio wizards ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7596711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Profile Unit test code which is written is cpp Is there any way we can profile unit test cases which are written for cpp program. I have implemented code coverage using gcov A: Since you have mentioned gcov, how about gprof, will that work for you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7596715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent a set of MSIs with common Upgrade code from installing post install of my msi? I distribute 2 msis A.msi and B.msi . I have been distributing it for long time and every new release maintains the same Upgrade code and new higher version. I have now a new msi C.msi . After installing C.msi, I want that the users should not be allowed to install any version of A.msi and B.msi . C.msi removes any existing A.msi and B.msi but I am unable to prevent installation post C.msi install. I use WIX to build my MSI. A: You cannot prevent already distributed installers from being installed over another package. So there's not much you can do. It would have worked only if A and B would have been configured from the start to stop if C is found.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Having exception. Spring 3 with Spring Tool Suite, Tomcat 7 and Maven I am new to Spring 3. I newly installed Eclipse Indigo, Spring Tool Suite. Using Spring Tool Suite "Spring Template --> Spring MVC project". I created a Hello world application. When running the application. It gives a exception. java.lang.LinkageError: loader constraint violation: when resolving interface method "javax.servlet.jsp.JspApplicationContext.getExpressionFactory()Ljavax/el/ExpressionFactory;" the class loader (instance of org/apache/jasper/servlet/JasperLoader) of the current class, org/apache/jsp/index_jsp, and the class loader (instance of org/apache/catalina/loader/StandardClassLoader) for resolved class, javax/servlet/jsp/JspApplicationContext, have different Class objects for the type javax/el/ExpressionFactory used in the signature org.apache.jsp.index_jsp._jspInit(index_jsp.java:31) org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:49) org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:181) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:370) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333) javax.servlet.http.HttpServlet.service(HttpServlet.java:722) What is wrong with the set up A: Remove any el-api.jar from WEB-INF/lib If you are running from within the IDE, you should have the el-api.jar with provided scope at most. Even with that it may still fail, because the IDE sometimes doesn't take into account the scope. I think the m2e-wtp plugin should fix it. A: it's because the template is created for Tomcat 6.0 with JSP 2.1 and Tomcat 7.0 works with JSP 2.2. As you can see in this page: http://tomcat.apache.org/whichversion.html. I try to change the jsp jar for a 2.2 in the pom.xml and add the el-api 2.2. but it's not enought. I don't find the final problem. Finally I choose to use the tomcat 6. Regards A: I had the same problem and solved it by editing the POM, changing the jsp-api version from 2.1 to 2.2 <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <!-- 2.1 for Tomcat 6, 2.2 for Tomcat 7 --> <scope>provided</scope> </dependency>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FB API - Is it possible to post a large photo on someone's wall? I'm wondering if is it possible to post a large photo on someone's wall? Right now there is a limit - 90px, but how about the new Open Graph? Is it possible to do with the OG and the timeline? A: To get the nice big photos, you'll need to mark them as user-generated. See here: http://developers.facebook.com/docs/opengraph/usergeneratedphotos/
{ "language": "en", "url": "https://stackoverflow.com/questions/7596735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Skia remote surface Hi I was researching the possibility to transport the "not rendered" rendering calls to a second screen from Android. While researching I found out that Skia is behind the Surfacefinger, and the Canvas.draw() method. So my question is now, what would be the best interception point to branch off the calls in order to use them for a second screen / machine. The second device mut not be a pure replay device, but can be another Android device. First I used VNC for that concept, but quickly found out that it badly performs, due to the double buffering effect, it is also possible to manipulate the android code in a sense that it omits the double buffering, but it is still of interest to actually use the pre rendered calles on a second, maybe scaled device. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7596736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sencha touch - accordion layout In this code ... var panel = new Ext.Panel({ fullscreen : true, scroll : "vertical", layout : { type : "accordion" }, items: [ { xtype : "panel", title : "One Title", html : "One" }, list, { xtype : "panel", title : "Three Title", html : "Three" }, { xtype : "panel", title : "Four Title", html : "Four" }, { xtype : "panel", title : "Five Title", html : "Five" }, { xtype : "panel", title : "Six Title", html : "Six" } ] }); In this, the panel title were hard coded as One title, Three title, etc.. but i want to display the result what i am getting from database (i have created the model and i got the result to display) as title of each panel ... how to iterate and show .. pls help me.. A: You could collect the results in an array then add this array to panel's items. Could be something like this: var panels = []; for ( var i=0; i<results.length; i++ ) { var p= '{ xtype : "panel", title : ' + results[i].title + ', html : "' + results[i].html + '" },'; panels.push(p); } var panel = new Ext.Panel({ fullscreen : true, scroll : "vertical", layout : { type : "accordion" }, items: panels }); A: I got the dynamic value in accordion panel by using the following var panel = new Ext.Panel({ layout: { type: "accordion" }, initComponent : function() { allVisitStore.data.each(function() { alert('inside teration'); jsonObj.push({xtype:"panel", title: this.data['title'], html : this.data['patientId'], style : 'padding-bottom:10px;'}); }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7596737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find POI along a Google Maps route? (Android) doing "points of interest along a route" in google maps This would fit perfectly to my question...... But its not suitable for an android activity :/ So I start copiing the question now... just wait :D... aargh! Done! I need to allow travelers to use google maps to plot a route, and then query my database of points of interest (let's say, McDonald's locations) and then show all of these locations that are within a mile or two of the route they will be taking. The question is, how do I efficiently take the "driving directions" information that comes back from google (essentially an array of lat/long pairs), and turn that into an sql query to get locations that fall within a certain distance from the route? ...and then put the whole thing into my android app? I dont get it :( A: First things first: 1) do you have latlng (geolocations) variable type in your database? If answer(1) == yes: Calculate and query your database: D²=(Xb-Xa)²+(Yb-Ya)² along each of your Xa,Ya route points to discover the POIs (Ya,Yb) within Distance = D.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Whenever i run my application, the application crashes and it shows " signal1:Program recieved signal SIGABRT" On the console it shows.... 2011-09-29 17:06:39.564 Project AddressBook[925:207] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name 'eve'' * Call stack at first throw: ( 0 CoreFoundation 0x00e655a9 exceptionPreprocess + 185 1 libobjc.A.dylib 0x00fb9313 objc_exception_throw + 44 2 CoreFoundation 0x00e1def8 +[NSException raise:format:arguments:] + 136 3 CoreFoundation 0x00e1de6a +[NSException raise:format:] + 58 4 UIKit 0x005500fa -[UINib instantiateWithOwner:options:] + 2024 5 UIKit 0x00551ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168 6 UIKit 0x00407628 -[UIViewController _loadViewFromNibNamed:bundle:] + 70 7 UIKit 0x00405134 -[UIViewController loadView] + 120 8 UIKit 0x0040500e -[UIViewController view] + 56 9 UIKit 0x00406a3d -[UIViewController viewControllerForRotation] + 63 10 UIKit 0x00402988 -[UIViewController _visibleView] + 90 11 UIKit 0x006a493c -[UIClientRotationContext initWithClient:toOrientation:duration:andWindow:] + 354 12 UIKit 0x0037c81e -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:] + 954 13 UIKit 0x00604619 -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:] + 1381 14 UIKit 0x0040965d -[UIViewController presentModalViewController:withTransition:] + 3478 15 Project AddressBook 0x000032cb -[Home Events:] + 155 16 UIKit 0x003554fd -[UIApplication sendAction:to:from:forEvent:] + 119 17 UIKit 0x003e5799 -[UIControl sendAction:to:forEvent:] + 67 18 UIKit 0x003e7c2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527 19 UIKit 0x003e67d8 -[UIControl touchesEnded:withEvent:] + 458 20 UIKit 0x00379ded -[UIWindow _sendTouchesForEvent:] + 567 21 UIKit 0x0035ac37 -[UIApplication sendEvent:] + 447 22 UIKit 0x0035ff2e _UIApplicationHandleEvent + 7576 23 GraphicsServices 0x01723992 PurpleEventCallback + 1550 24 CoreFoundation 0x00e46944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 52 25 CoreFoundation 0x00da6cf7 __CFRunLoopDoSource1 + 215 26 CoreFoundation 0x00da3f83 __CFRunLoopRun + 979 27 CoreFoundation 0x00da3840 CFRunLoopRunSpecific + 208 28 CoreFoundation 0x00da3761 CFRunLoopRunInMode + 97 29 GraphicsServices 0x017221c4 GSEventRunModal + 217 30 GraphicsServices 0x01722289 GSEventRun + 115 31 UIKit 0x00363c93 UIApplicationMain + 1160 32 Project AddressBook 0x00002828 main + 102 33 Project AddressBook 0x000027b9 start + 53 ) terminate called after throwing an instance of 'NSException' sharedlibrary apply-load-rules all Current language: auto; currently objective HELP ME PLEASE!! A: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name 'eve'' Your problem is exactly this. You try to load a nib file named 'eve'. Somewhere you call something like this: VC *aVC = [[[VC alloc] initWithNibName:@"eve" bundle:nil] autorelease]; Xcode 4 should show you the call stack when it hits that exception. And in the source window it should show you the code where it happened. Three or four lines above that line is your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: IsKeyboardFocusWithin in silverlight How to get the keyboard focus is anywhere within the element or its visual tree child elements in Silverlght? A: There are two possible solutions depending on your scenario (we usually prefer more detail in a question). First you can use the FocusManager.GetFocusedElement() static method to get the element that currently has the focus. You could then use the VisualTreeHelper to determine if the element is with the your element. I would normally use an extension class to make using VisualTreeHelper easier. Mine is found here. With that class present. Then:- public static bool IsFocusIn(DependencyObject element) { DependendyObject focusedElement = FocusManager.GetFocusedElement() as DependencyObject; if (focusedElement != null) { return focusedElement.Ancestors().Any(e => e == element); } return false; } The second approach is to add event handlers to the GotFocus and LostFocus events of your element. You can then track whenever the focus enters or leaves any control within your element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File Upload, jQuery Possible Duplicate: Using jQuery, Restricting File Size Before Uploading When a user clicks on the file select button on an input element with it's type "file" is it possible to determine the file size, and other information about the file, before the user presses upload? For example, and event that occurs after the user has added their file ready to be uploaded. A: For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload. Refer this link Using jQuery, Restricting File Size Before Uploading A: You would have to use flash or other unreliable and unrequired software, which would just ruin user's experience. Otherwise, it's not possible
{ "language": "en", "url": "https://stackoverflow.com/questions/7596745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery: Fire a function when there's a certain hash in the url...? I'm looking to execute a function when the a page is loaded with a certain hash in the url. So if I visit www.mypage.com/hello.html#functionplease then the code will execute. Can anyone point me in the right direction? Any advice appreciated! A: var h = location.hash.substr(1); if (h == 'functionplease') functionplease(); substr(1) remove the # in hash. Many functions? No problem! switch(location.hash.substr(1)) { case 'buy': buy(); break; case 'sell': sell(); break; case 'other': other(); break; } A: The following should work: <script type="text/javascript"> //check if hash tag exists in the URL if(window.location.hash) { //set the value as a variable, and remove the # var hash_value = window.location.hash.replace('#', ''); //check value of hash if (hash_value == 'functionplease'){ // execute code } } </script> Hope this helps! A: var pathname = window.location.pathname; if(pathname.indexOf("#") != -1){ //call your function } A: try: <script type="text/javascript"> window.onload = function () { setInterval(pollHash, 100); } var lasthash = ''; function pollHash() { if (window.location.hash == lasthash) { return; } lasthash = window.location.hash; console.log('hash is changed! Current hash is: ' + lasthash); switch (lasthash) { case '???' : /* do something */ break; default: /* do nothing */ break; } } </script> have a look to: http://ajaxpatterns.org/Unique_URLs#Unique_URL_Sum_Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7596746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# - How to list the files in a sub-directory fast, optimised way I am trying to list the files in all the sub-directories of a root directory with the below approach. But its taking much time when the number of files are in millions. Is there any better approach of doing this. I am using .NET 3.5 so can't use enumerator :-( ******************* Main ************* DirectoryInfo dir = new DirectoryInfo(path); DirectoryInfo[] subDir = dir.GetDirectories(); foreach (DirectoryInfo di in subDir) //call for each sub directory { PopulateList(di.FullName, false); } ******************************************* static void PopulateList(string directory, bool IsRoot) { System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "dir /s/b \"" + directory + "\""); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); string fileName = directory.Substring(directory.LastIndexOf('\\') + 1); StreamWriter writer = new StreamWriter(fileName + ".lst"); while (proc.StandardOutput.EndOfStream != true) { writer.WriteLine(proc.StandardOutput.ReadLine()); writer.Flush(); } writer.Close(); } A: Remove all Process-related stuff and try out Directory.GetDirectories () and Directory.GetFiles() methods: public IEnumerable<string> GetAllFiles(string rootDirectory) { foreach(var directory in Directory.GetDirectories( rootDirectory, "*", SearchOption.AllDirectories)) { foreach(var file in Directory.GetFiles(directory)) { yield return file; } } } From MSDN, SearchOption.AllDirectories: Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search. A: It will be definitely faster to use DirectoryInfo.GetFiles in a loop for each directory instead of spawning tons of new processes to read thier output. A: With millions of files you're actually running into filesystem limitation (see this and search for "300,000"), so take this into account. As for optimizations, I think you'd really want to iterate lazily, so you'll have to P/Invoke into FindFirstFile/FindNextFile. A: Check out already available Directory.GetFiles overload. For example: var paths = Directory.GetFiles(root, "*", SearchOption.AllDirectories); And yes it will take a lot of time. But I don't think that you can increase its performance using only .Net classes. A: Assuming that your millions of files are spread across multiple sub-directories and you're using .NET 4.0, you could look at the parallel extensions. Using a parallel foreach loop to process the list of sub-directories, could make things a lot faster. The new parallel extensions are also a lot safer and easier to use than attempting multi-threading at a lower-level. The one thing to look out for is making sure that you limit the number of concurrent processes to something sensible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OAuth 2.0 way of grant permissions in JS and use serverside, (no session) I have created several apps by using FB.login() in the middle of the steps on a page, and rely on C# gaining access to the same session and thereby access (and save) the user info correctly. JS: FB.login(function (response) { if (response.session) {// user has authed} }); C#: public FacebookSession CurrentSession { get { return (new CanvasAuthorizer()).Session; } } In two days Facebook will remove the session support, which breaks this functionality. As I understand I am now required to have a page-reload before serverside can detect the granted permissions. (https://developers.facebook.com/docs/authentication/). It seems I have to either redirect the user to the login-box and then setup a callback, or still use javascript but reload the page once the user grants permissions. This is really sad, since the apps works very well by showing the user the app-interface, before asking any permissions and reloading the page. Does anyone know how to get the JS coupled to the serverside once again? A: make sure you are on v5.2.1 which supports the new cookie format and in js set oauth:true when calling login. Your existing code will continue to work without any server side (c#) changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ondemand billing provider I've been looking around for a simple ondemand billing solution. My scenario is the following: My customers use virtual credits on my website. Payment option 1) Customers can buy virtual credits buy suppliying a credit card. Payment option 2) Customers can register their credit card for automatically getting billed when credits are running low. I know google does this for their API usages. Any one have a good idea of a provider that can achieve this in a simple way? I want to outsource the whole process to not run into any PCI compliance issues. Also I would like the hosted solution to be wihtin our site (ifram in a popup). The majority of our customers are companies. A: If you are in the US you can use Authorize.Net's Customer Information Manager (CIM) API to create payment profiles for your customers. Then you can charge against those profiles at any time to add credits when they are running low. They offer a hosted CIM option which greatly reduces your PCI compliance issues. A: I've been looking at Stripe.com lately. They offer a very simple to use API which seems to be very well thought out. They offer on-demand and subscription billing, good documentation, and their costs are not out of line (2.9% + $.30 per txn) considering you don't have to get a merchant account. They are US-based.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I link the youtube iframe to show popup message I there a way to show popup texts while clicking the youtube video iframe code ? <a href='login.html?sid=0&keepThis=true&TB_iframe=true&height=240&width=650' class="thickbox" title='test'> A: Have you try to call Javascript on the onclick attribute <a onclick="alert('test')" href='login.html?sid=0&keepThis=true&TB_iframe=true&height=240&width=650' class="thickbox" title='test' > This will open the pop up and then go to the URL (tested on Firefox 7). Edit: Another solution is to do the href location after the pop up : <a onclick="alert('test');document.location.href='login.html?sid=0&keepThis=true&TB_iframe=true&height=240&width=650'" class="thickbox" title='test'>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DO NOT redirect just render the login layout From my clients, they wanna all customers (users) SHOULD login before visiting any page on Magento site. I know that if I do that, I have to check if a user does not login, we will redirect to customer/account/login I have question is: I don't wanna redirect, I just wanna render login layout.(1) So, how can I do that? (1): I see in admin side, it has this behavior, when I try to visit any page of admin side. If the user did not login, or out session, it will render login layout, without redirect. A: Get the login page layout description, build a block, and render as HTML. A: If I understood you right, you need add next code to your controller action: if (!Mage::getSingleton('customer/session')->isLoggedIn()) { $this->_forward('login', 'account', 'customer'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7596756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passing boost python enum as parameter I defined enum_<mytype>("mytype") .value("one",1) .value("two",2) ; in my BOOST_PYTHON_MODULE. when I expose a class with a function taking a parameter of type mytype (essentially, an int), like: void myfunc(mytype m) { ... } I get the following compiler warning: dereferencing pointer 'p.2311' (or whatever) does break strict-aliasing rules now, it is just a warning, and the code works perfectly with optimization enabled.. may I safely ignore the warning? am I missing something? Thank you A: It's hard to say exactly without seeing the warning, but it's most likely caused by some macros from Python headers. To be safe, compile the code that uses Python (and Boost.Python) with -fno-strict-aliasing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calendar months wrong I try to set a simple date certain years after with calendar: String date is a parameter of this metod. SimpleDateFormat format = new SimpleDateFormat("dd.mm.yyyy"); String[] DateTimeParts = date.split(" "); String dt = DateTimeParts[0]; String[] dateParts = dt.split("-"); int d = Integer.parseInt(dateParts[2]); int y = Integer.parseInt(dateParts[0]); int m = Integer.parseInt(dateParts[1]); Calendar calendar = Calendar.getInstance(); calendar.set(y, m-1, d); calendar.add(Calendar.YEAR, years); return format.format(calendar.getTime()); } My problem is that the date return is otherwise fine, but the month number is totally wrong, and seems to be getting bigger on each run! What I'm missing? A: You are using lowercase "m" for month, when you should be using uppercase "M", i.e SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy"); lowercase "m" is used to format minutes - see the java API for SimpleDateFormat for more details. A: You have to use uppercase for month, otherwise you get minutes =) try: dd.MM.yyyy More: http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html A: Other Answers are correct but outdated. tl;dr LocalDate.parse( "23.01.2017" , DateTimeFormatter.ofPattern( "dd.MM.uuuu" ) ) Avoid legacy date-time classes FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes. See Tutorial by Oracle. LocalDate The LocalDate class represents a date-only value without time-of-day and without time zone. DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" ); LocalDate localDate = LocalDate.parse( "23.01.2017" , f ); // January 23, 2017. And going the other direction. Note that unlike the legacy classes, the java.time class have sane month numbering, 1-12 for January-December. LocalDate localDate = LocalDate.of( 2017 , 1 , 23 ); January 23, 2017. String output = localDate.format( f ); About java.time The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat. The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310. Where to obtain the java.time classes? * *Java SE 8, Java SE 9, and later * *Built-in. *Part of the standard Java API with a bundled implementation. *Java 9 adds some minor features and fixes. *Java SE 6 and Java SE 7 * *Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport. *Android * *The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically. *See How to use ThreeTenABP…. The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: File in local storage on Java, Android I serialization object into new file in local storage by this mean: ObjectOutputStream output=new ObjectOutputStream(openFileOutput("settings.dat", Context.MODE_PRIVATE)); output.writeObject(this); output.close(); But in another function I must check file for exist: File file=new File("settings.dat"); if (file.exists()) Toast.makeText(this, "yes", Toast.LENGTH_LONG).show(); file.exists() returne false always. Help me please. A: Use: File file = new File(getFilesDir() + "/settings.dat"); http://developer.android.com/reference/android/content/Context.html#getFilesDir%28%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7596764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: layout at the bottom of a gridview (at the end of it) What i want is to have the gridview filling whole screen. And when you scroll it down, at the end would appear a layout with 2 buttons. Ive been reading and couldnt figure how to get it. I could fix it on the top of the screen and the bottom (over the gridview). And also trying the layout with the button wont even appear when the gridview is filled. Ive been playing with weights, aligns, etc. But cant find whats wrong. Heres the xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/fondo"> <GridView android:layout_width="fill_parent" android:id="@+id/gridView1" android:layout_height="wrap_content" android:numColumns="2" android:listSelector="#00000000"> </GridView> <LinearLayout android:id="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="50dp" android:orientation="horizontal" android:layout_below="@id/gridView1"> <ImageView android:id="@+id/botonAtras" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_weight="1" android:onClick="onBotonAtrasClick"> </ImageView> <ImageView android:id="@+id/botonAdelante" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_weight="1" android:onClick="onBotonAdelanteClick"> </ImageView> </LinearLayout> </RelativeLayout> A: As far as I can tell you can't easily do this. You can do it with a plain ListView using addFooter(), but sadly GridView doesn't have this method. Also you can't implement your own GridView because it uses a lot of private APIs. However, there is a horrible hack used here that might work:Android Pull to refresh Apparently it uses a LinearLayout containing the header view and the ListView and moves them both. (According to this page.) As that guy says, a lot of work for a horrible horrible hack. The only other way I can think to do it, is to give up on GridView and use a ListView where each row is a horizontal LinearLayout. Still very hacky though. A: set LinearLayout below GridView by setting android:layout_below:"@+id/gridView" inside id/linearLayout A: I solve this problem like this: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:fillViewport="true" > <GridView android:id="@+id/myGrid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="60dp" android:gravity="center" android:horizontalSpacing="10dp" android:numColumns="3" android:padding="10dp" android:stretchMode="columnWidth" android:verticalSpacing="10dp" /> </LinearLayout> <Button android:id="@+id/bacth_button" android:layout_width="fill_parent" android:layout_height="50dip" android:layout_alignParentBottom="true" android:layout_marginLeft="2dip" android:layout_marginRight="2dip" android:layout_marginTop="2dip" android:text="Uninstall Selected Apps" android:textColor="#000000" android:textSize="16dip" android:textStyle="bold" /> </LinearLayout> include GridView in linearlayout,then i's work as you like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Detect screen size and pixel density on the server-side? I've been doing some research and I think I know the answer already, but I'm wondering if there's any means by which you can get a device's screen size and pixel density without the use of javascript or relying on CSS3 media queries. Essentially, I'm looking into what it would take to get the screen resolution and pixel density so that the server could decide which image to server in a URI request. So far I've not found anything that says this is even possible but I thought hey, why not ask? A: Ruby runs on the server side--without getting info from the client, it has no way of knowing any client capabilities. A: For something that's impossible it looks like Mobvious does a decent job: Mobvious detects whether your app / website is being accessed by a phone, or by a tablet, or by a personal computer. You can then use this information throughout your app. (E.g. fork your front-end code with regard to device type. There is a plugin for Ruby on Rails that helps you with this.) https://github.com/jistr/mobvious A: I don't agree entirely with the above correct answer. Realistically this answer is correct in many cases...but theoretically it is not. Often requests made to a web server contain a User-Agent field which could, in theory, be used to discern information about device screen resolutions and properties. Web requests do not pass through the client first. They pass to the server, which then serves a page to the client so the server gets the request first...Ruby on Rails, for example, receives a request through an action controller to a resource and then serves a page to the response. Look at an example UA parser such as : https://github.com/visionmedia/user-agent A sample user agent being sent by my computer is: User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.11 (KHTML, like enter code here`Gecko) Chrome/17.0.963.83 Safari/535.11 I think it is eminently possible to make a good guess what my screen resolution (DPI etc) is given that information via a server. You would, of course, need a table of device information to reference. For mobile devices it gets even easier. If the User-Agent is a mobile safari for iPad: Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10 You can know with strong certainty what the screen resolution is on the server. You can even know the height and width of the browser with that info. I suspect the same is true with many mobile devices such as Android or Win Mo. So in summation, I agree its impractical to do this but I also disagree. I believe Facebook has undertaken a major project cataloging devices and screen resolutions and made it open source because they faced similar issues when creating the facebook mobile app e.g. they had to catalog all the discrepancies between all mobile browser renderers so they could tailor the client app to every individual case. Perhaps that project might have the necessary information to do this...in theory. A: I had the same problem and solved it using a getter and a setter route for the window height. If the $height variabale is 0 the get_heigt.erb is served, otherwise the index.erb This is a one user app, so I use a global variable, with different users you would have to keep that info in cookies. Here the code that matters. Controller: get "/" do if $height == 0 erb :get_height else erb :index end end get "/get_height" do erb :get_height end get "/set_height" do $height = params[:height] redirect "/" end get_height.erb <script type="text/javascript"> function send_message(message) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { document.location.reload(true); } xhttp.open("GET", "http://localhost:4567/" + message + "?height=" + window.innerHeight, true); xhttp.send(); } send_message('set_height'); </script> A: You could use Ahoy. The current_visit method contains the following information. When someone visits your website, Ahoy creates a visit with lots of useful information. traffic source - referrer, referring domain, landing page, search keyword location - country, region, and city technology - browser, OS, and device type utm parameters - source, medium, term, content, campaign A: Not sure how realistic would be to build but you could build a database which maps specific device types you can get from user agent in server-side into know screen sizes. It still would not allow things like window size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Variable package name with Maven Android Plugin I'm using the Maven Android Plugin to build my application. Actually, I'm building 3 "branded" versions of the same app (the app icon, colors, etc... change, but not the features). I'm aware that I need to use a different package name for each application, for them to be considered as different. So far I have managed to have "dynamic" values, using Maven filters in strings.xml : <string name="app_name">${app_name}</string> <string name="widget_name">${widget_name}</string> <string name="app_icon">${app_icon}</string> The problem is that this does not work for the package name ! If I do : <manifest package="${foo.bar}"> ADT (well, the XML validator actually) complains saying attribute package has invalid character '$' I can't find any workaround for this... Is there a way to tell ADT to launch the Maven resources filtering or something like that ? A: After further research, it appears to be fairly easy ! You just need to add <renameManifestPackage> in the configuration of the Maven Android Plugin. Seems to work starting at version > 2.9.0 : <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>maven-android-plugin</artifactId> <version>2.9.0-beta-5</version> <configuration> ... <renameManifestPackage>${manifest_package}</renameManifestPackage> </configuration> </plugin>
{ "language": "en", "url": "https://stackoverflow.com/questions/7596771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Figuring out the biggest array I can create in memory I am sorting a number of integers from a file, which will probably be too large to fit into memory in one go, my current idea is to get sort chucks with quicksort, then mergesort them together. I would like to make the chunks as big as possible, so I'd like to know how much I can read in in one go. I know about Runtime.FreeMemory, but how should I go about using it. Should I carefully work out what other variables I use in the program then create an array of size (freeMemory - variablesSizes), or is that too likely to go wrong? Thanks! A: Experiment until you find a size that works well. The largest array you can allocate on the heap isn't necessarily the fastest way to do it. In many circumstances, the entire heap does not fit in the computers RAM, and might be swapped out in parts. Just because you can allocate a huge array, does not mean it will be the best size for optimizing speed. Some adaptive approach would probably be best (testing number of items sorted/second depending on array size) and adjusting for what you can fit without getting an OutOfMemoryError. Simpler: stick with some large value that works well, but isn't necessarily the largest you can use. Or: use an external library/database to do what you want - working with huge amounts of data is tricky to get right in general, and you will probably get better performance and shorter development time if you don't reinvent the wheel. A: I'd start with a relatively small chunk size for the first chunk. Then I'd double the chunk for every next chunk until you get an OutOfMemoryException. Though that will probably trigger swapping. A: I think figuring out exactly how much memory we can allocate is a sticky buisness, as by default in java the jvm will allocate a heap space of 256M, but this can always be increated using -Xmx, so it is best to trade performace for portability by having a fixed chunk size of lets say around 150M. A: If you go with java building sorting functionality, you will have to use a Collection of some sort, which will not take int primitive types, but rather, you will have to use Integer objects. (List<Integer>) In my experiences (not to be taken as gospel), an int weighs in at (obviously) 4 bytes of ram, whereas an Integer weighs in at 12 bytes on a 32bit machine and 24 bytes on a 64bit machine. If you need to minimize memory foot print, use int[] and then implement your own sorter... However, it might be easier all the way around to use List<Integer>, and the built in sorting functions and just deal with having to have more of smaller sized Lists. To answer the question though, you should definitely look at the Merge-Sort angle of attack to this problem and just pick an arbitrary List size to start with. You will likely find, after some experimentation, that there is a trade off between list size and number of chunks. Find the sweet spot and tell us your results!
{ "language": "en", "url": "https://stackoverflow.com/questions/7596773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change text within a tag on mouseover I have defined a tag in which on mouseover i am changing the text within the a tag <a class="bid-addwatchlist add-logout" href="/users/login" onmouseover="changeText(this)" onmouseout="sameText(this)"><span style="font-size: 32px; line-height: 18px;">+</span><span style="font-size: 14px; float: left;">Add to watchlists</span></a> <script> function changeText(theTag){ theTag.innerHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;">Login</span>'; } function sameText(theText){ theText.innerHTML = '<span style="font-size: 32px; line-height: 18px;">+</span><span style="font-size: 14px; float: left;">Add to watchlists</span>'; } </script> I have given the following css for this a tag to make it look like a box .bid-addwatchlist{ background-color : #32679B; border-radius : 5px 5px 5px 5px; color : #FFFFFF; cursor : pointer; float : left; height : 56px; line-height : 14px; padding-top : 4px; text-decoration : none; width : 76px; margin-left : 11px; } It is working fine but the problem i am facing is when i do mouseover the text changes to login and if i click on the login text nothing is happening whereas if i click on other side areas it is working. I am not understanding the problem why this is happening and what i need to do now so that if i click on the login text it works. Please suggest what i need to do or this is because the login text is not within the a tag. All i need to do is i want to change the text within the a tag onmouseover and consequently it should work. I have also tried this, defined the click event in the span for the text, but not working function changeText(theTag){ theTag.innerHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;" onclick=\'window.location="/users/login"\'>Login</span>'; } Note: The text is just a normal link A: I think you problem is that the text that you put in for the onMouseOver isn't bound to the link element since it isn't inside the when the DOM is parsed. Therefore I would add the link to the Login text too. function changeText(theTag){ theTag.innerHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;"><a href="/users/login">Login</a></span>'; } A: Here you go, fixed it ;) http://jsfiddle.net/WwM5g/2/ I didn't use onmouseover and onmouse out, instead I used the .hover jQuery event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a kernel equivalent for ReadFileScatter/WriteFileGather How to perform vectored file I/O from the Windows kernel? I need an equivalent of ReadFileScatter/WriteFileGather. A: NtReadFileScatter and NtWriteFileGatter Also the following might be a good addition A: I believe you can use ZwReadFileScatter and ZwWriteFileGather but I can't find documentation for them on MSDN, and I don't have the DDK headers at hand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there away to know if a user is still on my site - instead of using cookies or sessions I am wondering, if there is a real-time way time ping a user and see if that user is still only. My site uses jQuery, PHP and CRON jobs so I was wondering what would be the best way to check that the user is still online. Each user is issues a cookie aka session key but I don't want to just go by that. I know real-time analytics are able to it, using javascript so I wonder if I could also do the same thing. Thanks A: it could be done via continues ajax call from client but not recommended. I suggest use flash or something like that to reduce number of ajax request to the server. A: Any method you choose will work the same as what you mentioned, it will just update more often. You can use an ajax call that pings the server every x seconds and as soon as that stops you'll know they left at most x seconds ago. A similar option is to use WebSockets or Flash to hold a socket connection with the server and mark them as logged off the moment that socket connection is broken. Both these options are a bit more difficult to scale than sessions and cookies. A: Question is very confused and ambiguous. No you can't 'ping' a user. You can ping an IP adderss - but the IP addresses you see at your server probably don't map on a one-to-one basis with users. Which user? All users? Why? What will you do with the information? Have you got a better reason than "I don't want to" for not using session data? "I know real-time analytics are able to" - then you must know the method they use to do this - or are you just buying the sales speak? A: I guess only way to get "real-time" data is to use web-sockets. another way which is less acurate ( with delay ) is to use repited ajax calls. say 1 per 60 seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Downloading MMS emails sent to Gmail using Python So I tried the code below and it downloads attachments alright. The problem is on my gmail account, there are emails that were sent using MMS mail through mobile phone. Email attachments from mobile network A can be downloaded by the script below , while those that came from mobile network B fails. Here are the links to the full email details : http://pastie.org/private/ektv7yfa2xwdqzu77ys5a (From Mobile Network A, works) http://pastie.org/private/cljaaad4tz7v5jra20l0q (From Mobile Network B, fails) Grabbed from : How can I download all emails with attachments from Gmail? import email, getpass, imaplib, os detach_dir = '.' # directory where to save attachments (default: current) user = raw_input("Enter your GMail username:") pwd = getpass.getpass("Enter your password: ") # connecting to the gmail imap server m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead # use m.list() to get all the mailboxes resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp) items = items[0].split() # getting the mails id for emailid in items: resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue filename = part.get_filename() counter = 1 # if there is no filename, we create one with a counter to avoid duplicates if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1 att_path = os.path.join(detach_dir, filename) #Check if its already there if not os.path.isfile(att_path) : # finally write the stuff fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() A: The failing e-mail doesn't have Content-Disposition set in the headers for the attachment, so you're skipping over it. Looks like you're going to have to relax the if statement that checks for Content-Disposition a bit. Maybe you could just look too see if the Content-Type is image/jpeg and work with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7596789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }