text
stringlengths
8
267k
meta
dict
Q: Need a Property to hold the result from a data table I need to create a property tha will hold to ints for example int age and int numbers so.. something like This data is comming from a function in another class that returns a DataSet, in the data set there will be those two items like: Age number 24 1 29 6 32 2 27 1 19 3 So like I said, at the end I would like to have a property that contains this data and can reference at any time from different classes so I am not sure what to use to hold that data, but it would be something like public <int, int> personData { get { return _personData; } set { _personData = value; } } so I do not know what to use for _personData and for . And how can I access the values of such solution I would appreciate your help A: Looks like a Dictionary<int, int> will do it for you. Dictionary<int, int> _personalData = new Dictionary<int, int>{ {24, 1}, {29, 6}, ..}; and to access values, you can do int result = _personalData[24]; // should return 1 A: public class PersonData { public int Age{get;set;} public int Number {get;set;} } You can then create List<PersonData> And you can access each property like so: PersonData personData = new PersonData(); personData.Age=12; personData.Number=10; You can create a list of PersonData and add items doing this: List<PersonData> listPersondata = new List<PersonData>(); listPersondata.Add(new PersonData(){Age=12,Number=13}); You can bind this List to any control like a gridview, listbox, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 Asset Pipeline have Heroku implications? Does the asset pipeline have implications for rails on heroku that I should know about? A: Yes it does, details can be found on Heroku's Rails 3.1 guide: http://devcenter.heroku.com/articles/rails31_heroku_cedar A: Take care of that during the "rake asset:precompile" phase there is NO environment. There is a config initialize_on_precompile which prevent Rails to connect to the db during this step. This is essential on Heroku. BUT this config HAVE to go to config/application.rb and NOT to config/environments/production.rb. Keep in mind that there is no environment...
{ "language": "en", "url": "https://stackoverflow.com/questions/7542994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: setting NetworkStream.ReceiveTimeout not triggering exception This is a continuation of the this question. I am new to network programming, so I am just writing small sample stuff to gain understanding, but somewhat struggling with explaining results. It seems setting NetworkStream.ReceiveTimeout is not working correctly when client that was supposed to be sending data simply closes before sending all the expected data. Here is the sample code: public static void Main(string[] args) { TcpListener listener = new TcpListener(IPAddress.Any, 10001); listener.Start(); ThreadPool.QueueUserWorkItem(WriterThread); using (TcpClient client = listener.AcceptTcpClient()) using (NetworkStream stream = client.GetStream()) { client.ReceiveTimeout = (int)new TimeSpan(0, 0, 2).TotalMilliseconds; stream.ReadTimeout = (int)new TimeSpan(0, 0, 2).TotalMilliseconds; ReceiveMessage(stream, 1024); } listener.Stop(); Console.WriteLine("Done."); Console.ReadKey(true); } private static void WriterThread(object state) { using (TcpClient client = new TcpClient()) { client.Connect(new IPEndPoint(IPAddress.Loopback, 10001)); using (NetworkStream stream = client.GetStream()) { byte[] bytes = Encoding.ASCII.GetBytes("obviously less than 1024 bytes"); stream.Write(bytes, 0, bytes.Length); Thread.Sleep(10000); // comment out } } } private static byte[] ReceiveMessage(Stream stream, int length) { byte[] buffer = new byte[length]; int bufferFill = 0; while (true) { bufferFill += stream.Read(buffer, bufferFill, buffer.Length - bufferFill); if (buffer.Length == bufferFill) return buffer; Thread.Sleep(100); } } This version works correctly triggering exception on the stream.Read() call. However If I comment out Thread.Sleep(10000), the client closes connection, but listener fails to recognize it. Main thread gets stuck inside the while(true) loop. The stream.Read() keeps returning zero, but no exception thrown. Is this normal? If so how am I expected to handle abnormal client disconnections? A: Yes, this sounds normal. There is no receive- or read timeout because the client has disconnected. This means that no more data is available for reading and the stream will return 0 immediately just as documented. I would modify your ReceiveMessage method to something like the following: private static byte[] ReceiveMessage(Stream stream, int length) { byte[] buffer = new byte[length]; int bufferFill = 0; while (true) { int bytesRead = stream.Read(buffer, bufferFill, buffer.Length - bufferFill); if (bytesRead == 0) throw new Exception("No more data available."); bufferFill += bytesRead; if (buffer.Length == bufferFill) return buffer; Thread.Sleep(100); } } Clearly if the stream.Read() call returns 0 before we have received all the expected bytes there must have been some form of disconnection or similar. Either way we will never get any more data from the stream. Edit: The Stream class has no notion of a "message". The Read method blocks until more data becomes available if none is already in the buffer. It will however return 0 when no more data can be received, which in this case means the connection is closed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7542995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to populate the alertdialog from the values queried from database? Right now I can only see the fetched values when I press OK button of the dialog. But I want to see it when the alertdialog appears. I know I have put the display code inside the .setPositiveButton("OK", But even when I tried putting it before that, it didnt work. I some how have idea that i need to make use of this setview(addView) but dont know how. Please help me. enter code here private void populateFields() { LayoutInflater inflater=LayoutInflater.from(this); final View addView=inflater.inflate(R.layout.add_country, null); new AlertDialog.Builder(this) .setTitle("Edit country/year") .setView(addView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { Cursor c = getContentResolver().query (CONTENT_URI.buildUpon ().appendPath(String.valueOf(mRowId)).build(), null, null, null, null); /* Read alert input */ EditText editCountry =(EditText)addView.findViewById(R.id.editCountry); EditText editYear =(EditText)addView.findViewById(R.id.editYear); //System.out.println(c.getString(c.getColumnIndex("country"))); editCountry.setText(c.getString(c.getColumnIndex("country"))); editYear.setText(c.getString(c.getColumnIndex("year"))); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { // ignore, just dismiss } }) .show(); } A: Try putting your code right after you have inflated the view. Something like this : private void populateFields() { LayoutInflater inflater=LayoutInflater.from(this); final View addView=inflater.inflate(R.layout.add_country, null); Cursor c = getContentResolver().query(CONTENT_URI.buildUpon().appendPath(String.valueOf(mRowId)).build(), null, null, null, null); /* Read alert input */ EditText editCountry =(EditText)addView.findViewById(R.id.editCountry); EditText editYear =(EditText)addView.findViewById(R.id.editYear); editCountry.setText(c.getString(c.getColumnIndex("country"))); editYear.setText(c.getString(c.getColumnIndex("year"))); new AlertDialog.Builder(this) .setTitle("Edit country/year") .setView(addView) .setPositiveButton("OK",null) .setNegativeButton("Cancel",null) .show(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7542997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does "contextual conversion" with `&&` and `||` operators work in conjunction with user-defined operator overloads? From @Xeo's excellent c++-faq question: Is the safe-bool idiom obsolete in C++11? I learned that the safe bool idiom is no longer needed, because an explicit user-defined conversion to bool will be automatically invoked in contexts where the safe bool was needed in C++03. However, the ability to overload operators such as &&, || and ! seems to circumvent this. Cases where operator! is necessary beyond provision of conversion to bool are rare, as are operator&& and operator||, but C++ expression tree implementations (used for deferred execution and symbolic math techniques) do need to override these. Does "contextual conversion" take place when a user-defined operator is being invoked? What sort of SFINAE incantation is needed to make sure that a definition of operator&& or operator|| will work correctly both with types implementing "safe bool" and those designed for "contextual conversion"? To clarify, given: class uses_safe_bool { void f() {}; typedef void (uses_safe_bool::* safe_bool)(); public: operator safe_bool() const { return (rand() & 1)? &uses_safe_bool::f: 0; } }; class uses_explicit_bool { public: explicit operator bool() const { return rand() & 1; } }; template<typename T> class deferred_expression { // Not convertible to bool public: T evaluate() const; }; What signatures are required for operator|| such that the following expressions are all valid: deferred_expression<bool> db; uses_safe_bool sb; uses_explicit_bool eb; int i; auto test1 = sb || db; auto test2 = eb || db; auto test3 = true || db; auto test4 = false || db; auto test5 = i || db; these use a different overload: auto test6 = db || db; deferred_expression<int> di; auto test7 = di || db; and the following are rejected at compile-time: std::string s; auto test7 = s || db; std::vector<int> v; auto test8 = v || db; deferred_expression<std::string> ds; auto test9 = ds || db; A: The rule is the same for C++03 (safe-bool idiom) and for C++11 (explicit conversion operator): don't overload the boolean operators for this (so as to not lose short circuit behaviour, plus the defaults work just fine). The latter will work because the operands of the built-in boolean operators are eligible for a contextual conversion, for instance for && from n3290, 5.14 Logical AND operator [expr.log.and]: 1 The && operator groups left-to-right. The operands are both contextually converted to type bool (Clause 4). (emphasis mine, similar text for other operators) Overloaded operators are regular function calls, so no contextual conversion takes place. Make sure your overloaded boolean operators are always picked through overload resolution and you're good to go. For instance, this is neglecting lvalues: struct evil { explicit operator bool() const; }; void operator||(evil&&, evil&&); evil e; // built-in operator|| e || e; // overloaded operator|| evil() || evil() Note that template<typename Lhs, typename Rhs> void operator||(Lhs&&, Rhs&&); will be selected via ADL when any one of the operand type is of class type, regardless of cv-qualifiers and of value-category.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Ordered comparison between pointer and integer - (void) dealloc { [_id_list release]; [super dealloc]; } - (void)update { CFArrayRef ar = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID); CFDictionaryRef window; CFIndex i; CGWindowID wid; [_id_list release]; _id_list = [[NSMutableArray alloc] init]; for (i=0; i < window =" CFArrayGetValueAtIndex(ar," name =" (NSString*)CFDictionaryGetValue(window," owner_name =" (NSString*)CFDictionaryGetValue(window,");} for the last line, Xcode gives error: * *'Semantic Issue: Ordered comparison between pointer and integer ('CFIndex' (aka 'long') and 'CFDictionaryRef' (aka 'const struct __CFDictionary *'))' And, specifically for this it warns: * *i < window *'Expression is not assignable' Basically, I'm trying to get WindowID of Desktop (wallpaper only). Why does this happen? A: This: for (i=0; i < window =" CFArrayGetValueAtIndex(ar," name =" (NSString*)CFDictionaryGetValue(window," owner_name =" (NSString*)CFDictionaryGetValue(window,");} Doesn't make any sense. for loops are generally: for ( assignment-expr; comparison-expr ; increment-expr ) { body-of-for-loop } A: Ignoring the fact that there is some crazy stuff going on in that for loop, the compiler is complaining because: CFDictionaryRef window; CFIndex i; And this part: i < window It makes no sense to compare an index (long) to a dictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: spawning thread using a method without being static? is it possible to spawn a new thread using a method that isn't static? i have a program in wpf, i want to spawn a thread when it starts. i'm trying to do this: static Thread thread = new Thread(new ThreadStart(SomeMethod)); private void SomeMethod() { SendingMessage("hello"); SendingMessage("what's up"); } private void SendingMessage(string x) { if (x=="hello") //Do something awesome here if (x=="what's up") //do something more awesomer here } public MainWindow() { InitializeComponent(); thread.Start(); } i believe i'm doing something wrong here. A: It is not going to compile because you trying to reference instance member within static context. Simply move the Thread thread = new Thread(new ThreadStart(SomeMethod)); into your constructor and it should complile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL SELECT multiple rows with same column value based on value from another column I am just getting started with MySQL queries, and have been fighting this for days with no luck finding a solution, so here goes. Table structure as follows: | ID | TAG | 111909684134416384 | WesternU | 111909684134416384 | ldnon | 111910470428008448 | ldnont | 111910470428008448 | fb | 111910605249712128 | LTC | 111910605249712128 | ldnon | 111911886139826176 | ldnont | 111911886139826176 | WesternU I would like to select, count, and list the TAG(s) where one TAG of the same ID has 'ldnont' or 'ldnon' listed. Essentially, from this data set, I would like to list and count: WesternU (2) fb (1) LTC (1) I've been able to select and count, but only the first row of rows with duplicate ID. Thank-you in advance for any assistance. A: SELECT Tag, COUNT(*) FROM JodyTable WHERE Tag NOT IN ('ldnon', 'ldnont') AND ID IN (SELECT ID FROM JodyTable WHERE Tag IN ('ldnon', 'ldnont')) A: If i understand your question correctly - you want to count how many records with the same id has either "ldnon" or "ldnont" tags in table, not counting "ldnon" and "ldnont" themselves select outer.tag, count(*) as outer.num from table as outer where outer.tag NOT = "ldnon" AND outer.tag NOT = "ldnont" outer.id IN ( select * from table as inner where outer.id = inner.id AND (inner.tag = "ldnon" OR onner.tag="ldnont") ) group by outer.tag order by outer.num this one is quite complicated maybe, but straightforward. A: select t1.tag, count(*) from table as t1, table as t2 where t1.id = t2.id AND t1.tag NOT = t2.tag AND t1.tag NOT = "ldnon" AND t1.tag NOT = "ldnont" AND (t2.tag = "ldnon" OR t2.tag = "ldonont") group by t1.tag
{ "language": "en", "url": "https://stackoverflow.com/questions/7543013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drawing triangles with CSS problems This code .right { -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); border-color: #fff transparent transparent transparent; border-style: solid; border-width: 200px; height:0; width:0; position: relative; top:-800px; left:600px; margin:0px; padding:0px; } creates a triangle that looks like this in Safari: But in other browsers there are problems. On firefox on mac the triangle has lines through it like this: How can I make sure the lines do not appear? I would prefer not to replace the css triangle with an image. A: If the zoom is not the problem, I think the problem is being caused by rotating the elements. It is unnecessary and can be done simply with the borders. Live example: http://jsfiddle.net/tw16/TQx7x/ Remove the transforms and adjust border styles as below: .left { border-color: transparent #ffffff transparent transparent; /* change to this */ border-style: solid; border-width: 200px; height: 0; left: -400px; margin: 0; padding: 0; position: relative; top: -400px; width: 0; } .right { border-color: transparent transparent transparent #ffffff; /* change to this */ border-style: solid; border-width: 200px; height: 0; left: 600px; margin: 0; padding: 0; position: relative; top: -800px; width: 0; } A: I read all of the comments and I found the solution. Please follow link. A: You have the default font size of your browser increased. ctrl+0 or cmd+0 (PC / Mac) should fix your problem. A: Can you try using border-color #ffffff ? border-color: #ffffff transparent transparent transparent;
{ "language": "en", "url": "https://stackoverflow.com/questions/7543016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Call a method in a dynamically loaded module perl I am using Module::Load to load a module dynamically. But I am not able to invoke a method defined in the module. Here is what I am doing my $module = load("Module"); $module->function(); I am getting the following error: Can't call method "function" without a package or object reference What is wrong in the above code? A: The load function doesn't have a specified return value. I think you're looking for this: my $module = 'Module'; load($module); $module->function();
{ "language": "en", "url": "https://stackoverflow.com/questions/7543017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Jackson vs Gson for simple deserialisation For parsing JSON like this twitter API users/show response I've been using Jackson and Gson Java libraries as candidates to do this work. I'm only interested in a small subset of properties of the JSON so Gson was nice because of its very concise syntax but I'm losing an internal battle to continue to use Gson as Jackson is already used elsewhere in our application and it has documented better performance (which I concede are both good reasons to lose Gson). For a POJO like public class TwitterUser { private String id_str; private String screen_name; public String getId_str() { return id_str; } public void setId_str(String id_str) { this.id_str = id_str; } public String getScreen_name() { return screen_name; } public void setScreen_name(String screen_name) { this.screen_name = screen_name; } } The only code for Gson needed to build this is one line, TwitterUser user = new Gson().fromJson(jsonStr, TwitterUser.class); That's pretty nice to me; scales well and is opt-in for the properties you want. Jackson on the other hand is a little more laborious for building a POJO from selected fields. Map<String,Object> userData = new ObjectMapper().readValue(jsonStr, Map.class); //then build TwitterUser manually or TwitterUser user = new ObjectMapper().readValue(jsonStr, TwitterUser.class); //each unused property must be marked as ignorable. Yikes! For 30 odd ignored fields thats too much configuration. So after that long winded explanation, is there a way I can use Jackson with less code than is demonstrated above? A: With Jackson 1.4+ you can use the class-level @JsonIgnoreProperties annotation to silently ignore unknown fields, with ignoreUnknown set to true. @JsonIgnoreProperties(ignoreUnknown = true) public class TwitterUser { // snip... } * *http://wiki.fasterxml.com/JacksonAnnotations *http://wiki.fasterxml.com/JacksonHowToIgnoreUnknown
{ "language": "en", "url": "https://stackoverflow.com/questions/7543024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to have filled video at top and show label at bottom. (Fill and Anchor) In Winforms, I use Fill and Dock to achieve this. I have a "Page" where I would like to play a video file and also show the label at the bottom. I would like the page to be able to stretch and for the video to stretch and to have the label stay at the bottom of the page. My attempts so far always results in the video covering the label when it is played. How can this be fixed? (Other controls in the StackPanel have been omitted) <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SDKSample.MediaElementExample" > <DockPanel LastChildFill="True"> <MediaElement Source="media\numbers.wmv" Name="myMediaElement" LoadedBehavior="Manual" UnloadedBehavior="Stop" MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" DockPanel.Dock="Top" Margin="50" /> <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Height="30" DockPanel.Dock="Bottom" Margin="50"> <TextBlock Margin="5" VerticalAlignment="Center"> Video Label </TextBlock> </StackPanel> </DockPanel> </Page> Solution (with thanks to Daniel May): <Grid Height="Auto"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="30"/> </Grid.RowDefinitions> <MediaElement Source="media\numbers.wmv" Name="myMediaElement" LoadedBehavior="Manual" UnloadedBehavior="Stop" MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" /> <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Height="30" Grid.Row="1"> <Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" /> </StackPanel> </Grid> A: You can achieve this using a Grid. <Grid Height="300" Width="300"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <MediaElement Source="media\numbers.wmv" Name="myMediaElement" LoadedBehavior="Manual" UnloadedBehavior="Stop" MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded" /> <TextBlock Margin="5" Grid.Row="1" VerticalAlignment="Center" Text="Video Label" /> </Grid> Using the Height attribute on the second RowDefinition, you force that row to size to it's contents. The preceding RowDefinition then fills the rest of the available space (in your case, your MediaElement).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Playing one MediaPlayer instance at a time I'll keep it simple. I'm making what could essentially be considered a soundboard. I have everything working the way I want with one exception. When I select one ImageView, the sound assigned to it plays. When I select another ImageView, the sound assigned to it plays, but the first sound is still playing. They just overlap. I want the previous sound to stop when the new one starts. I do see where similar questions have been asked about this, but none of those have helped me. Is there just something simple I can change to make it work? Here's my code (minus the imports to save space): public class ringtones extends Activity implements OnClickListener { MediaPlayer songPlaying; MediaPlayer ring1; MediaPlayer ring2; MediaPlayer ring3; String songFile; String songTitle; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.ringview); //Rintones Sound ring1 = MediaPlayer.create(ringtones.this, R.raw.cc_sgl_rm); ring2 = MediaPlayer.create(ringtones.this, R.raw.cc_sgl_kft); ring3 = MediaPlayer.create(ringtones.this, R.raw.cc_sgl_e); ImageView iv = (ImageView)findViewById(R.id.ccsgl1); iv.setOnClickListener(this); registerForContextMenu(iv); ImageView iv2 = (ImageView)findViewById(R.id.ccsgl2); iv2.setOnClickListener(this); registerForContextMenu(iv2); ImageView iv3 = (ImageView)findViewById(R.id.ccsgl3); iv3.setOnClickListener(this); registerForContextMenu(iv3); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.ccsgl1: ring1.start(); songFile = "cc_sgl_rm"; songTitle = "Regenerate Me"; songPlaying = ring1; break; case R.id.ccsgl2: ring2.start(); songFile = "cc_sgl_kft"; songTitle = "Knock Four Times"; songPlaying = ring2; break; case R.id.ccsgl3: ring3.start(); songFile = "cc_sgl_e"; songTitle = "Eleven"; songPlaying = ring3; break; } } public boolean stopsong(MediaPlayer songPlaying){ if(songPlaying!=null){ songPlaying.stop(); songPlaying.release(); songPlaying.start(); } return false; } //CONTEXT MENU @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Save as..."); menu.add(0, v.getId(), 0, "Ringtone"); } @Override public boolean onContextItemSelected(MenuItem item) { if(item.getTitle()=="Ringtone"){function1(item.getItemId());} else {return false;} return true; } public void function1(int id){ if (savering(R.raw.cc_sgl_rm)){ // Code if successful Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); } if (savering(R.raw.cc_sgl_kft)){ // Code if successful Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); } if (savering(R.raw.cc_sgl_e)){ // Code if successful Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show(); } else { // Code if unsuccessful Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show(); } } //Save into Ring tone Folder public boolean savering(int ressound){ byte[] buffer=null; InputStream fIn = getBaseContext().getResources().openRawResource(ressound); int size=0; try { size = fIn.available(); buffer = new byte[size]; fIn.read(buffer); fIn.close(); } catch (IOException e) { // TODO Auto-generated catch block return false; } String path="/sdcard/media/audio/ringtones/"; String filename=songFile+".mp3"; boolean exists = (new File(path)).exists(); if (!exists){new File(path).mkdirs();} FileOutputStream save; try { save = new FileOutputStream(path+filename); save.write(buffer); save.flush(); save.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block return false; } catch (IOException e) { // TODO Auto-generated catch block return false; } sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename))); File k = new File(path, filename); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath()); values.put(MediaStore.MediaColumns.TITLE, songTitle); values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3"); values.put(MediaStore.Audio.Media.ARTIST, "six3six"); values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); //Insert it into the database this.getContentResolver().insert(MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values); return true; } A: If your sound clips are less than 1 MB, try using SoundPool instead of MediaPlayer. SoundPool pool = new SoundPool(maxStreams, streamType, srcQuality); Set maxStreams to the number of sounds you want to be able to play at once (1 in your case). streamType will probably be AudioManager.STREAM_MUSIC set srcQuality to 0 (it's not yet implemented). Then you'll call pool.load(this, R.raw.sound_file, 1); to load your sound file. The docs for SoundPool are pretty good: http://developer.android.com/reference/android/media/SoundPool.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7543027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: saving date to RMS in Java ME I would like to save a Date object into an RMS in Java ME. The way I would like to do it is by converting the date first to some String/int/any primitive data type value that the RMS can save. I then would like to read this data back and create a Date object from it. So how can I do this? A: You can use Date.getTime(), which returns a long. You can reverse the process by using the new Date(long) constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Improve Load Time of Sectioned UITableView I am displaying a UITableView modally, but it takes about two seconds for it to appear, below is the code that is holding up the transition. ModalViewController.m: - (void)viewDidLoad { [super viewDidLoad]; // get all songs from iTunes library MPMediaQuery *songQuery = [MPMediaQuery songsQuery]; // put the songs into an array self.songsArray = [songQuery items]; // create a sectioned array where songs are sectioned by title self.sectionedSongsArray = [self partitionObjects:self.songsArray collationStringSelector:@selector(title)]; } - (NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector { UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation]; NSInteger sectionCount = [[collation sectionTitles] count]; NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount]; for(int i = 0; i < sectionCount; i++) { [unsortedSections addObject:[NSMutableArray array]]; } for (id object in array) { NSInteger index = [collation sectionForObject:object collationStringSelector:selector]; [[unsortedSections objectAtIndex:index] addObject:object]; } NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount]; for (NSMutableArray *section in unsortedSections) { [sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]]; } return sections; } The above code works fine, but its slow to load the modal view first time, is there a better way to do this? Thanks. A: Yeah: don’t do it in -viewDidLoad. A better place would be in the view controller’s -init or -initWithNibNamed:bundle: or whatever, and in the background. Example: - (id)init { self = [super init]; if(self) { // ... dispatch_async(dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAULT, 0), ^{ // since it's not on the main thread, you need to create your own autorelease pool to prevent leaks NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; MPMediaQuery *songQuery = [MPMediaQuery songsQuery]; self.songsArray = [songQuery items]; self.sectionedSongsArray = [self partitionObjects:self.songsArray collationStringSelector:@selector(title)]; // UI calls have to be on the main thread, so we go back to that here dispatch_async(dispatch_get_main_queue(), ^{ if([self isViewLoaded]) { [self.tableView reloadData]; } }); // this releases any objects that got autoreleased earlier in the block [pool release]; }); } return self; } Your -tableView:numberOfRowsInSection: method should of course now check whether sectionedSongsArray is non-nil and in that case return 0 (or 1 if you want to display a “loading” cell, which you probably should).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add rows to mysql database table and display it in a listbox in vb.net? I have the following controls: * *textbox1 - this is where i type a message. *listbox1 - this is where i display the messages. *button1 - this is what posts my messages to the server. *StatusStrip1.Title1 - this is where the current user's title will go. (i.e: Administrator, manager... etc.) I have a table on a MYSQL database called "messages" and a column called "message". When i type something into textbox1 and click button1 i want to add a row to "messages" under the column "message" with the title and message as its value.(separated by a hyphen, dash, or other small delimiter)Then reload listbox1's contents to show the new message. so i want the final message to be something like: Administrator - Hello World! I currently have the following code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO messages(message) VALUES(?name - ?message)"";", con) sqlpost.Parameters.AddWithValue("?name", Title2.Text) sqlpost.Parameters.AddWithValue("?message", TextBox1.Text) Try con.Close() con.Open() ' Sending message. If TextBox1.Text = "" Then MessageBox.Show("You forgot to type a message!") Else sqlpost.ExecuteNonQuery() ' Reloading messages. ListBox1.Items.Clear() reader = sqlmessages.ExecuteReader() While (reader.Read) ListBox1.Items.Add(reader.Item("message")) ListBox1.Items.Add("") End While reader.Close() con.Close() TextBox1.Text = "" Label4.Text = "Message Sent!" Timer2.Start() End If Catch myerror As MySqlException MessageBox.Show("Error sending message to server: " & myerror.Message) End Try End Sub I had it working before, but when i made changes to it, it came up with various sql statement syntax errors... (stuff like invalid truncated value of "Administrator", or invalid DOUBLE value "hello") and now it won't even display any messages currently in the "messages" table...) If anyone could tell me what i'm doing wrong, or a more efficient way of doing this then i would greatly appreciate it! Thanks! A: One thing I see that looks incorrect is that you are using "?" for you parameter names in the query. The default character to use for parameter names is to start them with "@". Although I think there's a connection string option to use "?" as that is what was used in the older versions of the MySQL connector, but the current default is "@". Also, there seems to be some problems with your command in general. You have: Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO messages(message) VALUES(?name - ?message)"";", con) it should probably be something more like Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO messages(message) VALUES(@message);", con) I fixed up the query a bit, and replaced the ? with @. You you can do the concatenation of name and message (as you cleared up in the comment) in VB, with some code such as this: sqlpost.Parameters.AddWithValue("@message", Title2.Text & " - " & Title2.Text) I also see that you are calling sqlmessages.ExecuteReader() but I don't see where this is being initialized. A: You should have to use single parameter. Dim con as New MySqlConnection con.ConnectionString="set_connection_string_here" Dim sqlpost As MySqlCommand = New MySqlCommand("INSERT INTO `messages` (`message`) VALUES (@name)",con) sqlpost.Parameters.AddWithValue("@name", Title2.Text & " - " & TextBox1.Text) If TextBox1.Text = "" Then MessageBox.Show("You forgot to type a message!") Else con.Open() sqlpost.ExecuteNonQuery() con.Close() ListBox1.Items.Clear() sqlmessages.CommandText="select * from `messages`" sqlmessages.Connection=con reader = sqlmessages.ExecuteReader() While (reader.Read) ListBox1.Items.Add(reader.Item("message")) End While reader.Close() con.Close() End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7543034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIWindow UIView addSubview issue Every video tutorial and book I have read displays the following code to add a UIView to the UIWindow. [window addSubview:self.viewController.view]; My understanding of the above code is that a "View" (which is an instance of a UIView) is added to the window (Which is an instance of UIWindow). Let me break it down (According to my understanding): window (UIWindow) addSubview (method to add a View to a window) Self.viewController.view (simply returns an instance of a "view" which is already instantiated within the UIViewController class. The first problem I have is that I could not find the method "addSubview" in the UIWindow class reference document on apples site. However somebody kindly pointed out to me that UIWindow inherits addsubview method from UIView. thats all fine, but why do all the book and online documents state that the addsubview method adds a view to the window - but how can that be? really confused. Can somebody please explain step by step what this code is doing? If UIWindow inherits the addsubview method of UIView then how can it go back up the inheritance tree? really lost. What I really need is small example code with diagrams of what is happening step by step. would be REALLY greatfull. many thanks A: Think of a window as a view that's associated directly with a screen or drawing object. In the above example window.view is not correct. a window does not contain a view, it is a view with additional behavior. Assuming that you are loading a UIViewController from a NIB file, the view associated with the viewController will be instantiated by accessing the view. So ... You might see code like MyViewController *vc = [MyViewController alloc]initWithNibName:@"MyNibFile" bundle:nil]autorelease]; [window addSubView:vc.view]; [window makeKeyAndVisible]; View is simply a super class of Window so any public view method is available to you. Generally the window in your AppDelegate object is instantiated when the MainWindow.xib file is loaded. You should see something like @property(nonatomic, retain) IBOutlet UIWindow *window; in your AppDelegate header file . (The IBOutlet directive tells the initialize the window object when the nib file is loaded. Just remember, a UIWindow is simply a UIView with additional behaviors and data. Hope this helps. A: "However somebody kindly pointed out to me that UIWindow inherits addsubview method from UIView. thats all fine, but why do all the book and online documents state that the addsubview method adds a view to the window - but how can that be? really confused. Can somebody please explain step by step what this code is doing? If UIWindow inherits the addsubview method of UIView then how can it go back up the inheritance tree?" That's it. I think you are not understanding what inheritance is. The metaphor is "is a". A UIWindow "is a" UIView. It has everything a UIView has, and more. One thing a UIView has is the ability to addSubview. Therefore a UIWindow has that ability too. It doesn't need any other UIView to do it for it. It is a UIView. It can do it itself. A: try [window.view addSubview:self.viewController.view]; That is off the top of my head, so it may not be completely accurate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is wrong with this JQuery code? <script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script type="text/javascript"> //waits till the document is ready $(document).ready(function() { //onclick function $('button.butter').click(function(){ //code will only run on certain url if (pathname.indexOf("google")>= 0){ alert('This doesn't work anymore!'); //replacer $("a[href*='https://google.com']").attr('href',('http://www.google.com/search?q' + $('#FormID').val())); } else{ alert('Wrong page'); } }); }); </script> It doesn't alert, but why? This was working earlier and I forgot to save it. It should replace the url with another one plus the value from a field. edit: head, html, etc. tags are there. <button class="butter">Press</button> A: You don't declare pathname anywhere, this: if (pathname.indexOf("google")>= 0){ should result in an error in your console. A: I think you want location.pathname rather than pathname
{ "language": "en", "url": "https://stackoverflow.com/questions/7543043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to trigger cellTemplateSelector when Items changed I have 2 templates for DataGrid's CellTemplate. When I change the items, it won't help me select the template for me, my DisplayModeTemplateSelector won't even be called! What I'm wondering is if there is a way to trigger this CellTemplateSelector again when items changed? How to refresh CellTemplate in DataGrid or ListView When Content Changes <DataGridTemplateColumn x:Name="colorRange" Width="*" Header="Color Range"> <DataGridTemplateColumn.CellTemplateSelector> <local:DisplayModeTemplateSelector HeatMapTemplate="{StaticResource heatMapTemplate}" ThreshHoldTemplate="{StaticResource threshHoldTemplate}" /> </DataGridTemplateColumn.CellTemplateSelector> </DataGridTemplateColumn> I found this blog http://dotdotnet.blogspot.com/2008/11/refresh-celltemplate-in-listview-when.html I think this is similar with my problem, but I really can't understand him! Can anyone explain it? A: The solution in the blog post will not work with the DataGrid control because the DataGridTemplateColumn class doesn't belong to the Visual Tree, and even when I tried to bind it to a static class, I didn't suceed because of strange exceptions after property changes. Anyway there is two possible ways to solve this problem. 1) The easier way. Using the ObservableCollection class. var itemIndex = 0; var currentItem = vm.Items[itemIndex]; //Change necessary properties //.. vm.Items.Remove(currentItem); vm.Items.Insert(itemIndex, currentItem); 2) The more complex way. You can add to your item class the property which returns the object itself. public ItemViewModel(/*...*/) { this.SelfProperty = this; //... } public ItemViewModel SelfProperty { get; private set; } public void Update() { this.SelfProperty = null; this.OnPropertyChanged("SelfProperty"); this.SelfProperty = this; this.OnPropertyChanged("SelfProperty"); } After that you can use the ContentControl.ContentTemplateSelector instead of the CellTemplateSelector like this: <DataGridTemplateColumn Header="Color Range"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ContentControl Content="{Binding SelfProperty}" ContentTemplateSelector="{StaticResource mySelector}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> And when you change the property, call the Update method somehow: currentItem.SomeDataProperty = "some new value"; //Or you can add this method call to the OnPropertyChanged //so that it calls authomatically currentItem.Update(); The reason why I've set a null value to the SelfProperty in the Update method first, is that the Selector will not update a template until the Content property is completely changed. If I set the same object once again - nothing will happen, but if I set a null value to it first - changes will be handled. A: The easy way is to hook the Combo Box's Selection Changed event, and reassign the template selector. This forces a refresh. In XAML (assume the rest of the DataGrid/ComboBoxColumn: <DataGridComboBoxColumn.EditingElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.Gates, UpdateSourceTrigger=PropertyChanged}"/> <EventSetter Event="SelectionChanged" Handler="GateIDChanged" /> </Style> That refers to this DataGridTemplateColumn: <DataGridTemplateColumn x:Name="GateParamsColumn" Header="Gate Parameters" CellTemplateSelector="{StaticResource GateParamsTemplateSelector}"></DataGridTemplateColumn> And in the code behind: private void GateIDChanged(object sender, SelectionChangedEventArgs eventArgs) { var selector = GateParamsColumn.CellTemplateSelector; GateParamsColumn.CellTemplateSelector = null; GateParamsColumn.CellTemplateSelector = selector; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JavaScript SDK auto log me in I am trying to see if something is possible. If I am updating my website to act as a proxy for me and want to know if there is any way to access myself via Open Graph when someone comes to my site without having me needing to literally log myself in? I was only hoping to leverage the JavaScript SDK; not looking to have a back-end if possible. A: You could embed an access token in your javascript code but this is pretty unsafe because other users could look at your source code and use this token themselves. A much safer way would be to do this with server back-end code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 C#4.0 / Passing variables between views new to C# and MVC. What I would like to achieve is passing a variable as ViewData from one view to another view without using ID in the ActionResult because this view generates it own variable. I am sure there are better ways to do that, but here what I thought might work. First I made a model: public class EventToShow { public Int64? ID { get; set; } public Int64? EventID { get; set; } } Then I passed the variable EventID from the first View (Telerik MVC GRID) using the following: columns.Template(item => Html.Raw(string.Format("<a href=\"{0}\">{1}</a>", Url.Action("tableread", "Home", new { id = (long)item.Event_ID }), "EventID"))).Width(20); It worked using the following in my controller: [AcceptVerbs(HttpVerbs.Post)] public ActionResult tableread1(long? id) { ViewData["EID"] = id; EventToShow ctx = new EventToShow(); ctx.ID = 1; ctx.EventID = (long)ViewData["EID"]; return RedirectToAction("EditServerSide"); } To pass the variable to the other view I tried to use the following (I think it is very wrong): public ActionResult EditServerSide() { EventToShow ctx = new EventToShow(); var model1 = ctx.(x => x.ID == 1); **// The error here is (Identifier** expected) ViewData["EID"] = ctx.EventID; var model = from o in new Main().OffLinePayments select new EditOffLinePayment { ID = o.ID, Amount = o.Amount, Details = o.Details }; return View(model, ViewData["EID"]) **(this must be wrong)** } I thought maybe I should make the variable like this: private string GetFullName() { EventToShow ctx = new EventToShow(); var name = EventToShow().Where(x => x.ID == 1); ViewData["EID"] = ctx.EventID; return name; } First I got an error: ‘GridEdit_OfflinePayment.Models.EventToShow' is a 'type' but is used like a 'variable' I also did not know how to incorporate returned [name] in the EditServerSide Action. My question, is there a better way to achieve what I am trying to do, and if this approach is correct, I would appreciate any help to fix these errors A: From what I understand of the question is that you would like to pass data between several Actions? Like some sort of wizard steps process where you can pass data between multiple Actions? If that's the case then here are some related questions and their answers: How do I pass data across ActionResults in MVC 3? multi-step registration process issues in asp.net mvc (splitted viewmodels, single model)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What happen to existing server queries when pushing new Rails code to Heroku or putting it in maintenance mode? This page http://devcenter.heroku.com/articles/maintenance-mode doesn't give any indication. Server queries to Heroku could run up to 30 seconds before they got terminated forcefully. So I am wondering what would happen if I push new code to the busy server, or set it to be in Maintenance mode? Would the existing queries just stopped? What if it is writing to a database, etc? Would it leave my data in a corrupted state? Is there a correct way to let Rails app to shut down gracefully (finishing existing queries but not accepting any new one), so that I can upgrade the server code? Thanks. A: When you put your app in maintenance mode you are not changing your codebase at all. It's a front-end configuration. It means, if a query was sent to the database, the database won't be stopped and the query will be executed. The connections are not dropped when you switch to maintenance mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent users from entering invalid characters inside an input field Given a text input field. How can I prevent users from entering spaces, and other other than letters numbers or dashes (-). Alphanumerics only - "The alphanumeric character set consists of the numbers 0 to 9 and letters A to Z. In the perl programming language, the underscore character ( _ ) is also considered to be a member of the alphanumeric set of characters" This is for a field where users can pick a custom url. I would like to prevent users from entering invalid characters. Ideas? Thanks A: You can do this using the jQuery keyup(..) method. You will want to check that the event.keyCode is something valid. If it is not valid, you can prevent the event with preventDefault(). Remember to validate the data sent to the server because anything you do in javascript can be subverted. Here is a library to do it for you: http://www.itgroup.com.ph/alphanumeric/ A: DEMO - JS Fiddle Link Sorry for the late response. Though my answer is late. I have modified few changes to the answer and here it goes. Validation Required * *Restrict Digits entering on initial *Restrict Spaces, special characters but allow backspace and delete *Enable Alpha Numeric Characters <input name="pac_code" id="input_8_6" type="text" value="" class="form-control medium pacerror pacvalid" data-rule-maxlength="9" data-rule-minlength="9" maxlength="9" minlength="9" placeholder="Porting authorisation code (PAC) *" data-rule-required="true" autocomplete="off" size="9"> <label for="input_8_6" style="color: #ff0000;font-weight: 300;font-size: 12px;margin-bottom: 1%;">Example: ABC123456</label><br /> <label class="PAC_error error" style="display:none;">Invalid PAC Format</label> </div> JQuery jQuery(document).ready(function() { $('#input_8_6').bind('keypress', function(event) { var regex = new RegExp("^[a-zA-Z0-9\b]+$"); var regchar = new RegExp("^[a-zA-Z\b]+$"); var regnum = new RegExp("^[0-9\b]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); var pacvalue = $(this).val().length; if (!regex.test(key)) { event.preventDefault(); return false; } else if (pacvalue <= 2) { for (i = 0; i <= 2; i++) { if (!regchar.test(key)) { event.preventDefault(); return false; } } } else if (pacvalue >= 3) { for (j = 4; j <= 9; j++) { if (!regnum.test(key)) { event.preventDefault(); return false; } } } else { return true; } }); }); A: There are plenty of Javascript validation libraries out there. A quick Google search for 'javascript validation' produced the JQuery Validation plugin plugin as the first hit, so that's probably a good place to start. As @Chris Cooper said, make sure that you also do server-side validation, because it's pretty trivial for a user to turn off javascript and avoid your client-side validation rules. A: Though my answer is very late, but this may help for further readers/techie's. Who wants to implement a textbox to accepts with below condition. * *should accept Alphabets. *should accept Numbers. *should not accept any special characters. Below is the code. $("input[name='txtExample'] ").focus(function (e) { if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) { event.preventDefault(); } }).keyup(function (e) { if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) { event.preventDefault(); } }).keypress(function (e) { if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) { event.preventDefault(); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="txtExample"/> added with example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I add jpg files to ipa and load them with FileStream class I'm developing a tile engine with actionScript-3 for IOS machines. Is there a way to package JPG files with IPA and then read them with Adobe Air's FileStream Class. I need to read files asynchronously. Embeding them or putting them in a swc wouldn't help. I understand how it works on desktop. var file:File = File.documentsDirectory.resolvePath("myfile.txt"); On desktop, means: [user_dir]/Documents/myfile.txt On IOS: [app_dir]/Documents/myfile.txt How can I package the IPA that has "myAsset.jpg" in "[app_dir]/Documents/" directory? I tried to open a "Documents" directory and put some files in it and include it in the package content section of the run configration of flash builder 4.5.1. But that didn't work. Thank you. A: When you package the image files with your application, they will be in the application directory, which you can access with the File.applicationDirectory property. You should be able to load your images directly from there. If you want the images in the documents directory, you will have to copy them there after installation. A: One Addition to Joes answer: When you add a folder over adt the actual folder is added not its contents. So if you add the Folder assets you access your images like this: File.applicationDirectory.resolvePath("assets/image.jpg");
{ "language": "en", "url": "https://stackoverflow.com/questions/7543065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails: controller method or instance variable inside a helper I'm using the bitly gem and would like to have access to the bitly API inside my helper methods (which get called by views and mailers to generate URLs). I initiate an API connection in this method in my ApplicationController: (is there a more appropriate place to do this BTW?) class ApplicationController < ActionController::Base before_filter :bitly_connect def bitly_connect Bitly.use_api_version_3 @bitly ||= Bitly.new(APP_CONFIG['bitly_username'], APP_CONFIG['bitly_api_key'] ) end end By default I don't have access to @bitly in my helpers. Can you suggest a way to accomplish that? The only related thread I found wasn't helpful: Rails 3 and Controller Instance Variables Inside a Helper Thanks. A: If you need a controller method to be accessible as a helper, you can use helper_method class ApplicationController < ActionController::Base helper_method :bitly_connect def bitly_connect @bitly ||= begin Bitly.use_api_version_3 Bitly.new(APP_CONFIG['bitly_username'], APP_CONFIG['bitly_api_key'] ) end end end Note that I also altered the method, so that it doesn't call Bitly.use_api_version_3 each time it is called. As Ben Simpson noted, you should probably move this into a Model though. A: Rails by convention passes instance variables set in the controller actions (and filters) along to the views. The helper methods are available in these views, and should have access to the instance variables you set inside your controller action. Alternately, you can set a local variable inside your helper method by passing the variable to the method, or by using the Object#instance_variable_get method: http://ruby-doc.org/core/classes/Object.html#M001028 # app/controllers/example_controller.rb class ExampleController def index @instance_variable = 'foo' end end # app/helpers/example_helper.rb module ExampleHelper def foo # instance variables set in the controller actions can be accessed here @instance_variable # => 'foo' # alternately using instance_variable_get variable = instance_variable_get(:@instance_variable) variable # => 'foo' end end As for your concerns with the placement of the logic, it does not look like it belongs in the controller. Think of the controller as routing requests for your application. Most logic should be performed inside of your model classes. "Skinny controller, fat model.": http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
{ "language": "en", "url": "https://stackoverflow.com/questions/7543070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: what is wrong with this simple regex? I am stuck in a dump: import re print re.search('return[^$]+', 'return to the Treasury of $40 million\nnow!').group(0) The above regex only prints return to the Treasury of, but I expected it to include $40 million. What I understand from regex is that I am asking it to take every thing until the end of the line. I do not want to use .*, I want endline delimiter to go until the end of line from some point. If I remove $ from search string it prints the full string. Why is endline delimiter matching with dollar sign?? A: return[^$]+ will match a string "return" followed by any character that is not '$' one or more times. This is because [ ] mean character group and inside [ ] the special characters are threaded as simple characters. Thus it matches only until the the dollar sign. Why not use: return.+$ this is exactly what you want. A: Why don't you want to use .*? The regex you have will match any string that starts with "return", then one or more characters that are not the "$" character. Note that this will NOT look for the end-of-line marker. return.*$ will match everything up to and including the end of line marker. You may (but probably not) need to make the .* a lazy matcher if you are dealing with multi-line input. A: import re text = 'we will return to the Treasury of $40 million\nunits of money.' re.search(r'return.*$', text, re.MULTILINE).group(0) # prints 'we will return to the Treasury of $40 million' You need to include the multiline flag, then $ will match at newlines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting fb.me URL How do I go about either making, or retrieving facebook short url's (fb.me) from a page, profile, event etc? I want to update my url shortener site - but if the user links to a facebook page I want to just return a fb.me link instead. Does facebook make their short urls on the fly, or does each page automatically already have one? A: Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work. A: You can use bit.ly api to create facebook short urls find the documentation here http://api.bitly.com A: I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )
{ "language": "en", "url": "https://stackoverflow.com/questions/7543077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to load an image in memory with Flex/ActionScript? So I'm trying to load an embedded image this way: [Bindable] [Embed(source="path")] private var cls_img:Class; var img:Image = new Image(); img.source = cls_img; Now I'm trying to copy pixel chunks from it however I get an error that img.bitmapData is null and the error goes away when I add it to the application with addElement(img); Isn't it possible to force flex to load the image in memory so I can manipulate it without adding it to the stage? A: Yes - you can use cls_img as a BitmapAsset. [Bindable] [Embed(source="path")] private var cls_img:Class; ... var asset:BitmapAsset = new cls_img() as BitmapAsset; // The asset has a bitmapData property that gives you access to the image data img.source = asset; For more information, check out the documentation: http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7543078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to print http response first and do the heavy db operations later? I'm implementing a mobile api. One of the requests processes json data and returns afterwards a predefined message( is independent from the calculation) back to the device. I'm using kohana 3. How do I return the http response first and do the calculation afterwards? What do you think about, using a message queue and a separate program that does the processing and db operations? A: One option would be to use gearman. There is a Kohana gearman module made by one of the Kohana devs. A: Maybe you can help flush() function, which send buffer (and header also). But flush() don't guarantee header send, because between php and web browser stays a web server (like apache) A: Not sure I understand your question, but if you want to buffer output you can use ob_start() and ob_get_clean() A: I think you might be looking for something like ignore_user_abort(true) http://www.php.net/manual/en/function.ignore-user-abort.php After making the call you can send your response back to the browser and finish wrapping up your calculations/logging after the connection is closed and the client is off doing something else. This enables you to do some quick processing without hanging up the client or having to use an external process to handle your tasks
{ "language": "en", "url": "https://stackoverflow.com/questions/7543081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to walk dynamically into multidimensional arrays? For example: $size = 0; $array = $array; $size = 1; $array = $array[x]; $size = 5; $array = $array[x][x][x][x][x]; I got a $config array that can either have 1 dimension or many. Depending on setting of the var $size the elements I need walk gonna be on that position. If size = 1, I will be looking for $config[1]. If size = 2 I will be looking for $config[1][1] ... Thanks, A: $foo = $array; for($i=0;$i<$size;++$i) { $foo = $foo[x]; } A: $array = $array[x][x][x][x][x]; for ($x = 0; $x < 5; $x++) { if (!is_array($array[1])) break; $array = $array[1]; } You can make infinite loop and reach end of array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby: Resize Images without ImageMagick? Is there a way to resize images in Ruby without ImageMagick.... and also without ruby-vips? Yes, I know I am being rather narrow, but can't seem to get both of them to install on my Mac, which is kinda annoying. I just wanna resize, nothing fancy... anything lightweight? A: Quick search on ruby gems.org leads to a few candidates: http://rubygems.org/search?query=image+resize Also, with regard to having trouble installing ImageMagick on your Mac. Do you know about Homebrew? A: There used to be ImageScience, but I'm getting a lot of broken links for it when googling now. Might also try to find Ruby lib for GD or GD2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Callback conflict Both of my callback methods have update_attributes in them. So it looks like when calculate_rating runs it also calls modify_rating. I only want calculate_rating to run for creating a new record and modify_rating to run only when editing and updating a record through a form. after_create :calculate_rating before_update :modify_rating def calculate_rating end def modify_rating end A: From the fine manual for update_attributes: Updates the attributes of the model from the passed-in hash and saves the record [...] So when you call update_attributes, it will try to save the object and that means that update_attributes is not appropriate for either of the callbacks you're using; update_attributes is meant to be used by controllers for mass assignment and the like. You could replace the update_attributes call with simple assignments: def calculate_rating self.attr1 = 11 self.attr2 = 23 #... end
{ "language": "en", "url": "https://stackoverflow.com/questions/7543095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect unreachable ports for UDP in Erlang I am looking for a way to detect "port unreachable" errors for outgoing UDP packets in Erlang, so I can eagerly report transport layer errors to the application. I.e, I want to capture ICMP type 3 packets to report to the higher layers that packet have not reached the destination. Currently I know about two approaches: * *Use undocumented gen_udp:connect/3. However, it seems like this requires opening a new socket for every new destination pair address:port. The advantage is that this does not require any privileges. *Use gen_icmp which requires either setuid helper or capabilities to open raw sockets. Are there any other variants I am missing? A: procket might be what you're looking for, but I've never used it myself. It's a binding to the low-level socket API, therefore it allows you to use all the protocols the underlying API supports. I'm just quoting its README, so please take it with a pinch of salt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to sort the elements (columns) in xslt to transform the xml file to csv format <?xml version="1.0" encoding="utf-8"?> <Report p1:schemaLocation="Customer details http://reportserver?%2fCustomer details&amp;rs%3aFormat=XML&amp;rc%3aSchema=True" Name="Customer details" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance" xmlns="Customer details"> <table2> <Detail_Collection> <Detail Col1="aaa" col1_SeqID="2" col1_Include="1" Col2="aaa" col2_SeqID="1" col2_Include="1" Col3="aaa" col3_SeqID="" col3_Include="0" Col4="aaa" col4_SeqID="4" col4_Include="1" Col5="aaa" col5_SeqID="" col5_Include="0" ... ... ... ... ... ... ... ... ... Col50="aaa" col50_SeqID="3" col50_Include="1" /> <Detail_Collection> </table2> </Report> The above xml is produced by SSRS for the RDL file. I want to transform the above xml file to CSV format using XSLT (customized format). The RDL file (SSRS report) is very simple with 50 columns, and displays the data for all the columns depending on the user selection on the user interface. The user interface has got the parameter selection for all the 50 columns (i.e they can select the order of the column, they can select a particular column to be included on the report or not, the fontstyle etc...). As mentioned the each column has 2 main functionalities i.e. they can be sorted and as well ordered by based on the selections. For example from the report output i.e in the xml format given above you will see all the 50 columns exist on the xml format but I am also including the extra fiedls which are generally hided on the report. The col1 is included on the report and is ordered (seqID) as the 2nd column on the csv file. The col2 is also included on the report and is ordered as the 1st column on the csv file. The col3 is not included on the report and the order selection is empty, so this is not included on the csv file. ... ... like wise the col50 is included on the report but is ordered in as 3rd column in the csv file. My main challenge here to create the xslt file for "CSV" and put the columns in the order selection which are selected per user basis. The output in the CSV file after transformation will look as follows: Col2 Col1 Col50 Col4 ... ... ... .... Any good idea to create this kind of xsl file is much appreciated and I thank you so much for understanding my question and trying to help me in this regard. A: I. This XSLT 1.0 transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:c="Customer details"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="c:Detail"> <xsl:apply-templates select= "@*[substring(name(), string-length(name())-5) = '_SeqID' and number(.) = number(.) ] "> <xsl:sort data-type="number"/> </xsl:apply-templates> </xsl:template> <xsl:template match="@*"> <xsl:if test="not(position()=1)">,</xsl:if> <xsl:value-of select= "../@* [name() = concat('Col',substring-before(substring(name(current()),4),'_')) ]"/> </xsl:template> </xsl:stylesheet> when applied on this XML document (the provided one, made well-formed and unambiguous): <Report p1:schemaLocation="Customer details http://reportserver?%2fCustomer details&amp;rs%3aFormat=XML&amp;rc%3aSchema=True" Name="Customer details" xmlns:p1="http://www.w3.org/2001/XMLSchema-instance" xmlns="Customer details"> <table2> <Detail_Collection> <Detail Col1="aaa1" col1_SeqID="2" col1_Include="1" Col2="aaa2" col2_SeqID="1" col2_Include="1" Col3="aaa3" col3_SeqID="" col3_Include="0" Col4="aaa4" col4_SeqID="4" col4_Include="1" Col5="aaa5" col5_SeqID="" col5_Include="0" Col50="aaa50" col50_SeqID="3" col50_Include="1" /> </Detail_Collection> </table2> </Report> produces the wanted, correct result: aaa2,aaa1,aaa50,aaa4 Explanation: * *We use that the XPath 1.0 expression: __ substring($s1, string-length($s1) - string-length($s2) +1) = $s2 is equivalent to the XPath 2.0 expression: ends-with($s1, $s2)) .2. Appropriate use of <xsl:sort>, substring(), name() and current(). .3. Using the fact that a string $s is castable to number if and only if: __ number($s) = number($s) II. XSLT 2.0 solution: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:c="Customer details"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="c:Detail"> <xsl:apply-templates select= "@*[ends-with(name(),'_SeqID') and . castable as xs:integer]"> <xsl:sort select="xs:integer(.)"/> </xsl:apply-templates> </xsl:template> <xsl:template match="@*"> <xsl:if test="not(position()=1)">,</xsl:if> <xsl:value-of select= "../@* [name() eq concat('Col',translate(name(current()),'col_SeqID',''))]"/> </xsl:template> </xsl:stylesheet> when this transformation is applied on the same XML document (above), the same correct result is produced: aaa2,aaa1,aaa50,aaa4 Update: @desi has asked that the heading should also be generated. Here is the updated XSLT 1.0 transformation (as indicated, @desi is limited to use XSLT 1.0 only) that does this: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:c="Customer details"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="c:Detail"> <xsl:for-each select= "@*[substring(name(), string-length(name())-5) = '_SeqID' and number(.) = number(.) ] "> <xsl:sort data-type="number"/> <xsl:value-of select= "concat('Col', substring-before(substring(name(current()),4), '_') ) "/> <xsl:text>&#9;</xsl:text> </xsl:for-each> <xsl:text>&#10;</xsl:text> <xsl:apply-templates select= "@*[substring(name(), string-length(name())-5) = '_SeqID' and number(.) = number(.) ] "> <xsl:sort data-type="number"/> </xsl:apply-templates> </xsl:template> <xsl:template match="@*"> <xsl:if test="not(position()=1)">,</xsl:if> <xsl:value-of select= "../@* [name() = concat('Col',substring-before(substring(name(current()),4),'_')) ]"/> </xsl:template> </xsl:stylesheet> When this transformation is applied on the same XML document (above), the wanted, correct result is produced: Col2 Col1 Col50 Col4 aaa2,aaa1,aaa50,aaa4
{ "language": "en", "url": "https://stackoverflow.com/questions/7543099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Grammar involving braces I'm trying to solve DCG grammar in prolog and succeeded upto a point, i'm stuck in evaluating the expressions involving braces like these. expr( T, [’(’, 5, +, 4, ’)’, *, 7], []), expr(Z) --> num(Z). expr(Z) --> num(X), [+], expr(Y), {Z is X+Y}. expr(Z) --> num(X), [-], expr(Y), {Z is X-Y}. expr(Z) --> num(X), [*], expr(Y), {Z is X*Y}. num(D) --> [D], {number(D)}. eval(L, V, []) :- expr(V, L, []). A: The parsers implemented by Prolog's DCG grammars are recursive-descent LL(something) (predictive) grammars. It walks the input from left to right and produces a leftmost derivation as it goes. They're easy to craft but the grammar's must conform to a few restrictions: They cannot be left-recursive. Infinite recursion can/will result. This means that at least one symbol (token) has to be removed from the input stream prior to following a recursive path. Refactoring grammars to remove left-recursion is a fairly mechanical exercise, albeit tedious. See any decent compiler book on how to do that. Operator precedence is typically built into the structure of the grammar itself. Here's BNF notation showing one way of defining a recursive descent grammar for the parsing/evaluation of simple arithmetic expressions: ArithmeticExpression : AdditiveExpression ; AdditiveExpression : MultiplicativeExpression | MultiplicativeExpression '+' AdditiveExpression | MultiplicativeExpression '-' AdditiveExpression ; MultiplicativeExpression : ExponentialExpression | ExponentialExpression '*' MultiplicativeExpression | ExponentialExpression '/' MultiplicativeExpression | ExponentialExpression '%' MultiplicativeExpression ; ExponentialExpression : UnaryExpression | UnaryExpression '^' ExponentialExpression ; UnaryExpression : '-' UnaryExpression | AtomicExpression ; AtomicExpression : '(' ArithmeticExpression ')' | ['0'..'9']+ ; The term at each level of operator precedence is built from expressions of the next higher order of precedence. So an arbitrary arithmetic expression is just a single additive expression. Each additive expression is 1 or more multiplicative expressions, joined by addition and subtraction operators. Each multiplicative expression is 1 or more exponential expressions, joined by multiplication, division and remainder operators. Each exponential expression is a unary expression with an option exponent operator followed by another unary expression. Each unary expression is either an atomic expression, or a unary minus followed by another unary expression. Each atomic expression is either an arbitrary arithmetic expression, enclosed in parentheses, or an unsigned integer token. Translation of the above into Prolog's DCG syntax should be trivial. How to evaluate the term represented by each clause in the grammar should be self-evident. A: This is one of the strangest things I observed in the history of Prolog. Namely that a wrong expression syntax is shown around already for ages. The wrong syntax is already found in the DEC10 Prolog documentation and the misfit is seen when we look at a rule: expr(Z) --> num(X), "/", expr(Y), {Z is X/Y}. etc.. This makes the division operator xfy, but it should be yfx. Thus with the above rule an expression 10/2/5 is read as 10/(2/5) and leads to 25 as the result. But in fact the example should be read as (10/2)/5 yielding 1 as the result. The problem is that the correct syntax would be left recursive. And DCG do have problems with left recursive rules. The Prolog interpreter would just run into an infinite loop for a left recursive rules by repeatedly call expr/3: expr(Z) --> expr(X), "/", num(Y), {Z is X/Y} etc.. So the solution is to eliminate the left recursion by introducing an accumulator and additional rules. I don't know whether this method works in general, but it works for sure in the present case. So the correct and depth first executable rule would read: expr(Y) --> num(X), expr_rest(X,Y). expr_rest(X,T) --> "/", !, num(Y), {Z is X/Y}, expr_rest(Z,T). etc.. expr_rest(X,X). The above grammar is a little bit a more challenging DCG. It is not anymore pure Prolog, since it uses the cut (!). But we could eliminate the cut, for example by a push-back, something along the following lines. The push-back is again a complicated matter to explain in a DCG introduction, and we would need to introduce an stop character at the end of an expression to make it work: etc.. expr_rest(X,X), [C] --> [C], {not_operator(C)}. Or we could neither go into the lengths of the cut or the push-back and live with it that on backtracking the parser will do additional, in the present case unnecessary, work. So bottom line is probably, although the example is not correct, it is simple enough to explain DCG without needing to much advanced stuff of DCG. Interestinglyg the missing parenthesis syntax is hardly affected by the elimination of left recursion. Simply add: num(X) --> "(", !, expr(X), ")". Oops, a cut again! Best Regards Full code can be seen here: http://www.jekejeke.ch/idatab/doclet/prod/en/docs/05_run/06_bench/09_programs/10_calculator/01_calculator.p.html P.S.: Instead of eliminating the left recursion, we could also have worked with some form of tabling. A: It just works. However it is not easier than yacc/bison. %?-eval('11*(7+5-2)^2*(11+8)'). eval(A) :- lex(A,L), evallist(L). %?-evallist([11,*,'(',7,+,5,-,2,')',^,2,*,'(',11,+,8,')']). evallist(L) :- e(R,L,[]),write(R),!. e(N) --> t(N1), erest(N1,N). erest(N1,N) --> [+], !, t(N2), {N3 is N1+N2}, erest(N3,N); [-], !, t(N2), {N3 is N1-N2}, erest(N3,N). erest(N,N) --> []. t(N) --> f(N1), trest(N1,N). trest(N1,N) --> [*], !, f(N2), {N3 is N1*N2}, trest(N3,N); [/], !, f(N2), {N3 is N1/N2}, trest(N3,N). trest(N,N) --> []. f(N) --> n(N); n(N1), [^], f(N2), {N is N1**N2}. n(N) --> ['('], !, e(N), [')']; [-], !, e(N1), {N is -N1}; num(N). num(N) --> [N], {number(N)}. lex(A,NL) :- atom_chars(A,L), lex0(_,L,NL). lex0(S,L,NL) :- L=[], (number(S), NL=[S], !; NL=[]), !; L=[E|R], (d(E,N), (number(S), !; S=0), S1 is S*10+N, lex0(S1, R, NL), !; lex0(_,R,NR), (number(S), NL=[S|[E|NR]], !; NL=[E|NR])). d(I,N) :- char_code(I,C), C > 47, C < 58, N is C - 48. A: Adding this clause appears to work: num(D) --> ['('], expr(D), [')']. A: Thanks to @vladimir lidovski and based on the BNF notation (and on my needs), I expanded it to also include logical expressions. Here is my code (To see the full interpreter checkout my git repo): cond_expre(T) --> and_expre(E1), or_rest(E1,T). or_rest(E1,T) --> [punct('|'),punct('|')],!, and_expre(E2), {V = (\/,E1,E2)}, or_rest(V,T). or_rest(T,T) --> []. and_expre(T) --> equality_expre(E1), and_rest(E1,T). and_rest(E1,T) --> [punct(&),punct(&)], !, equality_expre(E2), {V = (/\,E1,E2)}, and_rest(V,T). and_rest(T,T) --> []. equality_expre(T) --> relat_expre(E1), equality_rest(E1,T). equality_rest(E1,T) --> equality_op(Op) ,!, relat_expre(E2), { V=(Op,E1,E2)}, equality_rest(V,T). equality_rest(T,T) --> []. relat_expre(T) --> atomic_texpre(E1), relat_rest(E1,T). relat_rest(E1,T) --> relat_op(Op) ,!, atomic_texpre(E2) , { V=(Op,E1,E2) },relat_rest(V,T). relat_rest(T,T) --> []. atomic_texpre(T) --> arith_expre(T); [punct('(')], !, cond_expre(T), [punct(')')] . arith_expre(V) --> expre(V). equality_op(==) --> [punct(=),punct(=)]. equality_op(\=) --> [punct(!),punct(=)]. relat_op(>=) --> [punct(>),punct(=)]. relat_op(>) --> [punct(>)]. relat_op('=<') --> [punct(<),punct(=)]. relat_op(<) --> [punct(<)]. expre(N) --> multiplicative(N1), additive_rest(N1,N). additive_rest(N1,N) --> [punct('+')], !, multiplicative(N2), {N3 = (+,N1,N2)}, additive_rest(N3,N); [punct('-')], !, multiplicative(N2), {N3 = (-,N1,N2)}, additive_rest(N3,N). additive_rest(N,N) --> []. multiplicative(N) --> atomic(N1), multiplicative_rest(N1,N). multiplicative_rest(N1,N) --> [punct('*')], !, atomic(N2), {N3 = (*,N1,N2)}, multiplicative_rest(N3,N); [punct('/')], !, atomic(N2), {N3 = (/,N1,N2)}, multiplicative_rest(N3,N); [punct('%')], !, atomic(N2), {N3 = (mod,N1,N2)}, multiplicative_rest(N3,N). multiplicative_rest(N,N) --> []. atomic(N) --> [punct('(')], !, expre(N), [punct(')')]; num(N). num(N) --> pl_constant(N). pl_constant(num(N)) --> pl_integer(N), !. pl_constant(id(X)) --> identifier(X), {call(id(X,_)) }. %Not sure if I remember what it does but I think, the right most call I wrote to assure that the variable is already registered in the cache so that a value can later be retrieved from it pl_integer(X) --> [number(X)]. %the value on the right works together with a tokenizer library -> :- use_module(library(tokenize)). It's basically a token labled as a number. Same with the next line. identifier(X) --> [word(X)].
{ "language": "en", "url": "https://stackoverflow.com/questions/7543100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Standard for uploads into a server directory? I have a topic/question concerning your upload filename standards, if any, that you are using. Imagine you have an application that allows many types of documents to be uploaded to your server and placed into a directory. Perhaps the same document could even be uploaded twice. Usually, you have to make some kind of unique filename adjustment when saving the document. Assume it is saved in a directory, not saved directly into a database. Of course, the Meta Data would probably need to be saved into the database. Perhaps the typical PHP upload methods could be the application used; simple enough to do. Possible Filenaming Standard: 1.) Append the document filename with a unique id: image.png changed to image_20110924_ahd74vdjd3.png 2.) Perhaps use a UUID/GUID and store the actual file type (meta) in a database: 2dea72e0-a341-11e0-bdc3-721d3cd780fb 3.) Perhaps a combination: image_2dea72e0-a341-11e0-bdc3-721d3cd780fb.png Can you recommend a good standard approach? Thanks, Jeff A: I always just hash the file using md5() or sha1() and use that as a filename. E.g. 3059e384f1edbacc3a66e35d8a4b88e5.ext And I would save the original filename in the database may I ever need it. This will make the filename unique AND it makes sure you don't have the same file multiple times on your server (since they would have the same hash). EDIT As you can see I had some discussion with zerkms about my solution and he raised some valid points. I would always serve the file through PHP instead of letting user download them directly. This has some advantages: * *I would add records into the database if users upload a file. This would contain the user who uploaded the file, the original filename and tha hash of the file. *If a user wants to delete a file you just delete the record of the user with that file. *If no more users has the file after delete you can delete the file itself (or keep it anyway). *You should not keep the files somewhere in the document root, but rather somewhere else where it isn't accessible by the public and serve the file using PHP to the user. A disadvantage as zerkms has pointed out is that serving files through PHP is more resource consuming, although I find the advantages to be worth the extra resources. Another thing zerkms has pointed out is that the extension isn't really needed when saving the file as hash (since it already is in the database), but I always like to know what kind of files are in the directory by simply doing a ls -la for example. However again it isn't really necessarily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get the content of a dt element using jquery? I'm trying to get the content of the dt element using jquery. var test_name = $('dt').text(); alert(test_name); <dt> cycle_1 </dt> This is not working. What I'm doing wrong? Meaning the alert message does not display. A: <script type="text/javascript"> $(function() { var test_name = $('dt').text(); alert(test_name); }); </script> <dt> cycle_1 </dt> You need the code to run after page loaded and all jQuery stuff. So, you use $document.ready(/* some function containing your code */) for this. The shortcut for this is $(/* function */), then you pass your code in anonymous function (don't have to name it). A: Are you sure you are loading the jQuery library properly? Are you using $(document).ready(function () { .. });? Here is a jsFiddle of it working: jsFiddle demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7543110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What effect does changing the process priority have in Windows? If you go into Task Manager, right click a process, and set priority to Realtime, it often stops program crashes, or makes them run faster. In a programming context, what does this do? A: It calls SetPriorityClass(). Every thread has a base priority level determined by the thread's priority value and the priority class of its process. The system uses the base priority level of all executable threads to determine which thread gets the next slice of CPU time. The SetThreadPriority function enables setting the base priority level of a thread relative to the priority class of its process. For more information, see Scheduling Priorities. A: It tells the widows scheduler to be more or less greedy when allocating execution time slices to your process. Realtime execution makes it never yield execution (not even to drivers, according to MSDN), which may cause stalls in your app if it waits on external events but has no yielding of its own(like Sleep, SwitchToThread or WaitFor[Single|Multiple]Objects), as such using realtime should be avoided unless you know that the application will handle it correctly. A: It works by changing the weight given to this process in the OS task scheduler. Your CPU can only execute one instruction at a time (to put it very, very simply) and the OS's job is to keep swapping instructions from each running process. By raising or lowering the priority, you're affecting how much time it's allotted in the CPU relative to other applications currently being multi-tasked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Switch Background Image with jQuery animate When the user hovers over a div I have the background image change using the code below $(document).ready(function(){ $("#f1_container2").hover(function(){ $(".photobg").fadeIn( 800); }, function(){ $(".photobg").fadeOut(800); }); }); That works fine but I want the background image to change again (in say, 2 seconds) if the user is still hovering over that div. I tried the code below. $(document).ready(function(){ $("#f1_container2").hover(function(){ $(".photobg").delay(2000).animate({"background":"#000 url(space-image.png) center center fixed no-repeat"}, 0); }), }); Is that wrong...or should I use something like a delayed fading in of a new background div with a different background. A: $(document).ready(function(){ var imgSrc = "space-image.png"; $("#f1_container2").hover(function(){ setInterval($(".photobg").fadeOut('2000', function(){$(".phtobg").css("background-image", "url(" + imgSrc + ")"); }).fadeIn(), 1000);}); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7543122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why does nmap show that my tcp server is not listening on the port it should be? I intend to build on this code, found here However, I notice I can telnet to this server on the local host. Can't from another computer. I did a quick nmap scan, which reported that nothing was listening on the port I had selected. For purposes of troubleshooting, I had shut down my firewall, so I've ruled that out as a possible problem. Clues from haskell windows programmers would be appreciated. A: It seems that the socket got bind to localhost (127.0.0.1), thats why you are not able to connect it from other machine and it only connect from local machine. Try to use Bind API to first create the socket and then bind the socket to "Any address" which binds the socket to every interface available on local machine. A: This is for future new haskellers. I based my code on this example. I made improvements based on this reddit thread, and suggestions made above. The import statements are still sloppy, but fixing them is left as the proverbial "exercise for the reader". I invite any additional suggestions leading to improvements. import Network.Socket import Control.Monad import Network import System.Environment (getArgs) import System.IO import Control.Concurrent (forkIO) main :: IO () main = withSocketsDo $ do [portStr] <- getArgs sock <- socket AF_INET Stream defaultProtocol let port = fromIntegral (read portStr :: Int) socketAddress = SockAddrInet port 0000 bindSocket sock socketAddress listen sock 1 putStrLn $ "Listening on " ++ (show port) sockHandler sock sockHandler :: Socket -> IO () sockHandler sock' = forever $ do (sock, _) <- Network.Socket.accept sock' handle <- socketToHandle sock ReadWriteMode hSetBuffering handle NoBuffering forkIO $ commandProcessor handle commandProcessor :: Handle -> IO () commandProcessor handle = forever $ do line <- hGetLine handle let (cmd:arg) = words line case cmd of "echo" -> echoCommand handle arg "add" -> addCommand handle arg _ -> do hPutStrLn handle "Unknown command" echoCommand :: Handle -> [String] -> IO () echoCommand handle arg = do hPutStrLn handle (unwords arg) addCommand :: Handle -> [String] -> IO () addCommand handle [x,y] = do hPutStrLn handle $ show $ read x + read y addCommand handle _ = do hPutStrLn handle "usage: add Int Int" A: I usually go with netstat -an | grep LISTEN If you see the port listed, something is listening. I can't remember offhand what the lsof command is for sockets and Google isn't giving up the goods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing an object from the duplicate ArrayList only I've copied an ArrayList over as so: MyList2 = MyList1; In an attempt to load MyList2's objects with the ones which MyList1 has. Now as I iterate through MyList2, I it.remove() some objects, but this is causing a concurrent modification exception elsewhere on the parent iteration through MyList1. I think when i it.remove() it's actually removing it from the original ArrayList as well, how do remove it only from MyList2? Thanks. A: Your problem there is that you haven´t created a copy of the ArrayList, there are two references to the same object. If you want to copy the list, then you could do Collections.copy(MyList2,MyList1); or MyList2 = new ArrayList(MyList1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7543131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Efficient Methods of Rapidly Redrawing a Map (Java / JPanel) I'm currently working on a simple 2D top-down shooter in which you maneuver your character around a map. The graphics are still very much in the "testing" phase (solid colors and rectangles). The drawing process is as follows: * *I have the map (this is basically just walls or free space) stored as an integer array which is then looped through and painted onto my JPanel. *Once the map is drawn, I go through each "entity" on the map (powerups, other characters) and place them. *Finally, I draw the user's character I experimented with different methods, and finally decided that the user's character would stay in the center of the screen with the map moving around it. Currently, it works but it seems slow. I only have 4 walls, 2 entities, and the user's character being drawn and it's at 90FPS, spiking around 60-70 quite often. This would be acceptable if the game were finished, however I still have fancier graphics, many more entities, walls, bullets, etc. to be rendered onto the map. I've tried increasing the speed of my gameLoop, which can get it as high as 230 FPS, but even then when I move into areas with entities or walls it spikes down to 50-70. I've tried limiting what is drawn to only what is visible but the results were overall negligible and even negative. The current paintComponent() method looks something like this: public void painComponent(Graphics g) { for(int x = 0; x < Map.size.getWidth() ; x++) { for(int y = 0; y < Map.size.getHeight(); y++) { if(mapArray[y][x] == WALL) { g.setColor(Color.BLACK); g.fillRect(x, y, wallSize, wallSize); } } } for(int i = 0; i < map.countEntities(); i++) { Entity obj = map.getEntity(i); g.setColor(Color.WHITE); g.fillRect(obj.getCoords().x, obj.getCoords().y, obj.getSize().width, obj.getSize().height); } Robot bot = map.getPlayerBot(); g.setColor(Color.BLACK); g.fillRect(bot.getCoords().x, bot.getCoords().y, bot.getSize().width, bot.getSize().height); } Do any of you gurus out there have any tips to speed this up a bit? A: Beyond the answers mentioned in the following links: Java 2D Drawing Optimal Performance, Java2D Performance Issues, Java 2D game graphics and How to display many SVGs in Java with high performance A common and simple trick to improve 2D performance is to draw all the static objects ('background') into a buffered image, then when drawing the next image you just offset the pixels of your background image from the previous screen accordingly, then you need only draw the pixels around at most two edges of the screen rather than the entire screen, this only really matters when you're drawing a lot of image layers to the screen. Beyond all of that make sure you have double buffering enabled so that the drawing doesn't try and draw to the actual screen while you're still drawing the next image. A: Seph's answer was taken into consideration and implemented, but it did not increase the speed. Apparently, the image being drawn was not the problem at all. The problem was the timer that I was using to call the update methods. I was using an instance of the Timer class which seems to be very unreliable, especially at small intervals such as these. Upon removing the timer and calling my update methods based on the system clock, I was able to reach and maintain incredibly high FPS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Android SDK Wall Stream I am developing an application for a client who wishes to display their Facebook wall posts in the application. The Facebook SDK examples do a wonderful job explaining how to allow users to sign in, but this is not the functionality I desire. I only wish to stream information from a single profile for all application instances without any users having to sign in. If anyone has done anything similar, I would appreciate your suggestions. I will gladly provide any additional details. A: One option would be to embed one of the social plugins inside a web view. Otherwise, you could embed an application token inside the application and then make a graph api call to /pageid/feed and use the json result to show the feed entries. A: Your client can also create a page which is public and then just get its feed simply via RSS, no need to sign-in and no need for access token in this case. Url for RSS feed should be: https://www.facebook.com/feeds/page.php?id=PAGE_ID&format=rss20 hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7543139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .htaccess cache static content (unless modified)? Was wondering is this possible in .htaccess? I'm currently caching .js, .css and all image files via PHP (and providing the cached only if the file has not been modified by checking the filemtime()). However someone suggested it's possible via .htaccess and much faster, so was hoping maybe someone can shed some light...I've looked around and found various snippets but none which cover what I'm after. A: If you've got mod_expires installed on your apache server you can put something like this in your .htaccess file. This example is PHP orientated (actually grabbed from the Drupal 7 .htaccess file) but should serve as a good starting point. FileETag MTime Size <IfModule mod_expires.c> # Enable expirations. ExpiresActive On # Cache all files for 2 weeks after access (A). ExpiresDefault A1209600 <FilesMatch \.php$> # Do not allow PHP scripts to be cached unless they explicitly send cache # headers themselves. Otherwise all scripts would have to overwrite the # headers set by mod_expires if they want another caching behavior. ExpiresActive Off </FilesMatch> </IfModule>
{ "language": "en", "url": "https://stackoverflow.com/questions/7543142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Google App Engine (Java) Datastore Statistics API causes error I'm trying to implement Google App Engine's default Datastore Statistics API example: http://code.google.com/appengine/docs/java/datastore/stats.html import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Query; // ... DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity globalStat = datastore.prepare(new Query("__Stat_Total__")).asSingleEntity(); Long totalBytes = (Long) globalStat.getProperty("bytes"); // NullPointerException happens here... Long totalEntities = (Long) globalStat.getProperty("count"); I get a java.lang.NullPointerException when trying to access the globalStat object properties. I'm testing locally, does this API only work in production or am I missing something? Thanks A: If you look at the javadoc for the DatastoreService class, it doesn't look like there's a prepare method. I believe you are supposed to just use the get and put methods, where the get methods parameters would be the "key" for what you're trying to get, and the put method's parameter would just be the entity you created's object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does "each" function work in Ruby (and therefor Rails)? In the book I'm reading to learn Rails (RailsSpace) , the author creates two functions (below) to turn all caps city names like LOS ANGELES into Los Angeles. There's something I don't get about the first function, below, however. Namely, where does "word" come from? I understand that "word" is a local/block variable that disappears after the function has been completed, but what is being passed into/assigned to "word." IN other words, what is being split? I would have expected there to have been some kind of argument taking an array or hash passed into this function...and then the "each" function run over that.. def capitalize_each space = " " split(space).each{ |word| word.capitalize! }.join(space) end # Capitalize each word in place. def capitalize_each! replace capitalize_each end end A: Let's break this up. split(space) turns the string into a list of would-be words. (Actually, if the string has two spaces in a row, the list will have an empty string in it. but that doesn't matter for this purpose.) I assume this is an instance method in String; otherwise, split wouldn't be defined. .each { |word| word.capitalize! } .each takes each thing in the list (returned by split), and runs the following block on it, passing the thing as an arg to the block. The |word| says that this block is going to call the arg "word". So effectively, what this does is capitalize each word in the string (and each blank string and lonely bit of punctuation too, but again, that's not important -- capitalization doesn't change characters that have no concept of case). .join(space) glues the words back together, reinserting the space that was used to separate them before. The string it returns is the return value of the function as well. A: The string is being split by spaces, i.e. into words. So the 'each' iterator goes through all the words, one by one, each time the word is in the 'word' object. So then for that object (word) it uses the capitalize function for it. Finally it all gets joined back together With Spaces. So The End Result is Capitalized. A: At first I thought that the method was incomplete because of the absence of self at the beginning but it seems that even without it split is being called over the string given, space would simply be a default separator. This is how the method could look with explicit self. class String def capitalize_each(separator = ' ') self.split(separator).each{|word| word.capitalize!}.join(separator) end end puts "LOS ANGELES".capitalize_each #=> Los Angeles puts "LOS_ANGELES".capitalize_each('_') #=> Los_Angeles A: These methods are meant to be defined in the String class, so what is being split is whatever string you are calling the capitalize_each method on. Some example usage (and a slightly better implementation): class String def capitalize_each split(/\s+/).each{ |word| word.capitalize! }.join " " end def capitalize_each! replace capitalize_each end end puts "hi, i'm a sentence".capitalize_each #=> Hi, I'm A Sentence A: Think of |word| word.capitalize! as a function whch you're passing into the each method. The function has one argument (word) and simply evaluates .capitalize! on it. Now what the each method is doing is taking each item in split(space) and evaluating your function on it. So: "abcd".each{|x| print x} will evaluate, in order, print "a", print "b", print "c". http://www.ruby-doc.org/core/classes/Array.html#M000231 To demystify this behavior a bit, it helps to understand exactly what it means to "take each item in __". Basically, any object which is enumerable can be .eached in this way. A: If you're referring to how it gets into your block in the first place, it's yielded into the block. #split returns an Array, and it's #each method is doing something along the lines of: for object in stored_objects yield object end A: This works, but if you want to turn one array into another array, it's idiomatically better to use map instead of each, like this: words.map{|word|word.capitalize} (Without the trailing !, capitalize makes a new string instead of modifying the old string, and map collects those new strings into a new array. In contrast, each returns the old array.) Or, following gunn's lead: class String def capitalize_each self.split(/\s/).map{|word|word.capitalize}.join(' ') end end "foo bar baz".capitalize_each #=> "Foo Bar Baz" by default, split splits on strings of spaces, but by passing a regular expression it matches each individual space characters even if they're in a row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: matching double quote in preg_match I want to match the pattern below and obtain the word target. INPUT TYPE="HIDDEN" NAME="TITLE" VALUE="target "> I try this but in vain. preg_match('@(?:<INPUT TYPE="HIDDEN" NAME="TITLE" VALUE=")(.*)(?:">)@',$data,$matches); I think the problem is because of double quote I also try \" but still fail... A: It fails simply because you have a double space in your pattern in here (marked with _ ): INPUT TYPE="HIDDEN"__NAME="TITLE" Remove one space there and it works, anyway here would be my attempt from scratch, case insensitive and either with " or ' though I'm not sure if it's part of what you want that name has to be title in which case I'd have to edit it a bit. <?php $data = '<input type="hidden" name="title" value="target">'; preg_match('/<input[^>]+value=[\'"](\w*)[\'"][^>]*>/i',$data,$matches); echo $matches[1]; //=> target ?> A: Try this: preg_match('@<INPUT TYPE="HIDDEN" NAME="TITLE" VALUE="([^"]*)">@', $data, $matches); A: You're close... You need to match usng (). It looks like you've got an extra ) preg_match('@<INPUT TYPE="HIDDEN" NAME="TITLE" VALUE="([^"]*)">@',$data,$matches); [^"] - any character other than " ( ) - matching part
{ "language": "en", "url": "https://stackoverflow.com/questions/7543150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how do i call a webservice using phonegap for android How do I make a webservice call from my phonegap app? I found two javascript libraries one from IBM and another IvanWebService http://wiki.phonegap.com/w/page/43725416/SOAP%20Web%20Service that allow you to make such calls but i couldnt get them to run any of my webservices. I am passing in a wsdl link as the service link and i have updated the envelope parameters, still nothing. A: If it were me, I would use jQuery. http://www.bennadel.com/blog/1853-Posting-XML-SOAP-Requests-With-jQuery.htm http://openlandscape.net/2009/09/25/call-soap-xm-web-services-with-jquery-ajax/ http://weblogs.asp.net/jan/archive/2009/04/09/calling-the-sharepoint-web-services-with-jquery.aspx A: <head> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" /> <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script> <script type="text/javascript"> $(function() { $("#requestXML").click(function() { $.ajax({ type: "POST", url: "http://YOURSITE/script.php", data: "{}", cache: false, dataType: "xml", success: onSuccess }); }); $("#resultLog").ajaxError(function(event, request, settings, exception) { $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status); }); function onSuccess(data) { alert(data); } }); </script> </head> Button to call the above method: <input id="requestXML" type="button" value="Request XML" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7543153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: problem with asp.net redirection after login to admin page I built a simple site which has an open section and admin page, which you can get to, only after loging in. I implemented the default asp .net login control. The problem is, after successful login (the login page is called admin.aspx) I want to redirect to another page called groups.aspx (redirecting it by code - Response.Redirect("AdminTools\\Groups.aspx") ), but instead I get an error "The resource cannot be found.", which says that cannot find "login.aspx". The problem is I don't have a page called login.aspx in my site, and I can't manage to find the place where I can configure it. A: Always use ~ root operator. Response.Redirect("~/AdminTools/Groups.aspx") You can configure your own login url by setting the LoginUrl in web.config. <authentication mode="Forms"> <forms loginUrl="~/mylogin.aspx"> </forms> </authentication>
{ "language": "en", "url": "https://stackoverflow.com/questions/7543156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python script or applescript to get active pdf in foreground window, open in another application I'm interested in writing an OS X service and figured python would be the easiest way. Is it possible to write a script to get the active PDF in the foreground window of any app, and then open that file (or a copy) in a different app? What function calls would I need to get this done? Would it be easier to do this with AppleScript? Edit: Apparently, the application I want to send the PDF to (Papers 2) isn't AppleScriptable. Python it is, I guess.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is there a way to add current working directory/current git repo/branch in terminal prompt for Mac first time poster. This came up in conversation at work this week... Is there a way, when you connect to git remotely that you can get display current working directory/current git repo/branch in your terminal prompt? Apparently, there are linux/vim scripts that exist for linux users, and I'd like to add this sort of shell script to my profile. Currently I'm using some info from this page http://sos.blog-city.com/mac_os_x__bash_customize_your_terminal_prompt_a_little_color.htm to address some of this info locally. Thanks in advance. A: Get a copy of the git completion script. You can get this from git itself, or if you have a Linux box handy you could even just copy it from there (it'll probably be /etc/bash_completion.d/git). Then, arrange for this to get "sourced" by bash. You can do this by adding something like this to your .bashrc: . /usr/local/git-completion (assuming you named the file /usr/local/git-completion on your Mac). Finally, you'll want to adjust your prompt. Also in your .bashrc, add something like: export PS1='[\w$(__git_ps1 "|%s")]\$ ' Here's a blog post (not by me) that talks about this (and some other related stuff) in more detail: http://blog.bitfluent.com/post/27983389/git-utilities-you-cant-live-without A: OK, I experimented with this after you pointed me in the right direction, my google searches got more refined results. A lot of people point to the post you shared with me, like here: https://superuser.com/questions/31744/how-to-get-git-completion-bash-to-work-on-mac-os-x but I found some other jewels like these, which I didn't use but were informative: jeetworks.org/node/10 , jonmaddox.com/2008/03/13/show-your-git-branch-name-in-your-prompt/ . I needed some different guidance on installing git.completion because I use homebrew which I found here: https://github.com/bobthecow/git-flow-completion/wiki/Install-Bash-git-completion which covers several ways to install it. Finally, my bash/terminal has been a bit pokey so I upgraded to the latest bash with these instructions before I meshed with any of this: milkbox.net/brace_completion_snow_leopard_upgrading_bash/ and got some great speed improvement. I ended up having to rebuild my profile script very carefully but with trail and error (because of differences between Bash 3 and 4, and some syntax errors)- now it looks great, and does the job. Thanks again. Sorry about above the security restraints of the site, restrict me (since I'm a newb) to 2 links to combat spam. A: You just need 2 steps to do it. Step.1: Open ~/.bash_profile in your favorite editor and add the following content to the bottom. For me it is like emacs ~/.bash_profile Step.2: Add the following content to the bottom. function git_branch { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'} export PS1='\h:\w$(git_branch) \u\$' Done! P.s: If you want your terminal colorful, try the following content. export PS1 = '\[\e[1;39m\]\h:\w\[\e[01;39m\]$(git_branch) \[\e[01;39m\]$ \[\e[0m\]' A: Another option to get git branch/status info in your shell prompt is to use powerline-shell. You can see what this looks like in this screenshot: The magenta/green bar is the current branch name. Its color indicates whether the working directory is clean. There are also markers that appear when there are untracked files, or when there are commits to be pulled-from/pushed-to the upstream remote. Powerline-shell is compatible with bash, zsh, and fish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Close window as soon as it opens I am using the facebook dialog feed to allow the user to post a message to their wall. You must provide a redirect_url for the page to redirect to after it has submitted, I want on the page it redirects to to have some code which simply closes the windows. I tried using <html><head><title>Close</title></head><body onload="window.close();"></body></html> and <html><head><title>Close</title></head><body onload="self.close();"></body></html> but to no effect. (note that my testing is simply me opening a new tab with this url, could that be the issue?) A: You can only close windows with javascript if they were opened with javascript. Otherwise, try looking at this question: How can I close a browser window without receiving the "Do you want to close this window" prompt?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Kohana : how to get the sub-request's (HMVC) cookie changes I use the following code to perform sub-request in HMVC structure: A request to "page1" will make a sub-request to "page2" by the following code: $request = Request::factory('/page2') ->method(Request::POST) ->post($postData) ->execute(); The execution in "page2" will add / change the value of a cookies item by setcookie('new_var', $newValue); Now I need to capture the new value of the cookie "new_var" in "Page1". So how can I do that? PS: Due to some limitations, I have to set the 'new_var' in cookie, so putting it to session is not an answer. ==========update ============= As suggested by zerkms, I did something like this: $response = Request::factory('/page2') ->method(Request::POST) ->post($postData); //before error_log(print_r($response->cookie(), TRUE)); $response->execute(); //after error_log(print_r($response->cookie(), TRUE)); the result of the "before" and "after" log entries are both empty array. :( A: In kohana you'd better used Response::cookie() method. In this case you can use this method for both retrieving and setting cookies (even in the same request)
{ "language": "en", "url": "https://stackoverflow.com/questions/7543162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I insert a variable result into a string in C++ I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like, NSString *name = [NSString stringWithFormatting:@"Hello, %@", [nameField stringValue]]; [nameField setStringValue:name]; How would I go about doing something like this with C++? Thanks for the help A: I assume we're talking about Qt's QString class here. In this case, you can use the arg method: int i; // current file's number long total; // number of files to process QString fileName; // current file's name QString status = QString("Processing file %1 of %2: %3") .arg(i).arg(total).arg(fileName); See the QString documentation for more details about the many overloads of the arg method. A: You don´t mention what type your string is. If you are using the standard library then it would be something along the lines of std::string name = "Hello, " + nameField; That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this: std::ostringstream stream; stream << "Hello, " << nameField; stream << ", here is an int " << 7; std::string text = stream.str(); Qt probably has its own string types, which should work in a similar fashion. A: I would use a stringstream but I'm not 100% sure how that fits into your NSString case... stringstream ss (stringstream::in); ss << "hello my name is " << nameField; I think QString has some nifty helpers that might do the same thing... QString hello("hello "); QString message = hello % nameField; A: You could use QString::sprintf. I haven't found a good example of it's use yet, though. (If someone else finds one, feel free to edit it in to this answer). You might be interested in seeing information about the difference between QString::sprintf and QString::arg.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to generate with ruby interpolation? I have a need to generate an html id using some .erb code. Specifically, I want to use the row and column index of a cell in a rectangular array (made out of a table of cells). I have a method cell.web_id, which constructs a string thus: "r#{row_index}_c#{column_index}", so that cell(2,3) would yield "r2_c3". So far, so good. Now for the odd part. I haven't figured out how to wrap the web_id result in double quotes required to properly define the attribute. No matter what I try, I always get: <span class="cell" id=&quot;r1_c1&quot; > This form doesn't work. So, how can I get this form: <span class="cell" id="r2_c3" > I know this is easy if you know the proper incantation, but I don't have it. A: Try this: <span class="cell" id="<%="r#{row_index}_c#{column_index}"%>" > OR <span class="cell" id="r<%=row_index%>_c<%=column_index%>" > OR <span class="cell" id="<%=foo_span_id(row_index, column_index)%>" > Where foo_span_id is a custom helper method A: "\"r#{row_index}_c#{column_index}\"".html_safe (apidock docs) (mostly useless, but included for completeness :) A: Instead double quotes, why don't you try single quotes? (that is normally what I do in situations like this). So your code will be "'r#{row_index}_c#{column_index}'" and your HTML will also need to be slightly changed to single quotes <span class='cell' id='r2_c3'; >
{ "language": "en", "url": "https://stackoverflow.com/questions/7543166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getOwnerActivity returns null in custom dialog I write a custom dialog and try to get some data from its parent activity, but I always get null when I call getOwnerActivity, could anyone tell me why this happen? Why I can show the data in the DemoDialog while failed to show data from TestDialogActivity? Many thanks in advance. DialogTestActivity public class DialogTestActivity extends Activity { List<String> data = new ArrayList<String>(); Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button)findViewById(R.id.button); button.setOnClickListener(new OnClickListener(){ public void onClick(View v) { showDialog(0); } }); } public List<String> getData(){ data.add("one"); data.add("two"); data.add("three"); return data; } public Dialog onCreateDialog(int id){ return new DemoDialog(this); } } DemoDialog public class DemoDialog extends Dialog { Context context; public DemoDialog(Context context) { super(context); setContentView(R.layout.dialog); this.context = context; setTitle("Delete City"); ListView list = (ListView)findViewById(R.id.list); ArrayAdapter<String> aa = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, ((DialogTestActivity)getOwnerActivity()).getData()); // ArrayAdapter<String> aa = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, getData()); list.setAdapter(aa); list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } private List<String> getData(){ List<String> data = new ArrayList<String>(); data.add("1"); data.add("2"); return data; } } A: If you think about the situation, you will understand why. When you call new DemoDialog(this), you execute all the code in the constructor. After that, you return it from onCreateDialog and Android does its magic. If you try to get owner from the constructor, Android hasn't hooked it yet, so you have no owner yet. So you can do either of these: public class DemoDialog extends Dialog { public DemoDialog(Context context) { super(context); // chances of context not being an activity is very low, but better to check. Activity owner = (context instanceof Activity) ? (Activity)context : null; if (owner != null) { // owner activity is defined here } } public void onAttachedToWindow() { super.onAttachedToWindow(); // getOwnerActivity() should be defined here if called via showDialog(), so do the related init here Activity owner = getOwnerActivity(); if (owner != null) { // owner activity defined here } } } Note that the second method is preferred because A: I tried to use getOwnerActivity() method in all possible methods of my custom Dialog. It always returns null (Android 2.3). Then I checked its source code and the activity it returns is set only in setOwnerActivity(Activity activity) which is not called anywhere. So if you want getOwnerActivity() to return value different than null, you have to do this: public MyCustomDialog(Context context) { super(context); if (context instanceof Activity) { setOwnerActivity((Activity) context); } } A: You can extends your custom dialog from AppCompatDialog and access to activity by this code: public static Activity scanForActivity(Context context) { if (context == null) return null; else if (context instanceof Activity) return (Activity) context; else if (context instanceof ContextWrapper) return scanForActivity(((ContextWrapper) context).getBaseContext()); return null; } A: This, below, worked for me. private Activity activity; public MyCustomDialog(Activity activity) { super(activity); this.activity = activity; } Then I use activity instead of getOwnerActivity().
{ "language": "en", "url": "https://stackoverflow.com/questions/7543167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: how to perform a post through chrome extention? How can I perform a post through the chrome extention, lets say I want to send the current tab page title to a webpage A: You can do POST XHRs from chrome extensions to any URL, as long as you have host permissions defined in your manifest. See these docs. A: In a chrome extension the best way to try and do what i think you want is via a content script see documentation a word of warning however pinging your server with a POST request every time someone with your extension installed opens a web page is going to be extremely heavy going on your servers especially if you have a lot of installs. A possible solution is to use the content script to keep tally of the sites a user visits and save this data in a HTML5 database (wich chrome supports) then using background.html sending the data at given intervals in bulk with an AJAX request, this will significantly cut down the number of times your server is pinged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ado.Net - How to use connection pooling? .Net allows connection pooling which based on what I've read is simply by adding parameters to App.config The question is, am I suppose to do anything in my code to use the connection pool? In my code I open a connection every time data is needed and I close it as soon as I'm done. Am i suppose to do anything special to reuse connections? A: You don't need to do anything special as long as your connections use the same connection string. Use the connection, close it and will automatically return to the pool. From SQL Server connection pooling: Connections are pooled per process, per application domain, per connection string and when integrated security is used, per Windows identity. Connection strings must also be an exact match; keywords supplied in a different order for the same connection will be pooled separately. You can configure certain pool related options in the connection string itself: * *Pooling (enabled by default) *Connection Lifetime (or Load Balance Timeout) *Enlist *Max Pool Size *Min Pool Size A: The point is to not do anything to re-use connections :) If you store the connection and re-use it, the pool is defeated. A good pattern is to take advantage of IDisposable and using. For the ado.net connection classes, dispose calls close. If you do that, you can't go wrong. using (conn = new SqlConnection(...)) { // use the connection }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cannot find settings to change moderation options Ok- new to this today. Two major issues: First- I am setting up a FB comments box for each of the pages on my website. I have followed step by step and have created an app so I can mederate all of the comments at once rather than page by page. Problem is when I get to my app I am supposed to click on "settings", however I cannot find it. There is an "edit settings' but it does not take me to the box where I can choose either to make every post visible or to let me approve each comment, etc... it just takes me to a summary of my app where I can choose app display name, app namespace, etc. Here are the directions I have been given: Changing Moderation Settings Click on your app in the left column. Then click on Settings (it has two small gears beside it) in the top right corner of the tool to give you access to a few options... Second issue is that after creating my app and saving changes, I was supposed to click on "need to grant permissions" to create an access token and then see a pink box with the App ID/API Key and App Secret. After I saved the changes for my app. there was no "need to grant permissions" nor was there a pink box. The App Id and API key and App Secret show, but they are just at the top of the app- no pink box. Do I need to do something with permissions and create an access token? If so how? (I am not even sure what this is) A: Assuming the comments plugin is linked to the app correctly (which can be checked by running your URL through the URL Debugger, you can moderate the settings in two places: * *The Comment moderation tool *The Settings links, with the gears, displayed in the top right of an instance of the comments plugin itself You can see your current access token for an app you admin in many ways, but the easiest two places I can think of are: * *The Access token tool on the Facebook Developer site *By authorising your app in the Graph API Explorer
{ "language": "en", "url": "https://stackoverflow.com/questions/7543188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSNumberFormatter Won't Accept Zeros After a Decimal Point Similar questions have been asked but I find that the offered solutions don't work with the latest iOS SDK or are not exactly applicable in this particular case. I call a method using an NSNotification, that formats a number with grouping symbols in a UILabel as it is entered using digits from button input. It works great for integers and decimals too--so long as no zeros are entered after a decimal point. For example if 2000 is entered, it is displayed as 2,000 as it is entered just fine. If 23.345 is entered, that displays just fine too. Any calculations done on these numbers come out correct. But it is impossible to enter 0.0001 or 0.2340007! It just won't take and append any zeros after the decimal point. I got the original code idea from another post here at stackoverflow: NSString *currentText = [display_ text]; currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@""]; currentText = [currentText stringByReplacingOccurrencesOfString:@"." withString:@"."]; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setGroupingSeparator:@","]; [formatter setDecimalSeparator:@"."]; [formatter setMaximumFractionDigits:10]; NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:currentText]; NSString *finalText = [formatter stringFromNumber:number]; NSString *lastChar = [currentText substringFromIndex:[currentText length] - 1]; if ([lastChar isEqualToString:@"."]) { finalText = [finalText stringByAppendingString:@"."]; } [display_ setText: finalText]; [formatter release]; No amount of finagling (that I have tried) with the parameters of the formatter will allow the entry of zeros after the decimal point. A: Why do you replace "." with "."? What do you see in debugger after number is instantiated? I have never worked with NSDecimalNumber but struggled already with doubles some time ago. I would suggest breaking down the problem. Instantiate number with a hard-coded value, format it and write it to log file. If this doesn't work try my code below, it works fine in my app with double values. I am using German locale settings but that shouldn't be the point. NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init]; [formatter setAllowsFloats:TRUE]; [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setMinimumSignificantDigits:20]; [formatter setMaximumSignificantDigits:20]; [formatter setMinimumFractionDigits:0]; [formatter setMaximumFractionDigits:5]; NSLocale* locale = [NSLocale currentLocale]; [formatter setLocale:locale]; NSNumber* number = [NSNumber numberWithDouble:1000.0123f]; myTextField.text = [formatter stringFromNumber:number]; If your code does work already, * *check that there is no O instead of zero *Remove this "." replacement mentioned above *I found out that setting a locale explicitly solved some problems (it's too long ago to remember details but you might give it a try) *Replace NSDecimalNumber by NSNumber and feed it with double values *Check your XIB file and ensure that your text field does not perform any other formatting
{ "language": "en", "url": "https://stackoverflow.com/questions/7543189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting margin and padding for in css? I can't seem to get the CSS to modify my radio buttons. Their default settings aren't symmetrical so my layout looks a little ugly. I am generating a bunch of these forms with javascript. I do not want to inject large amounts of inline style='margin:0px padding:0px' stuff but it's the only way I can get it to work. A: Using a CSS selector, you can probably do this: input[type=radio] { margin: 0; padding: 0; } Note however that older versions of IE don't support attribute selectors. For those, you can do: <div class="radios"> ...input tags... </div> and .radios input { margin: 0; padding: 0; } to catch the oldies. This would cut down the amount of presentational code while maintaining compatibility with ie6.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python CGI - Change data based on user time zone I have a Python CGI program which prints datetime values. The timestamps are all formatted to the server's time which is way off from the local time of some of the users. How can I format it automatically for all users based on their time zone? Here is one of the formatted string: 2011-09-25 02:04:54 That string was created by using a datetime.datetime object. -Sunjay03 A: You will have to have a way to find the timezone of the user. One way to do this is by having them set it in a preference page, and storing it in the database, and looking it up when you render the page. Another way is to have the browser include its current time in the request, so that you can adjust your times. One you know the user's offset from your server time, you can use timedelta methods to adjust the datetime object. A: You can use ip location service http://www.geobytes.com/iplocator.htm to get the timezone based on IP. you can get IP from REMOTE_ADDR on the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to put two Lambda expressions inside a single query? I was wondering if there is an easy way to place two Lambda expressions in a single (Linq/Where) query? For example, I currently call a method with something like the following: string testing = "blablabla"; if(testing == "" || testing == null) I have tried a few combinations such as: testing.Where(x => x == ("") || x=> x == null); But the above doesn't work. I know I can set up a method that returns a predicate/bool, but, at the moment, I am interested in Lambdas and was just wondering how to achieve this. Do I need to chain multiple Where methods, or is there a way to achieve multiple Lambdas? (p.s. I know about IsNullOrEmpty, this is just the first example I could think of!) A: You can always combine them to a single lambda. testing.Where(x => x == null || x == ("") ); A: If you're looking for a general way to combine query conditions in arbitrary ways, you can use expression trees: http://msdn.microsoft.com/en-us/library/bb882637.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7543204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ubuntu 8.04 Hardy and node.js upstart script I am trying to write an upstart script for my ubuntu machine, which is version 8.04 "Hardy". I have followed the instructions on this site: upstart for node.js but it seems like these instructions are for a current version of ubuntu. I noticed that the /etc/init directory does not exist on my machine, first I tried putting the script in the /etc/init.d directory and then I created the /etc/init dir and placed it there. I will post my upstart script below (which is basically the same as from the website above with some path changes), but when I run start jobname, I just get an error "start: Unknown job: jobname". So then I changed the script around to a slimmed down version, posted below, and still I get the same result. For now, I am using the 'nohup' command to run my node server but I would like a more permanent solution. Please, any help? SCRIPT 1: description "node.js chat server" author "iandev ith3" # used to be: start on startup # until we found some mounts weren't ready yet while booting: start on started mountall stop on shutdown # Automatically Respawn: respawn respawn limit 99 5 script # Not sure why $HOME is needed, but we found that it is: export HOME="/root" exec /root/local/node/bin/node /home/ian/chat.js >> /var/log/node.log 2>&1 end script post-start script # optionally put a script here that will notifiy you node has (re)started # /root/bin/hoptoad.sh "node.js has started!" end script SCRIPT 2: description "node.js chat server" author "iandev ith3" script exec /root/local/node/bin/node /home/ian/chat.js >> /var/log/node.log 2>&1 end script A: Just use Forever. https://github.com/indexzero/forever A: From looking at the website you provided I'd say that the /etc/init was just a typo and it should be /etc/init.d/. Some things you may want to check: * *executable flag on your scripts. With most versions of Ubuntu executable files show up green when running 'ls' from the command line. If you want to check if your file is executable run 'ls -l /etc/init.d/YOUR_SCRIPT' from the command line. You will see something like this: -rwxr-xr-x 1 root root 1342 2010-09-16 10:13 YOUR_SCRIPT The x's mean that it is executable. To set the executable flag if it is not set, run chmod u+x YOUR_SCRIPT *I'm pretty sure for older versions of ubuntu you need to have the script in /etc/rc.d/rc3.d or /etc/rc3.d. What linux does is run through rc0.d to rc5.d and execute every script in there. From what it looks like, ubuntu is moving away from this to something simpler so if you have rc directories you may need to edit your script a little. Anyway I think i'm getting a little over complicated here. Check your executable flag and if you have rc directories and we'll move on from there. A: May not be the best thing to start a process with sudo, but here's what I have setup on my local pc: #!upstart description "node.js server" author "alessio" start on startup stop on shutdown script export HOME="/ubuntu" exec sudo -u ubuntu /usr/bin/node /home/ubuntu/www/test.js 2>&1 >> /var/log/node.log end script Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get data from a forum thread? I'm starting in Curl / php and I'm really enjoying what it can do. Although, I'm blocked for several days on something and I really need help. There are some peculiar datas I need to grab and treat with another script thanks to a txt file. The datas are proxies posted on my forum by a member which agreed to be published in a external website related to the forum. The proxies are under this form 107.2.178.129:47535<br/>173.174.251.89:18785<br/>173.48.224.237:1807<br/>and so on ... I would need them to be placed in a text file with one proxy per line. Here is what I have so far <?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://www.external-site.com/Members/Login.php'); curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2'); curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); $store = curl_exec ($ch); curl_setopt($ch, CURLOPT_URL, 'http://www.external-site.com/index.cgi?action=display&thread=26'); $content = curl_exec ($ch); curl_close ($ch); ?> After that I'm stuck. A: So you've gotten the forum post text? Assuming $content is valid: file_put_contents('proxies.txt', implode('\n', explode('<br/>', $content))); Use \n on Linux, or \r\n on Windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically create named classes in Coffeescript without using eval? I want to be able to write: generate 'Cat', 'meow' and define the generate function in such a way that it produces: class Cat meow: -> @.__proto__.constructor.name + ' says meow.' so that I can write: garfield = new Cat garfield.meow() # "Cat says meow" A: If you don't mind polluting your global namespace, I actually got this snippet running in the 'try coffeescript' runner at the CoffeeScript site: root = exports ? window alert = alert or console.log gen = (clsname, val) -> root[clsname] = class meow: => "#{clsname} says #{val}" gen 'Cat', 'meow' g = new root.Cat alert g.meow() gen 'Dog', 'woff' d = new root.Dog alert d.meow() Not 100% what you asked for, but it's almost what you wanted, isn't it? Edit: Actually, the first script only worked in the browser, not the (Node.js-based) CLI, corrected the script. If you know you'll only live in the browser, you can loose root.Cat and only say Cat, but if you want Node.js and browser compat, you'll have to live with root.* Edit 2: It's generally a better idea to return the class from the generating function rather than magically putting it in a namespace. It's also possible to make the method names dynamic. With some inspiration from @Loren, the asker (notice how it doesn't need to refer the global object anymore): alert = alert or console.log gen = (clsname, val) -> C = class C.prototype[val] = -> "#{clsname} says #{val}" C Cat = gen 'Cat', 'meow' console.log Cat g = new Cat alert g.meow() Dog = gen 'Dog', 'woff' d = new Dog alert d.woff() A: If by "named class" you mean "a class with a named function," what you're asking for isn't possible—in CoffeeScript or JavaScript. Without eval, there's no way to create the equivalent of function FuncName() {...}. You can only use the __proto__.constructor.name property on functions defined with that syntax. The class syntax is the only way of creating named functions in CoffeeScript, for reasons explained in the FAQ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help needed in refining PHP search I am trying to create a php search engine which can refine search results based on time similar to google's search refine but with a select dropdown without a submit button. I am using sql server as database with pdo-sqlsrv driver. The regular search works great. I have problem only in passing value in time variable through select box and loading the page as soon as user selects the option. Any help would be great. Thanks A: Add <select name="foo" onchange="javascript:this.form.submit();"> A: In JavaScript , you can do something like... onchange="mysubmit()"
{ "language": "en", "url": "https://stackoverflow.com/questions/7543221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: How to put the value of a variable inside a new LI element? How do I put a variable name inside an li tag? For exmaple, var test_name = $('dt').text(); $('#test_div').html('<li> test_name </li>'); This is not working. What am I doing wrong here. It displays test_name not the value of test_name. A: You need to build a string containing your value: $('#test_div').html('<li>' + test_name + '</li>'); Note that this is an XSS hole; you need to escape the HTML. You can do that by building an element with jQuery: $('#test_div').html( $('<li></li>').text(test_name) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7543225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ‘Cannot modify header information’ at the very first line I'm getting this very weird error. I call it weird because the full error is Cannot modify header information - headers already sent by (output started at [...]/user.php:1) As you can see it says that the first line of the script prints something, therefore the header is already sent. The point is that the script is: <?php class User extends AppModel { And nothing more! Not even a space or anything else. I can't really understand what's wrong with it. Additional information The point is that the script works without any problem in my local webserver but not when I upload it to my hosting server. I ran a shell script on my whole folder (with all my script) too look for whitespace at the beginning or at the end of the pages, but nothing was found. A: In your code editor, save the file without BOM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++11 with Xcode on Mac OS X Snow Leopard I have project that is at times developed on Windows/Visual Studio 2010 and uses some C++11 features and I need to be able to develop/build on Mac OS X. When I tried to build the project with Xcode I got a lot of errors around new C++11 features and checked the gcc version to find it's pretty old (4.2). It looks like Apple is trying to force developers to pay an unnecessary upgrade to Lion by refusing to allow Xcode 4+ to be downloaded on any other version of Mac OS thus I'm left with Xcode 3.x. How can I continue to use C++11 on Snow Leopard? Is there a way I can do this and keep Xcode as an IDE? A: Update feb.25 2012: There are now a lot of features available for you to work with using the latest clang. Maybe you could target 10.6 if you use language features only. If you need library features, you will need 10.7. given the present (sept.24.2011) state of the Xcode toolset, it's easiest (IMO) to choose another ide or os if you need c++11 support. the fork of gcc xcode uses will never support these features. clang is pretty far behind wrt c++11 features (because its c++ implementation is still very new and other compilers have had a few extra years). therefore, the compilers xcode ships with do not presently support enough features for c++11 development, regardless of the version of osx you use. you can install a newer version of gcc and use another ide fairly easily. technically, you can also make a plugin for xcode 3 (not officially supported) which invokes another compiler (e.g. a more recent release of gcc). that route has been closed in xc4 (afaik). Update apparently, it's still available in Xc4; see idljarn's comment below. for many projects, it's easier to just use your mac to boot into linux or windows (or use virtualization). your final option is intel's compiler, which can be used in xcode and provides a decent amount of c++11 support -- try it with xcode before you buy to see if it fits your needs, plays well with xcode, and supports the c++11 features your team uses. lastly, i don't think they do this for your upgrade money. they really don't maintain xcode for multiple releases very well - they just expect you to stay with the latest and greatest unless you need backwards compatibility; you just stop upgrading in that case. they invested in and assisted development of clang after gcc's license changed. so yeah... osx has always been very far behind wrt c++11 support because they decided to switch to another (very young) compiler. if you wait for xcode to support c++11, you will have to wait for clang to support it, which can be quite some time. A: I just saw this now and I would like to update you on this. LLVM currently shipping with XCode is at version 3 (Source). This current version is very good with supporting C++11. Here is a link to what is supported: http://clang.llvm.org/cxx_status.html You can compare this with the current GCC support here: http://gcc.gnu.org/projects/cxx0x.html As you can see, Clang is currently not far behind, if it is at all, with features of the new standard being supported. The only thing that I see concerning is the lack of support for concurrency features, but that is the case for most C++11 compilers due to the nature of supporting it.So I hope that this answer is not too late and that you are not deterred. Go get the latest version of Xcode and fire away (If you have not done so already ;) )!
{ "language": "en", "url": "https://stackoverflow.com/questions/7543236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How To Parse Multipart HttpWebResponse I'm completely lost on how to parse this multipart httpresponse. This is the format that I receive: MIME-Version: 1.0RETS-Version: RETS/1.8RETS-Server: Interealty-RETS/1.5.247.0Transfer-Encoding: chunkedCache-Control: private,private, max-age=0Date: Sun, 25 Sep 2011 00:45:51 GMTSet-Cookie: ASP.NET_SessionId=jt11w155vitdtlnwt2p3l345; path=/; HttpOnly,RETS-Session-ID=jt11w155vitdtlnwt2p3l345; path=/Server: Microsoft-IIS/6.0X-AspNet-Version: 2.0.50727Content-Type: multipart/parallel; boundary=yz2C9C5D87FD6148a3986510BCACF917A82C9C5D87FD6148a3986510BCACF917A8ZY --simple boundaryContent-Type: image/jpegContent-ID: 123456Object-ID: 1<binary data> --simple boundaryContent-Type: image/jpegContent-ID: 123457Object-ID: 1<binary data> How can I isolate the different parts of the response? This is returning a bunch of images. What I need to do is convert the binary data into the image (which i can do) and save it to the disk in the format Content-ID + "-" + Object-ID + ".jpg". I know how to convert the bytes into the image, i just don't know how to isolate the bytes so i can convert it. Any help and example code would be much appreciated! A: I ended up using a library to parse the RETS (Real Estate Transaction Standard) responses. The library I used was called librets. A: I recommend you use a library like RestSharp. A: If you are trying to download real estate transactions using the RETS protocol, try using http://code.google.com/p/jrets/
{ "language": "en", "url": "https://stackoverflow.com/questions/7543237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: no-jk Equivalent in mod_proxy I've always used Apache + Tomcat via mod_jk. To tell Apache not to forward /recources to Tomcat, you just put this in vhosts: SetEnvIf Request_URI "/resources/*" no-jk How do you do the same thing with mod_proxy. If it matters, I'm using the bitnami tomcat stack and there is a tomcat.conf with: <Location /> ProxyPass ajp://localhost:8009/ </Location> Do I change that somehow? A: #<Location /> # ProxyPass ajp://localhost:8009/ #</Location> ProxyPass /resources ! ProxyPass / ajp://localhost:8009/
{ "language": "en", "url": "https://stackoverflow.com/questions/7543238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there such a thing as a SECURE client side password encryption? Client side encrption of user password->> I have searched for an answer to my question on this site but there is nothing specific to my question and was wondering if someone could shed some ligth. *THE QUESTION*** Would it be possible (and secure) if I was to encript a user password on the client side by using the user entered password on the login form as the passsword for the encrpted file, then send file to server side. The only way that this file can be decypted would be with an administrative password (second password) which only the server side knows meaning that not even the user is able to decypt it. As an example - say i encrpt a password using the user entered form password in winrar. the winrar file gets sent to the server. Now for the server to decrpt and get the password it needs to use its unique server side decypting password. Or perhaps, instead of using the user entered password to decrypt - get say Javascript to produce a once of random() password? I'm not that advanced in web development and only have loggic to go off and hope that somone who is can give me some pointers on the flaws of this approach? A: Unless you use HTTPS and SSL, this is inherently insecure, since an attacker can pre-emptively replace your Javascript with malicious Javascript that sends the user's password to an evil server, then does everything else normally. A: Using one password to encrypt and a different password to decrypt is called Public-key Cryptography (PKI) But if you do use it, then there is no need to send the encryption key to the server as a "public" key used to encrypt the data and only a "private" key can decrypt it. Implementing PKI in Javascript would be a big project. You might want to re-phrase your question, it is a bit confusing. A: You could store your password as a one way hash (ie MD5). Then on the client side, MD5 the password input and send that to the db.. A: See https://docs.djangoproject.com/en/dev/topics/signing/
{ "language": "en", "url": "https://stackoverflow.com/questions/7543239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: for each loop inside a if statement? I've been getting an "illegal start of expression" error when trying to compile this for loop inside a if statement in java. Does anyone have any idea why? if(letter.equals(" ") || letter == null ||for(String a: array){ letter.equals(a);}) A: Try if( letter == null || letter.equals(" ") || checkArray(array, letter)) { ... } boolean checkArray(String[] arryay, String letter) { for(String a: array) if(letter.equals(a)) return true; return false; } Note: checking letter for null after you have already called equals() does not make too much sense; i've reordered those. A: You cannot. Perhaps you should move the if statement into the for statement? As rfausak said, a for statement does not return a boolean. You should have made that an answer by the way. A: Well, that´s because you can not have a for loop within an if condition. It seems you want to see if the letter is within the array array; if so then you can do it with Apache commons-lang's ArrayUtils: ArrayUtils.contains( array, letter ); A: If you use a Set you could write: if ( (letter.equals(" ")) || (letter == null) || (a.contains(letter)) ) {} A: This wont work because a for doesn't evaluate to a boolean. For readabilities sake you should extract that to a method anyway, good examples appear in other answers. Other points, you should rejig your conditionals to not be susceptible to NullPointerExceptions if (letter == null || " ".equals(letter) || arrayContains(array, letter)) { //... } If you are able to add additional libraries, there are some nice apache commons libraries to make this work easier, namely StringUtils in commons-lang and CollectionUtils in commons-collections. You also may like to harden that input checking if it's possible to get Strings larger than one character, by using String#trim() after checking for null. Again, this would be a good candidate for an extracted method isBlank(String str).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS: Submit button looks smaller than text input and textarea I just noticed this strange rendering of a very simple form. Here's my markup/CSS: http://jsfiddle.net/a9PLM/ As you can see, text fields and the button share the same styles but their size is quite different. Why does this happen? Thanks! A: This is because of the box model being used is different for the <input type="submit"> and the <input type="text">/<textarea>. You can make the box models the same by specifying them with CSS: box-sizing: border-box; -moz-box-sizing: border-box; You can read more about box models here: http://www.quirksmode.org/css/box.html I edited your jsFiddle to show it working: jsFiddle demo A: I think this is a browser rendering issue... with buttons being displayed differently than text inputs. To fix, add this to your css form input[type="submit"]{ width:273px; } Example: http://jsfiddle.net/jasongennaro/a9PLM/1/ A: Padding on the text fields give it extra space on the sides. Set the padding of inputs and textareas to 0. A: The problem is that the form parts are generally not rendered like normal HTML elements, and styling them is always a bit hit-or-miss. I would attempt to avoid a case like this that requires exact sizing, but if you can't, then split the selectors like this: form textarea, form input[type=text] { width:250px; padding:10px; } form input[type=submit] { width: 270px } Note that I added 20 px (10 x 2) to the width to compensate for padding. A: I've used this CSS-only solution which works in IE, FF and Chrome. Basically, the idea is to manually force the height of input elements to values larger than standard boxes. Do this for both text and button: * *Set margins and padding to 0. *Set vertical-align to middle. *Use height/width to control text and button dimensions. Text height must be several pixels greater than font height (in order to override standard box dimensions). Height of button must be 2 pixels greater than text. Example: input { margin:0; padding:0; border:solid 1px #888; vertical-align:middle; height:30px; } input[type="submit"] { height:32px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Homework: "Exception in thread "main" java.lang.NullPointerException" Okay so I have a homework assignment. I thought I had everything good on it, and I am getting an "Exception in thread "main" java.lang.NullPointerException at HW3.main<HW3.java:18> That line is: tempMembers[i/4].setFirstName(args[i]); Now I am still pretty much a noob at programming, and everything up until this point I have done was in Eclipse. This program was to be created in a text editor and then compiled and ran at the command prompt. I do not know if maybe I am just inputting the arguments incorrectly or what not. So for this error my command prompt entry was java HW3 Bill Smith 2009 Football Jane Doe 2000 Tennis David Jones 1995 Baseball So is the error in my code or in my input? And if the error is in my code can you point me in the correct direction? Like I said command line arguments are completely new to me, and my class doesn't do examples of any of this, just talks about concepts. public class HW3 { public static void main(String[] args) throws Exception { if (args.length % 4 != 0) { throw new Exception( "First Name, Last Name, Year Inducted, Sport not entered correctly"); } HallOfFame hallOfFameList = new HallOfFame(); hallOfFameList.setNumberOfMembers(args.length / 4); HallOfFameMember[] tempMembers = new HallOfFameMember[args.length / 4]; for (int i = 0; i < args.length; i += 4) { tempMembers[i/4].setFirstName(args[i]); tempMembers[i/4].setLastName(args[i+1]); tempMembers[i/4].setYearInducted(Integer.parseInt(args[i+2])); tempMembers[i/4].setSport(args[i+3]); } hallOfFameList.setMembers(tempMembers); HallOfFameMember[] sortedMembers = null; hallOfFameList.sortMembers(sortedMembers); HallOfFame.printReport(sortedMembers); } } public class HallOfFameMember implements Comparable<HallOfFameMember> { private String firstName; private String lastName; private String sport; private int yearInducted; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getSport() { return sport; } public void setSport(String sport) { this.sport = sport; } public int getYearInducted() { return yearInducted; } public void setYearInducted(int yearInducted) { this.yearInducted = yearInducted; } @Override public int compareTo(HallOfFameMember o) { return this.getYearInducted() - o.getYearInducted(); } } public class HallOfFame { private HallOfFameMember[] members; private int numberOfMembers; public HallOfFameMember[] getMembers() { return members; } public void setMembers(HallOfFameMember[] members) { this.members = members; } public int getNumberOfMembers() { return numberOfMembers; } public void setNumberOfMembers(int numberOfMembers) { this.numberOfMembers = numberOfMembers; } public void sortMembers(HallOfFameMember[] sortedMembers) { boolean bool = true; HallOfFameMember temp; while (bool) { bool = false; for (int i = 0; i < sortedMembers.length - 1; i++) { if (sortedMembers[i].compareTo(sortedMembers[i + 1]) > 0) { temp = sortedMembers[i]; sortedMembers[i] = sortedMembers[i + 1]; sortedMembers[i + 1] = temp; bool = true; } } } } public static void printReport(HallOfFameMember[] print) { System.out.println("Java Sports Hall of Fame Inductees\n\n"); System.out.printf("%-30s\t%-30s\t%-30s\n", "Name", "Year Inducted", "Sport"); for (int i = 0; i < print.length; i++) System.out.printf("%-30s\t%-30s\t%-30s\n", print[i].getLastName() + "," + print[i].getFirstName(), print[i].getYearInducted(), print[i].getSport()); } } A: You initialised your array on this line: HallOfFameMember[] tempMembers = new HallOfFameMember[args.length / 4]; but the array will contain null elements. You need to construct each element in the array before you try to call methods on it: tempMembers[i/4] = new HallOfFameMember(); tempMembers[i/4].setFirstName(args[i]); A: When you declare tempMembers, you initialize the array but not the elements. Add this to your for loop: tempMembers[i / 4] = new HallOfFameMember(); Then you'll get another NPE because sortedMembers is null (as you are explicitly setting it to be). I also notice some other strange areas in your code. For example, in HallOfFame#sortMembers(HallOfFameMember[]), why do you use a while loop that will run exactly once in any condition (setting bool to true beforehand and false during the loop)? Change the last four lines to : hallOfFameList.setMembers(tempMembers); final HallOfFameMember[] sortedMembers = tempMembers; hallOfFameList.sortMembers(tempMembers); HallOfFame.printReport(sortedMembers); to resolve the last exception and get the desired output. A: The exception means that tempMembers[i/4] evaluates to null, and when you try to call a method on null, you get a NullPointerException. In this case, you're getting it because you haven't actually put anything into tempMembers yet. In Java, creating an array doesn't populate it. Creating the array with new HallOfFameMember[args.length / 4] creates a new array of some length with all of its positions set to null. So after creating the array, you need to create and store a new HallOfFameMember in each array position.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select elements row-wise from a NumPy array? I have an array like this numpy array dd= [[foo 0.567 0.611] [bar 0.469 0.479] [noo 0.220 0.269] [tar 0.480 0.508] [boo 0.324 0.324]] How would one loop through array selecting foo and getting 0.567 0.611 as floats as a singleton. Then select bar and getting 0.469 0.479 as floats as a singleton ..... I could get vector the first elements as list by using dv= dd[:,1] The 'foo', and 'bar' elements are not unknown variables, they can change. How would I change if element is in position [1]? [[0.567 foo2 0.611] [0.469 bar2 0.479] [0.220 noo2 0.269] [0.480 tar2 0.508] [0.324 boo2 0.324]] A: You have put the NumPy tag on your Question, so i'll assume you want NumPy syntax, which the answer before mine doesn't use. If in fact you wish to use NumPy, then you likely don't want the strings in your array, otherwise you will also have to represent your floats as strings. What you are looking for is the NumPy syntax to access elements of a 2D array by row (and exclude the first column). That syntax is: M[row_index,1:] # selects all but 1st col from row given by 'row_index' W/r/t the second scenario in your Question--selecting non-adjacent columns: M[row_index,[0,2]] # selects 1st & 3rd cols from row given by 'row_index' The small complication in your Question is just that you want to use a string for row_index, so it's necessary to remove the strings (so you can create a 2D NumPy array of floats), replace them with numerical row indices and then create a look-up table to map the the strings with the numerical row indices: >>> import numpy as NP >>> # create a look-up table so you can remove the strings from your python nested list, >>> # which will allow you to represent your data as a 2D NumPy array with dtype=float >>> keys ['foo', 'bar', 'noo', 'tar', 'boo'] >>> values # 1D index array comprised of one float value for each unique string in 'keys' array([0., 1., 2., 3., 4.]) >>> LuT = dict(zip(keys, values)) >>> # add an index to data by inserting 'values' array as first column of the data matrix >>> A = NP.hstack((vals, A)) >>> A NP.array([ [ 0., .567, .611], [ 1., .469, .479], [ 2., .22, .269], [ 3., .48, .508], [ 4., .324, .324] ]) >>> # so now to look up an item, by 'key': >>> # write a small function to perform the look-ups: >>> def select_row(key): return A[LuT[key],1:] >>> select_row('foo') array([ 0.567, 0.611]) >>> select_row('noo') array([ 0.22 , 0.269]) The second scenario in your Question: what if the index column changes? >>> # e.g., move index to column 1 (as in your Q) >>> A = NP.roll(A, 1, axis=1) >>> A array([[ 0.611, 1. , 0.567], [ 0.479, 2. , 0.469], [ 0.269, 3. , 0.22 ], [ 0.508, 4. , 0.48 ], [ 0.324, 5. , 0.324]]) >>> # the original function is changed slightly, to select non-adjacent columns: >>> def select_row2(key): return A[LuT[key],[0,2]] >>> select_row2('foo') array([ 0.611, 0.567]) A: First, the vector of first elements is dv = dd[:,0] (python is 0-indexed) Second, to walk the array (and store in a dict, for example) you write: dc = {} ind = 0 # this corresponds to the column with the names for row in dd: dc[row[ind]] = row[1:]
{ "language": "en", "url": "https://stackoverflow.com/questions/7543250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Rails - Problems refactoring controller's nested attribute creation I have models: Transaction has_many :credits, :debits Credit belongs_to :transaction Debit belongs_to :transaction Each credit must have a balancing debit and vice versa. I currently (successfully) achieve this with the following inside Transaction's create method: @transaction = Transaction.new(params[:transaction]) Transaction.transaction do # Balance debits with credits (Sales) if params[:balance_transaction] == 'credit' @transaction.credits.each do |credit| @transaction.debits.push(Debit.new({ :quantity => 0, :cost_per_unit => 0, :description => 'Balancing Debit', :amount => credit.amount, :account_id => 23 #Get from settings in future to allow users to choose Debtor account })) end elsif params[:balance_transaction] == 'debit' @transaction.debits.each do |debit| @transaction.credits.push(Credit.new({ :quantity => 0, :cost_per_unit => 0, :description => 'Balancing Credit', :amount => credit.amount, :account_id => 43 #Get from settings in future to allow users to choose Creditor account })) end else raise ActiveRecord::Rollback # There's no balancing transaction. Don't save it! end end I tried moving the balancing debit/credit creation into the debit/credit models by replacing @transactions.credits.push(...) with debit.balancing_credit and putting the following in the debit model: def balancing_credit transaction.credits.new({ :quantity => 0, :cost_per_unit => 0, :description => 'Balancing Debit', :amount => amount, :account_id => 43 #Get from settings in future to allow users to choose Creditor account }) end I thought this was pretty straightforward refactoring, but it throws up an undefined method 'debits' for nil:NilClass error. Seems it looks in the database for the not yet saved transaction in order to create the balancing credit? Am I doing something wrong? A: You're right on the fact that such a mechanism should belong to the models, not to a controller. You could have a before_save callback on your Transaction model: class Transaction after_save :balance_operations def balance_operations if credits credits.each do|credit| debit = debits.build (#do all your stuff here. build() automaticly fills the transaction_id field of your new debit with the proper id) return false unless debit.save end if debits # can use elsif if mutually exclusive conditions # same thing as above end end end This relies on the fact that the callback chain is wrapped in an ActiveRecord::Base.transaction. If a callback returns false, ActiveRecord will perform a Rollback. See the "transaction" chapter here for more info. If you have many operations in one transaction, you can also peek a look at this to improve performance. Edit: you can also add validates_associated :debit, :credits to your model
{ "language": "en", "url": "https://stackoverflow.com/questions/7543252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding detailed text in QMessageBox makes close (X) button disabled I noticed an interesting thing - if I add a detailed text to QMessageBox (which adds "Show Details..." button) then executing it will show the system frame's close (X) button disabled and hence marking this window as non-closable (right click on frame -> Close disabled). Here is some sample code: QMessageBox box(QMessageBox::Critical, title, text, QMessageBox::Ok); box.setDetailedText(detailedText); // comment this line to get close button enabled box.exec(); I didn't even find a way to manually do this in Qt. Any ideas? Thanks A: I was having the same problem with Python 2.7 and PySide. In this example, the red close button works as expected: from PySide import QtGui, QtCore import sys app = QtGui.QApplication(sys.argv) message_box = QtGui.QMessageBox() message_box.setWindowTitle("Close Test") message_box.setText("Testing whether or not the red X is enabled.") ret = message_box.exec_() Adding detailed text disables the close button: from PySide import QtGui, QtCore import sys app = QtGui.QApplication(sys.argv) message_box = QtGui.QMessageBox() message_box.setWindowTitle("Close Test") message_box.setText("Testing whether or not the red X is enabled.") message_box.setDetailedText("These details disable the close button for some reason.") ret = message_box.exec_() The answer marked as the solution does not solve this problem. As you can see in this example, the close button remains disabled: from PySide import QtGui, QtCore import sys app = QtGui.QApplication(sys.argv) message_box = QtGui.QMessageBox() message_box.setWindowTitle("Close Test") message_box.setText("Testing whether or not the red X is enabled.") message_box.setDetailedText("These details disable the close button for some reason.") message_box.setWindowFlags(message_box.windowFlags() & ~QtCore.Qt.WindowCloseButtonHint) ret = message_box.exec_() The answer is to set the standard buttons and ALSO set the escape button: from PySide import QtGui, QtCore import sys app = QtGui.QApplication(sys.argv) message_box = QtGui.QMessageBox() message_box.setWindowTitle("Close Test") message_box.setText("Testing whether or not the red X is enabled.") message_box.setDetailedText("These details disable the close button for some reason.") message_box.setStandardButtons(QtGui.QMessageBox.Ok) message_box.setDefaultButton(QtGui.QMessageBox.Ok) message_box.setEscapeButton(QtGui.QMessageBox.Ok) ret = message_box.exec_() This restores the desired close button behavior. A: I came across this recently on Qt 4.8 Linux. I found that whether or not the X was disabled depended on the ButtonRole I used on the call to QMessageBox::addButton(). The X was disabled when all roles were ActionRole - which is really supposed to be for buttons that affect the dialog, but do not accept or reject it. What the buttons did in my case is more accurately described as AcceptRole or RejectRole. When I changed the roles to have one RejectRole and the rest AcceptRole, the X started working. It looks as though QMessageBox was reluctant to accept a close when none of the buttons had roles that mapped to close. A: You need to unset the Qt::WindowCloseButtonHint widget flag. Like this: QMessageBox messageBox; messageBox.setWindowFlags(messageBox.windowFlags() & ~Qt::WindowCloseButtonHint); You may unset this flag Qt::WindowSystemMenuHint either. Adds a window system menu, and possibly a close button (for example on Mac). If you need to hide or show a close button, it is more portable to use WindowCloseButtonHint. http://qt-project.org/doc/qt-4.8/qt.html#WindowType-enum
{ "language": "en", "url": "https://stackoverflow.com/questions/7543258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: iOS: executeFetchRequest:error: A fetch request must have an entity I developed an application targeted for iPhone and it uses CoreData. All is working ok when I run it on the simulator, but when I run it on the device I'm getting the following error: "*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'" I have specified and defined an entity in my code as follows: NSFetchRequest *select = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"NewsStand" inManagedObjectContext:[CDHelper sharedCDHelper].managedObjectContext]; [select setEntity:entity]; NSError *error; NSMutableArray *results = [[[CDHelper sharedCDHelper].managedObjectContext executeFetchRequest:select error:&error] mutableCopy]; The error occurs when I execute the fetch to show in a tableView what has stored the DB. I also have defined a managedObjectModel: - (NSManagedObjectModel *)managedObjectModel { if (__managedObjectModel != nil) { return __managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"newsStandModel" withExtension:@"momd"]; __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return __managedObjectModel; } A: When you load the managed object model what do you specify as the model file name? (something .mom). The simulator is not case sensitive, the device is. i.e. if the file is called MyModel.mom then NSString *path = [NSBundle mainBundle] pathForResource:@"mymodel" type:@"mom"]; NSURL *url = [NSURL fileURLWithString:string]; myModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:url]; works on the simulator but not on the device. A: Are you sure you spelled the entity name correctly? Are you sure the managed object context's managed object model has an entity with that name? Either of those things could cause +entityForName:inManagedObjectContext: to return nil, which is almost definitely your problem. A: You can also use setter method from CoraData ... Just do something like this... On your CustomCoreDataManager.m #import "ObjectiveRecord.h" call init method like this -(instancetype)init { self = [super init]; if (self) { [[CoreDataManager sharedManager] setModelName:@"YourModelName"]; } return self; } Hope this helps to someone...
{ "language": "en", "url": "https://stackoverflow.com/questions/7543260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using GET for the values of two text inputs I am having some difficulty getting the values of two text inputs: <form action="search.php"> <input type="text" name="q1"> <input type="text" name="q2" > <input type="submit" name="submit" value="Search" /> </form> This is the search.php page: $q1 = @$_GET['q1']; $q2 = @$_GET['q2']; if(isset($q1) && isset($q2)) { $var= "$q1, $q2"; } if(isset($q1) && empty($q2)) { $var= "$q1"; } When both q1 and q2 are filled out and sent, it works perfectly. However, when only the q1 input is filled out and sent (leaving q2 blank), it still creates $var using the the first if-statement -- if(isset($q1) && isset($q2) -- instead of the second one -- if(isset($q1) && empty($q2). Why is this happening? A: You're setting $q1 and $q2 so isset($q1) and isset($q2) will always return true. Try if(isset($_GET['q1']) && isset($_GET['q2'])) { Or test for an empty value: if(empty($q1) && empty($q2)) { A: $q2 is set even if they don't enter any value. It's a valid form field (although containing an empty string). A: You're setting both $q1 and $q2 when you do the assignment: $q1 = @$_GET['q1']; $q2 = @$_GET['q2']; In the case when the user didn't fill out the second field, $q2 just gets set to the empty string. A string being empty is not the same as a string being null. Take a look at this page about isset from the PHP manual: http://php.net/manual/en/function.isset.php A: if ($q1 != '' && $q2 != '') { $var = "$q1, $q2"; } elseif($q1 != '') { $var = "$q1"; } A: Are they both being passed along - but not filled? I'm thinking a conditional more like: !empty($_GET['q1']) && ($_GET['q1'] != '') Some combination of that should help. I imagine q1 & q2 are being sent whether or not they're being used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook RSVP to an event using jQuery / JavaScript I've been trying this without success. I've already gotten the user's authentication with event_rsvp permissions, as well as an access token, yet each time I try to RSVP to an event, it doesn't work. I call the following on a button click: function attendingEvent() { var url = 'https://graph.facebook.com/'+eventid+'/attending/'+userid+'?access_token='+accessToken; $.post(url, function(data) { $('#event_info').html(data); }); } For some reason I'm not even getting the "callback". What am I doing wrong? A: That should work, but as Colin says make sure you're POSTing the request. A GET request to /{event id}/attending/{user id} returns an array of user name and user id if the user is already attending the event, and an empty array otherwise Try the Graph API Explorer to debug this A: You may need to include the POST method by adding it like: https://graph.facebook.com/'+eventid+'/attending/'+userid+'?access_token='+accessToken&method=POST I would also look at the access_token. I believe if you receive no response its an access token issue, you should get an error response for most other conditions. Try copying your values into the FB test console here: http://developers.facebook.com/docs/reference/rest/events.rsvp/ Below the RSVP function details. It may reveal more about an access token issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Issue with Checkboxes in Wicket I am finding an issue in getting the checkboxes count that are checked by default using, item.add(new CheckBox("selected",new PropertyModel(this, "checked")).setEnabled(false)); Any help is appreciated. My Listview class: ExampleListView(String id, List<Extended> lists, PageParameters params){ protected void populateItem(ListItem<Extended> item) { item.add(new CheckBox("selected",new PropertyModel(this, "checked")).setEnabled(false)); } boolean checked= true; public boolean isChecked() { return checked; } public void setChecked(boolean checked) { this.checked = checked; } } This I need to have the checkbox selected and disabled (kind of read only selected checkbox). In other scenario I also need to have item.add(new CheckBox("selected", new PropertyModel(this, "checked"))); As shown in above code, I introduced, Checked boolean, this displays a selected checkbox in UI, but the selected count list did not get incremented In My Form class constructor: public class ExampleForm{ public ExampleForm(String id, List<Extended> list, PageParameters params){ add(new ExampleListView("Rows", list,params)); AjaxButton<Void> button= new AjaxButton<Void>("Button"){ @Override public void onClick(AjaxRequestTarget target) { for (Extended extn : list) { if (((Extended)extn).isSelected()) { selected.add(extn); } } }; } add(button); } } my Html file : <input class="simpleLink" wicket:id="selected" type="checkbox"/> Class file: public class Extended implements Serializable { private transient boolean selected = false; public boolean isSelected() { return selected; } public void setSelected (Boolean selected) { this. selected = selected; } } A: Your checked model is the same for all your checkboxes (using a PropertyModel mapping to ExampleListView.checked), is it by purpose ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7543269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing a binding to libpcap with Python 3 I've been banging away at this for a while an I'm unsure of the issue here. For some reason my device is being changed and I'm unsure why. I suspect it has to do with how I'm mapping the libpcap libs to ctypes because the same program written in pure C works just fine on my host. The code is as follows #!/usr/bin/env python3.2 import ctypes,sys from ctypes.util import find_library #pcap = ctypes.cdll.LoadLibrary("libpcap.so") pcap = ctypes.cdll.LoadLibrary(find_library("libpcap")) # required so we can access bpf_program->bf_insns """ struct bpf_program { u_int bf_len; struct bpf_insn *bf_insns;} """ class bpf_program(ctypes.Structure): _fields_ = [("bf_len", ctypes.c_int),("bf_insns", ctypes.c_void_p)] class sockaddr(ctypes.Structure): _fields_=[("sa_family",ctypes.c_uint16),("sa_data",ctypes.c_char*14)] class pcap_pkthdr(ctypes.Structure): _fields_ = [("tv_sec", ctypes.c_long), ("tv_usec", ctypes.c_long), ("caplen", ctypes.c_uint), ("len", ctypes.c_uint)] pcap_lookupdev = pcap.pcap_lookupdev pcap_lookupdev.restype = ctypes.c_char_p #pcap_lookupnet(dev, &net, &mask, errbuf) pcap_lookupnet = pcap.pcap_lookupnet #pcap_t *pcap_open_live(const char *device, int snaplen,int promisc, int to_ms, char *errbuf) pcap_open_live = pcap.pcap_open_live pcap_open_live.restype = ctypes.c_char_p #int pcap_compile(pcap_t *p, struct bpf_program *fp,const char *str, int optimize, bpf_u_int32 netmask) pcap_compile = pcap.pcap_compile #int pcap_setfilter(pcap_t *p, struct bpf_program *fp) pcap_setfilter = pcap.pcap_setfilter #const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h) pcap_next = pcap.pcap_next # prepare args snaplen = ctypes.c_int(1540) linktype = ctypes.c_int(12) # DLT_RAW on linux program = bpf_program() #buf = ctypes.c_char_p(filter) optimize = ctypes.c_int(0) mask = ctypes.c_int(0) errbuf = ctypes.create_string_buffer(256) dev = pcap_lookupdev(errbuf) dev = bytes(str('en1'), 'ascii') if(dev): print("{0} is the default interface".format(dev)) else: print("Was not able to find default interface {0}".format(errbuf.value)) mask = ctypes.c_uint(32) net = ctypes.c_uint(32) if(pcap_lookupnet(dev,ctypes.pointer(net),ctypes.pointer(mask),errbuf) == -1): print("Error could not get netmask for device {0}".format(errbuf.value)) sys.exit(0) else: print("Got Required netmask") to_ms = ctypes.c_int(1000) promisc = ctypes.c_int(1) handle = pcap_open_live(dev,snaplen,promisc,to_ms,errbuf) if(handle is False): print("Error unable to open session : {0}".format(errbuf.value)) sys.exit(0) else: print("Pcap open live worked!") filter = bytes(str('port 80'), 'ascii') buf = ctypes.c_char_p(filter) if(pcap_compile(handle,ctypes.byref(program),buf,ctypes.c_int(1),mask) == -1): # this requires we call pcap_geterr() to get the error print("Error could not compile bpf filter because {0}".format(errbuf.value)) else: print("Filter Compiled!") if(pcap_setfilter(handle,ctypes.byref(program) == -1)): print("Error couldn't install filter {0}".format(errbuf.value)) sys.exit(0) else: print("Filter installed!") header = pcap_pkthdr() if(pcap_next(handle,ctypes.bref(header)) == -1): print("ERROR pcap_next failed!") print("Got {0} bytes of data".format(pcap_pkthdr().len)) pcap_close = pcap.pcap_close pcap_close(handle) For some reason when we get to pcap_compile() the system tries to look up one of the vmware interfaces instead of the value assigned to dev .. here is the output. bash-3.2# ./libpcap.py b'en1' is the default interface Got Required netmask Pcap open live worked! Error could not compile bpf filter because b'vmnet8: No such device exists (BIOCSETIF failed: Device not configured)' Bus error: 10 A: This is incorrect: if(handle is False): A NULL pointer returned from ctypes is None. In Python it is customary to just say: if not handle: I suspect handle is invalid because dev is not in the correct format. Note in Python parentheses are not required with if. As an aside: bytes(str('string'), 'ascii') can simply be: b'string' A: ctypes.cdll.LoadLibrary(find_library("pcap")) On my ubuntu 16.04, find_library failed unless the name was given without the 'lib' prefix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sync Code-first Entity Framework 4 built database with Membership on remote server I've started building a ASP net MVC 2.0 web application using SQL Express 2008 R2. I'm hosting the application on somee.com. I decided to use Entity Framework 4 with a code-first implementation of the database as to be able to easily change the design. It works fine locally, but when I deploy it on my host provider a lot of problems appear. First of all, I can't manage to reinitialise the database if the model has changed, since the database most be created beforehand on the hosting website. Hence, I don't have the permissions to do so. So OK, I decide to fetch the .mdf file on my local server SQLEXPRESS and to send it on the host server, but then for some reason I can't connect to the database when I register a new user with Membership. The is where the exception occurs: _provider.CreateUser(userName, password, email, null, null, true, null, out status); The error: Cannot open database "People" requested by the login. The login failed. Login failed for user 'dalya'. Now, I have a feeling that by fetching the mdf file in the DATA folder of my local SQL EXPRESS server, the permissions might be different then the permissions given by my most provider when it attached the file. Still, here is my Web.config file: <?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=152368 --> <configuration> <connectionStrings> <!-- <add name="People" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=People;" providerName="System.Data.SqlClient" /> --> <add name="People" connectionString="Data source=PraxtPeople.mssql.somee.com; packet size=4096; user id=dalya; pwd=********; persist security info=False; initial catalog=People; " providerName="System.Data.SqlClient"/> </connectionStrings> <appSettings> <add key="DefaultConnectionString" value="People"/> <add key="webpages:Version" value="1.0.0.0"/> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation> <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication> <membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="People" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership> <profile> <providers> <clear/> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="People" applicationName="/" /> </providers> </profile> <roleManager enabled="false"> <providers> <clear/> <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="People" applicationName="/" /> <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> </providers> </roleManager> <pages> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration> Could anyone give me an idea on how to resolve this? Or does anyone know a good host provider that permits code-first entity framework 4.0 implementation, where databases using Membership can be recreated in runtime without hassle if the design changes? Thank you for any help, A: Try to change persist security info=False; to persist security info=True;
{ "language": "en", "url": "https://stackoverflow.com/questions/7543279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Non-bootable Win 2003 Server--need to find ODBC settings I inherited a problem. I have a Windows 2003 machine that will not boot. I really just need to view the ODBC setttings from this drive (i.e. win 2003 boot drive). I was able to mount and access the drive from Win 7. My plan was to: 1. Launch regedit from Win 7 2. Use Load Hive to access registry on 2003 drive. 3. Find ODBC setting information. However, Win 7's regedit will not let me use load hive. It's disabled. How can I enable load hive? Will load hive allow me to access the win 2003's registry? Is there an easier way to vview the ODBC settings? Thanks! A: Follow instructions here. You can only load onto HKLM (local machine) in win7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Iterate through lots of records and aggregate an integer property in Google App Engine - java Google App Engine - Java - JDO I'm storing an object "Bucket" in the datastore that has a field/property of "totalsize" - an integer that is an aggregate of all the size of the associated blobs of the Bucket. Each Bucket has 3 corresponding blobs. This field gives me the total size in bytes of all three of it's blobs. I'm aggregating this count when I put the blobs into the datastore. Now, I say I have MILLIONS of these Buckets. How can I get a total aggregate of all the totalsize fields in all of the Buckets? These buckets relate to an Account object. Essentially, I'd like to determine the total amount of data under management per account. Obviously I'm looking for the best way to do this. I doubt that retrieving them all and looping through is a possibility. Thanks! A: I've got MapReduce working and it is amazing. To do it, I followed the instructions here: http://code.google.com/p/appengine-mapreduce/wiki/GettingStartedInJava
{ "language": "en", "url": "https://stackoverflow.com/questions/7543296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fadeout on hover effect in iPad I tried to use the fadeIn and fadeOut effect as you can see in this page: http://www.lifetime-watches.com/gal-w.html var titleString = $(this).find('a').attr("title"); $("#title").html(titleString).fadeIn(100); ; So when they run the script the title of the image would fade in in a div. But the problem is when this page is opened in iPads, the hover function doesn't work (because obviously they don't have hover) and the div wouldn't fade out. What are the alternatives to this? Any help is appreciated. Thank you. A: The jQuery Hoverable Plugin: unifies touch and mouse events over different platforms like desktops and mobile devices with touchscreens That might be a good alternative for your app. A: You want to create a second implementation that works with the click event. May be something like this: $(selector syntax).click(function () { AnimationEffect(this); }); $(selector syntax).mouseenter(function () { AnimationEffect(this); }); function AnimationEffect(TheDiv) { //your animation goes here, TheDiv is the jquery object //you can access it like this: $(TheDiv). } A: Have the user click on the watch, then click again to get rid of the info. This can be accomplished using the .toggle() method: http://api.jquery.com/toggle-event/
{ "language": "en", "url": "https://stackoverflow.com/questions/7543306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: touch issue advice Hi guys i have a issue with my code. I have 6 sprites that moves from bottom and to the top. 3 of the sprites can be touched. When i touch that sprite counter will increate +1 and that sprite will be removed. The problem I'm facing is that when i select that sprite the counter increase to 1, but if i select that sprite twice within half secs, counter increase to 2. i can see on the first touch the sprite disappear, but why once it disappears it can still detect that sprite bounding box(if click within half sec). How can i solve this problem? I'm using cocos2d P.S if i select the sprite after half sec no problem. //other code CGPoint gridu2 =ccp(80,-45); CGPoint gridu3 =ccp(80,-130); CGPoint gridu4 =ccp(80,-215); CGPoint gridu7 =ccp(240,-45); CGPoint gridu8 =ccp(240,-130); CGPoint gridu9 =ccp(240,-215); //left grid up id actionMoveUp2 = [CCMoveTo actionWithDuration:7 position:ccp(80,winSize.height + 215)]; id actionMoveUp3 = [CCMoveTo actionWithDuration:7 position:ccp(80,winSize.height + 130)]; id actionMoveUp4 = [CCMoveTo actionWithDuration:7 position:ccp(80,winSize.height + 45)]; //right grid down id actionMoveDown7 = [CCMoveTo actionWithDuration:7 position:ccp(240,winSize.height +255)]; id actionMoveDown8 = [CCMoveTo actionWithDuration:7 position:ccp(240,winSize.height +170)]; id actionMoveDown9 = [CCMoveTo actionWithDuration:7 position:ccp(240,winSize.height +85)]; correctColor1.position=gridu2; correctColor2.position=gridu3; correctColor3.position=gridu9; random4.position=gridu4; random5.position=gridu7; random6.position=gridu8; [correctColor1 runAction:actionMoveUp2]; [correctColor2 runAction:actionMoveUp3]; [correctColor3 runAction:actionMoveDown9]; [random4 runAction:actionMoveUp4]; [random5 runAction:actionMoveDown7]; [random6 runAction:actionMoveDown8]; [self addChild:correctColor1 z:10 tag:1]; [self addChild:correctColor2 z:10 tag:2]; [self addChild:correctColor3 z:10 tag:3]; [self addChild:random4 z:1 tag:14]; [self addChild:random5 z:1 tag:15]; [self addChild:random6 z:1 tag:16]; -(void)addToScore:(int)number { score=score+number; [scoreLabel setString:[NSString stringWithFormat:@"%d",score]]; } -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { CGSize winSize =[[CCDirector sharedDirector] winSize]; UITouch* myTouch = [touches anyObject]; CGPoint location = [myTouch locationInView: [myTouch view]]; location = [[CCDirector sharedDirector]convertToGL:location]; // to remove touched sprite int totalNumberOfItems=3; for (int y=1; y < totalNumberOfItems; y++){ CCSprite *temp = (CCSprite*)[self getChildByTag:y]; CGRect correctColor = [temp boundingBox]; if (CGRectContainsPoint(correctColor, location)) { NSLog(@"touched"); [self removeChild:temp cleanup:YES ]; [self addToScore:1]; return; } } A: I think what you need to implement a ccTouchEnded function so that you can detect the touch has ended and avoid the duplicate touches. A: There are a couple of things you could try. Try putting the [self removeChild:temp cleanup:YES] in the ccTouchesEnded: method. Im not sure that would work. Another thing you could do is disable touch for half a second. Call [self setIsTouchEnabled:NO] and then set it to yes after a delay in ccTouchesEnded: Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7543307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating new files on SD card: Permission denied. I've tried all solutions? I am sure that I have added permission WRITE_EXTERNAL_STORAGE in manifest.xml, and I have also checked the state of SD card using Environment.getExternalStorageState(), makeing sure the value is Environment.MEDIA_MOUNTED, not Environment.MEDIA_SHARED or anything else. Even with these checks passed, there still is a permission denied error when I try to create new files! This error only occurs on Nexus One so far. For I myself do not have a Nexus One, I cannot debug it directly. Could anybody help me? A: I think you should try this. Not sure if it will solve your problem: Environment.getExternalStorageDirectory() example: String path= Environment.getExternalStorageDirectory()+"/yourfilename/"; File file = new File(path); if(!file.exists()) file.mkdirs(); A: As far as I was concerned, Environment.MEDIA_MOUNTED returned false and an IOException (Permission denied) was raised because I forgot to add a SD card to my Android Virtual Device.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I override default privacy setting using Facebook API? I got default privacy setting set to Custom (Only you) in my facebook. Then I have the following code to create a photo album: $privacy = Array('value'=>'ALL_FRIENDS'); $privacy = (object)$privacy; $albumDetails = array( 'name' => 'My album name', 'privacy' => $privacy ); $facebook->api('/me/albums', 'post', $albumDetails); After executing the code, album is created but the privacy is keep to Custom (only you), not All friends/friends. What's wrong in my code. Is there any special code to override the default privacy? Thank you. A: i can't promise it ! in the developer docs http://developers.facebook.com/docs/reference/api/post/ says "Note: This privacy setting only applies to posts to the current or specified user's own Wall. Facebook ignores this setting for targeted Wall posts (when the user is writing on the Wall of a friend, Page, event, group connected to the user). Consistent with behavior on Facebook, all targeted posts are viewable by anyone who can see the target's Wall. " this mean, the developer can't make privacy control on their app did user can control it from wall, and if then application use privacy statmen is make lost control of privacy settings :p sorry my bad english :p A: You can't override the default privacy that the user stated in their configuration, unless you are overriding it to a more restrictive option. Meaning that if the user's default configuration is set to "All friends", and you specify "Only me", it will work. But not the other way around, like you are trying to do
{ "language": "en", "url": "https://stackoverflow.com/questions/7543312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle keypress events in a Qt console application? For example, that when you press "Esc", the application ends. A: Here is a workaround for linux. Using these posts Capture characters from standard input without waiting for enter to be pressed https://stackoverflow.com/a/912796/2699984 I've made it like this: ConsoleReader.h #ifndef CONSOLEREADER_H #define CONSOLEREADER_H #include <QThread> class ConsoleReader : public QThread { Q_OBJECT signals: void KeyPressed(char ch); public: ConsoleReader(); ~ConsoleReader(); void run(); }; #endif /* CONSOLEREADER_H */ ConsoleReader.cpp #include "ConsoleReader.h" #include <stdio.h> #include <unistd.h> #include <termios.h> static struct termios oldSettings; static struct termios newSettings; /* Initialize new terminal i/o settings */ void initTermios(int echo) { tcgetattr(0, &oldSettings); /* grab old terminal i/o settings */ newSettings = oldSettings; /* make new settings same as old settings */ newSettings.c_lflag &= ~ICANON; /* disable buffered i/o */ newSettings.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ tcsetattr(0, TCSANOW, &newSettings); /* use these new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &oldSettings); } /* Read 1 character without echo */ char getch(void) { return getchar(); } ConsoleReader::ConsoleReader() { initTermios(0); } ConsoleReader::~ConsoleReader() { resetTermios(); } void ConsoleReader::run() { forever { char key = getch(); emit KeyPressed(key); } } And then just start new thread to read keys: ConsoleReader *consoleReader = new ConsoleReader(); connect (consoleReader, SIGNAL (KeyPressed(char)), this, SLOT(OnConsoleKeyPressed(char))); consoleReader->start(); *UPDATED (added restoring terminal settings on quit) A: If you need only 'quit' maybe the following snippet will help (c++11 and qt5 required): #include <iostream> #include <future> #include <QCoreApplication> #include <QTimer> int main(int argc, char *argv[]) { QCoreApplication application(argc, argv); bool exitFlag = false; auto f = std::async(std::launch::async, [&exitFlag]{ std::getchar(); exitFlag = true; }); QTimer exitTimer; exitTimer.setInterval(500); exitTimer.setSingleShot(false); QObject::connect(&exitTimer, &QTimer::timeout, [&application,&exitFlag] { if (exitFlag) application.quit(); }); exitTimer.start(); std::cout << "Started! Press Enter to quit..."; int ret = application.exec(); std::cout.flush(); f.wait(); return ret; } A: Qt doesn't handle console events, it can just read \n-terminated lines from the console. You need to use native APIs or other libraries (curses).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Internal anchor links break scrollbar with Tiny Scrollbar plugin Help! I'm trying to build a webpage using the excellent Tiny Scrollbar from www.baijs.nl. However, i need to add some internal anchor links to jump down to the appropriate section of the content but this is proving to be a problem. (All the content, including the internal anchor links, are housed within the Tiny Scrollbar div containers). See my basic mockup on http://jsfiddle.net/uy4hK/ My problem is that although the internal link is jumping down to the correct section, the scrollbar on the right is not updating to the correct position - it just stays at the top. There is an update method that can be used, and the demo also has a version of internal scrolling but using a number variable (200px) but i am unable to tweak this to make it work in my jsfiddle demo. I can't really use a number because content can vary and the internal links are within the content inside the Tiny Scrollbar container. Can anyone help? A: jsFiddle: http://jsfiddle.net/fausak/uy4hK/2/ I think you can pull this off with use of jQuery's position() method. Try this: $('a[href^="#"]').click(function() { // Find the bottom of the box with the scrollbar // (close approximation: the top position of the last element in the box) var bottom = $('.viewport .overview').children().last().position().top; // Determine what position this internal link is located at // (if you use <a name=".."> you will need to change this, // right now it only matches element IDs like <h1 id="link0"> var cur = $($(this).attr('href')).position().top; // If the position of the link is too low for the scrollbar in this box, // just set it to the bottom if (cur >= bottom - $('.viewport').height()) { cur = 'bottom'; } else { cur = cur + 'px'; } $('#scrollbar1').tinyscrollbar_update(cur); }); A: Thanks rfausak. Actually in situation, we want to make anchor link external from scrollbar. We can make for example : <div class="overview"> <h3 id="link0">Magnis dis parturient montes</h3> <p>Text in here</p> <h3 id="link1">Magnis dis parturient montes</h3> <p>Text in here</p> </div> <a href="#" rel="link1" class="scroll1load">anchor link1</a> <a href="#" rel="link0" class="scroll1load">anchor link0</a> Modifying of rfausak code: $('a.scroll1load').click(function(){ // Find the bottom of the box with the scrollbar // (close approximation: the top position of the last element in the box) var bottom = $('.viewport .overview').children().last().position().top; // Determine what position this internal link is located at // (if you use <a name=".."> you will need to change this, // right now it only matches element IDs like <h1 id="link0"> //var cur = $($('#scroll1load').attr('href')).position().top; var anchor = $(this).attr('rel'); var cur = $('div.overview h3#'+anchor).position().top; // If the position of the link is too low for the scrollbar in this box, // just set it to the bottom if (cur >= bottom - $('.viewport').height()) { cur = 'bottom'; } else { cur = cur + 'px'; } oScroll.tinyscrollbar_update(cur); return false; }); A: I'm not sure if exactly what you're asking is possible with the Tiny Scrollbar plugin. The following will get you pretty close, though: $('a[href^="#"]').click(function() { $('#scrollbar1').tinyscrollbar_update('bottom'); }); If your content is static, you could replace 'bottom' with an actual pixel length, like '25px'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IIS 7.5 Rewrite URL with Reverse Proxy from a default web site to two web sites failed I want the users to access my intranet test website - http://mywebsite:9090 if they type http://mywebsite/test. I am following section - 7. Reverse Proxy To Another Site/Server in http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx to create a url rewrite. After checked the “Enable proxy” checkbox located in Application Request Routing feature view in IIS Manager. I have the rule as - <rule name="Proxy"> <match url="(.*/test)" /> <action type="Rewrite" url="http://{HTTP_HOST}:9090/{R:1}" /> </rule> However this does not work. It does not direct me to http://mywebsite:9090 but prints out that http://mywebsite/test is not found. Changed the rule to see if it is a proxy problem by using - <rule name="Proxy"> <match url="(.*)" /> <action type="Rewrite" url="http://{HTTP_HOST}:9090/{R:1}" /> </rule> I can see it can direct me to http://mywebsite:9090 when I browse http://mywebsite. What happens to my first rule? Thanks for the help. A: What you want is the rule: "^test(/.*)?$" Your action can stay the same. With the rule above, you're saying "if the first thing after the HTTP_HOST part of the url (which includes the first slash, i.e. "http://mywebsite.com/") is equal to test, then you create a capture group on all of the rest of the URL (if there is any), rewrite the URL to have the HTTP_HOST, add the port 9090, and then append whatever was in the first capture group (i.e. R:1, whatever is in the parens in the regex). Make sure you uncheck Append query string as you are capturing what you need as part of the Regex and don't need that. Credit where's it due, I was struggling with solving this too and found what I needed here: http://forums.iis.net/t/1180781.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7543320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to convert WebResponse.GetResponseStream return into a string? I see many examples but all of them read them into byte arrays or 256 chars at a time, slowly. Why? Is it not advisable to just convert the resulting Stream value into a string where I can parse it? A: You should create a StreamReader around the stream, then call ReadToEnd. You should consider calling WebClient.DownloadString instead. A: Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string. using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); String responseString = reader.ReadToEnd(); } " i can't vote.so wrote this. A: You can create a StreamReader around the stream, then call StreamReader.ReadToEnd(). StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream()); var responseData = responseReader.ReadToEnd(); A: You can use StreamReader.ReadToEnd(), using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); String responseString = reader.ReadToEnd(); } A: As @Heinzi mentioned the character set of the response should be used. var encoding = response.CharacterSet == "" ? Encoding.UTF8 : Encoding.GetEncoding(response.CharacterSet); using (var stream = response.GetResponseStream()) { var reader = new StreamReader(stream, encoding); var responseString = reader.ReadToEnd(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7543324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "86" }
Q: Will I see decreased network throughput if I bind many sockets on the same port? I am creating 3 sockets(sender sockets) to send my data to a remote single socket using UDP. I have bound all these 3 sender sockets on the same single port. Will this design of binding all the 3 sender sockets on the same port decrease the throughput efficiency of sending packets? Or should I create a new port and a new socket for each of my threads? My goal is send the packets as quickly as possible and keep the network constantly busy. Important: I am using UDP sockets. Unlike TCP sockets which have a different process created for each of its child threads. A: I can't think of any reason why binding multiple sockets to the same port would affect sending efficiency one way or the other. Since your CPU is (presumably) much faster than your network card, your limiting factor is going to be the speed at which your Ethernet hardware can push data onto the network, nothing else. Of course the only real way to know for sure is to try it both ways and see if you see any differences in throughput; but I would be surprised if you did. (Note that when sending UDP packets it is important not to try to send them faster than than the network card can transmit them, or the kernel will simply drop the UDP packets it doesn't have room in its send-buffer for. Specifically, you need to either send using blocking I/O (in which case the send() call won't return until the kernel has enough send-buffer space to send the packet you asked it to send), or use non-blocking I/O but only send a packet when the UDP select()'s (or poll()s or whatever) as ready-for-write. Otherwise you will get an amazing fast "send rate" where 99% of your packets were sent only to the bit-bucket ;^)) A: The number of sockets per port is irrelevant. Ports aren't a physical entity and they don't have bandwidths to be divided among their users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7543326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Controller's Action name in View What is the correct way to get the name of the Action returning the View in MVC3? I am using ViewContext.Controller.ValueProvider.GetValue("action").RawValue to return the name of the Action (Method), which is creating the View in MVC3. I return this in a Partial View, which is included in the View returned by the Action. It works fine for Index, but, when I try to use it for another method name, it always evaluates to false. In the immediate window I get the following results: ViewContext.Controller.ValueProvider.GetValue("action").RawValue "Edit" ViewContext.Controller.ValueProvider.GetValue("action").RawValue == "Edit" false Which is highly confusing, because the first statement evaluates to a string with value "Edit", while comparing this to a string "Edit" returns false? Bizarre... A: RawValue is an object, so RawValue == "..." calls Object.op_Equality, which comparse by reference rather than by value. Call ViewContext.RouteData.GetRequiredString("action")
{ "language": "en", "url": "https://stackoverflow.com/questions/7543327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Explanation of plain SQL to get user_meta from Wordpress I have below SQL command that works to get user_meta details in Wordpress. This works fine to get the data in one table and one row per user info with info for each user in each column but I'm just trying to find out how this works. Can anyone be kind enough to explain below?: SELECT u.id, u.user_login, MIN(CASE m.meta_key WHEN 'title' THEN m.meta_value END) AS title, MIN(CASE m.meta_key WHEN 'first_name' THEN m.meta_value END) AS first_name, MIN(CASE m.meta_key WHEN 'last_name' THEN m.meta_value END) AS last_name, MIN(CASE m.meta_key WHEN 'suburb' THEN m.meta_value END) AS phone, MIN(CASE m.meta_key WHEN 'state' THEN m.meta_value END) AS state, MIN(CASE m.meta_key WHEN 'country' THEN m.meta_value END) AS country, MIN(CASE m.meta_key WHEN 'postcode' THEN m.meta_value END) AS postcode, MIN(CASE m.meta_key WHEN 'contact_no' THEN m.meta_value END) AS contact_no, MIN(CASE m.meta_key WHEN 'email' THEN m.meta_value END) AS email, MIN(CASE m.meta_key WHEN 'occupation' THEN m.meta_value END) AS occupation, MIN(CASE m.meta_key WHEN 'workplace' THEN m.meta_value END) AS workplace, MIN(CASE m.meta_key WHEN 'maternitybg' THEN m.meta_value END) AS maternitybg, MIN(CASE m.meta_key WHEN 'trainingdate' THEN m.meta_value END) AS trainingdate, MIN(CASE m.meta_key WHEN 'traininglocation' THEN m.meta_value END) AS traininglocation, MIN(CASE m.meta_key WHEN 'coltraining' THEN m.meta_value END) AS coltraining, MIN(CASE m.meta_key WHEN 'trainingyear' THEN m.meta_value END) AS trainingyear, MIN(CASE m.meta_key WHEN 'coltraining' THEN m.meta_value END) AS coltraining, MIN(CASE m.meta_key WHEN 'isinstructor' THEN m.meta_value END) AS isinstructor, MIN(CASE m.meta_key WHEN 'gender' THEN m.meta_value END) AS gender, MIN(CASE m.meta_key WHEN 'idf_indig_tsi' THEN m.meta_value END) AS idf_indig_tsi, MIN(CASE m.meta_key WHEN 'idf_ct_ld' THEN m.meta_value END) AS idf_ct_ld, MIN(CASE m.meta_key WHEN 'comments' THEN m.meta_value END) AS comments FROM wp_users u LEFT JOIN wp_usermeta m ON u.ID = m.user_id AND m.meta_key IN ('title', 'first_name', 'last_name', 'suburb', 'state', 'country', 'postcode', 'contact_no', 'email', 'occupation', 'workplace', 'maternitybg', 'trainingdate', 'traininglocation', 'coltraining', 'isinstructor', 'gender', 'idf_indig_tsi', 'idf_ct_ld', 'comments') GROUP BY u.ID Thanks for your help! A: Not sure what part you want explained but anyway, here we go This part is about specifying what columns you want: SELECT u.id, u.user_login, Followed by the part where you include the source tables: FROM wp_users u LEFT JOIN wp_usermeta m ON u.ID = m.user_id By using left join you make sure that you will get rows from wp_users even if there are no matches in wp_usermeta. ON u.ID = m.user_id connect the rows between wp_users and wp_usermeta. Apparently, wp_usermeta is key-value table and this limits the keys you are interested in. AND m.meta_key IN ('title', 'first_name', 'last_name', 'suburb', 'state', 'country', 'postcode', 'contact_no', 'email', 'occupation', 'workplace', 'maternitybg', 'trainingdate', 'traininglocation', 'coltraining', 'isinstructor', 'gender', 'idf_indig_tsi', 'idf_ct_ld', 'comments') Finally there is group by clause that will make the output one row for each distinct value of u.ID. GROUP BY u.ID There is a little trick in the field list as well using a case statement. MIN(CASE m.meta_key WHEN 'title' THEN m.meta_value END) AS title, First you get the value m.meta_value if the m.meta_key equals 'title', otherwise the value will by null. CASE m.meta_key WHEN 'title' THEN m.meta_value END If there are more than one 'title' keys in wp_usermeta for a given user you will get the min() value. Title 'Bus driver' will be picked before title 'Cab driver'. MIN(CASE m.meta_key WHEN 'title' THEN m.meta_value END) And at last you give the column retrieved a column alias title. MIN(CASE m.meta_key WHEN 'title' THEN m.meta_value END) AS title,
{ "language": "en", "url": "https://stackoverflow.com/questions/7543330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Shortcut key to open a class or a file in VS2010? I've googled around for an answer to this - can't find one. In Intellij, if you want to open an arbitrary class, you press ctrl-n, you get a little text box where you can type the name of a class or just the camel caps initials or some wildcards. Same with files - ctrl-shift-n. What is the keystroke to do this in Visual Studio 2010? A: Press Ctrl + ,
{ "language": "en", "url": "https://stackoverflow.com/questions/7543331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: EF Gives Odd Property Names in Entity I've created a Companies table with foreign key (ParentCompaniesId) to the primary key of the same table. When I generate an Entity Framework model from the database, it adds a ParentCompany property, just as I want. However, it also adds a collection property called Companies1 to represent the many side of this same relationship. Why Companies1? Is there any way to have it name this property Companies instead? My table is similar to the one scripted below. CREATE TABLE [dbo].[Companies]( [CompaniesId] [int] IDENTITY(1,1) NOT NULL, [ParentCompaniesId] [int] NULL, [Description] [nvarchar](100) NOT NULL, CONSTRAINT [PK_Companies] PRIMARY KEY CLUSTERED ( [CompaniesId] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO ALTER TABLE [dbo].[Companies] WITH CHECK ADD CONSTRAINT [FK_Companies_Companies] FOREIGN KEY([ParentCompaniesId]) REFERENCES [dbo].[Companies] ([CompaniesId]) GO ALTER TABLE [dbo].[Companies] CHECK CONSTRAINT [FK_Companies_Companies] GO A: This is bug in the designer - actually the only thing in conceptual model I'm aware of which doesn't survive update from database. There is not much to do with this. You can use simple script / app. which will be run manually after Update from database to replace all these unexpected names with expected one. You can also give up with Update from database and maintain EDMX manually (it is XML file).
{ "language": "en", "url": "https://stackoverflow.com/questions/7543335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }