text
stringlengths
8
267k
meta
dict
Q: Splitting a large XML file in two using C# console app I need to split am XML file (~400 MB) in two, so that a legacy app can process the file. At the moment its throwing an exception when the file is over around 300 MB. As I can't change the app which is doing the processing, I thought I could write a console app to split the file in two first. What's the best way of doing this? It needs to be automated so I can't use a text editor, and I'm using C#. I suppose the considerations are: * *writing a header to the new files after the split *finding a good place to split (not in middle of 'object') *closing off tags and file correctly in first file, opening tags correctly in second file Any suggestions? A: You might want to consider making a full copy of the file and then deleting elements from each. You will have to decide at what level the deletions could occur. It should then be fairly straightforward, from a count of how many elements have been deleted from FileA, to identify how many (and from what starting point) should be deleted from FileB. Is that feasible for your circumstance? I have put together the following to describe my thinking. It is not tested, but I would value the comments of the group. Downvote me if you want but I would prefer constructive criticism. using System.Xml; using System.Xml.Schema; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { SplitXML(args[0], args[1]); } private static void SplitXML(string fileNameA, string fileNameB) { int deleteCount; XmlNodeList childNodes; XmlReader reader; XmlTextWriter writer; XmlDocument doc; // ------------- Process FileA reader = XmlReader.Create(fileNameA); doc = new XmlDocument(); doc.Load(reader); childNodes = doc.DocumentElement.ChildNodes; deleteCount = childNodes.Count / 2; for (int i = 0; i < deleteCount; i++) { doc.DocumentElement.RemoveChild(childNodes.Item(0)); } writer = new XmlTextWriter("FileC", null); doc.Save(writer); // ------------- Process FileB reader = XmlReader.Create(fileNameB); doc = new XmlDocument(); doc.Load(reader); childNodes = doc.DocumentElement.ChildNodes; for (int i = deleteCount + 1; i < childNodes.Count; i++) { doc.DocumentElement.RemoveChild(childNodes.Item(deleteCount +1)); } writer = new XmlTextWriter("FileD", null); doc.Save(writer); } } } A: The "best" way is likely to be based on XmlReader and XmlWriter. Using these "streaming" APIs avoids needing to load the whole XML object model in memory (and with DOM –XmlDocument– that can need considerably more memory than the text data). Using these APIs is harder than just loading the document: your implementation needs to track the context (eg. current node and ancestor list), but in this case that wouldn't be complex (just enough to open the elements to the current state when opening each output document). A: If it's pure C#, running it as a 64-bit process might solve the problem for no effort at all (assuming you have a 64-bit Windows at hand).
{ "language": "en", "url": "https://stackoverflow.com/questions/7513080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Static constant members in a class C++ How do I declare static constant values in C++? I want to be able to get the constant Vector3::Xaxis, but I should not be able to change it. I've seen the following code in another class: const MyClass MyClass::Constant(1.0); I tried to implement that in my class: static const Vector3 Xaxis(1.0, 0.0, 0.0); However I get the error math3d.cpp:15: error: expected identifier before numeric constant math3d.cpp:15: error: expected ‘,’ or ‘...’ before numeric constant Then I tried something more similar to what I'd do in C#: static Vector3 Xaxis = Vector3(1, 0, 0); However I get other errors: math3d.cpp:15: error: invalid use of incomplete type ‘class Vector3’ math3d.cpp:9: error: forward declaration of ‘class Vector3’ math3d.cpp:15: error: invalid in-class initialization of static data member of non-integral type ‘const Vector3’ My important parts of my class so far look like this class Vector3 { public: double X; double Y; double Z; static Vector3 Xaxis = Vector3(1, 0, 0); Vector3(double x, double y, double z) { X = x; Y = y; Z = z; } }; How do I achieve what I'm trying to do here? To have a Vector3::Xaxis which returns Vector3(1.0, 0.0, 0.0); A: class Vector3 { public: double X; double Y; double Z; static Vector3 const Xaxis; Vector3(double x, double y, double z) { X = x; Y = y; Z = z; } }; Vector3 const Vector3::Xaxis(1, 0, 0); Note that last line is the definition and should be put in an implementation file (e.g. [.cpp] or [.cc]). If you need this for a header-only module then there is a template-based trick that do it for you – but better ask separately about that if you need it. Cheers & hth., A: You need to initialize static members outside of class declaration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the Font styles and face in Android? I want to change the font face and styles in android. How to do this? Am using emulator. Is this possible to change in emulator. Is there any permissions available to do that. Thanks in Advance. A: You can change the font style and font face in your XML files. For example if you want to change your Button's style and face. Choose your button in xml and follow the below methods : Button -> Right Click -> Properties -> Typeface and style Hope this will help you. A: If you want to change in code ; This is good reference; http://mobile.tutsplus.com/tutorials/android/customize-android-fonts/ A: in android only five fonttype-face TypeFace Typeface.DEFAULT Typeface.MONOSPACE Typeface.SANS_SERIF Typeface.DEFAULT_BOLD Typeface.SERIF and font-type Typeface.NORMAL Typeface.BOLD Typeface.BOLD_ITALIC Typeface.ITALIC you can use like as textView.setTypeface(Typeface.DEFAULT, Typeface.BOLD); and other way is you can download any .ttf file and put it in asset folder and use like as this Typeface type=Typeface.createFromAsset(context.getAssets(), "DroidSansMono.ttf"); textView.setTypeface(type, null); A: what you want?. Do you want to change the font face and styles of text in textview. if yes then use this Typeface type = Typeface.createFromAsset(this.getAssets(),"your font name"); text.setTypeface(type); and for styles use these links: * *Style-resource *Themes A: If you want to use a font which is not default (like "Helvetica") for the text in Android application then put the font file(Helvetic.ttf) in assets folder and do use this code as below: Typeface tf= Typeface.createFromAsset(getAssets(), "Helvetica.ttf"); TextView mTextView =(TextView) findViewById(R.id.text); mTextView.setTypeface(tf); A: if u want to use custom font jus download .ttf file and put the file into assets folder and use like this: TextView tv=(TextView)findViewById(R.id.textView); Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/arial.ttf"); tv.setTypeface(tf);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Custom image enum for MessageBoxResult I try to create a custom MessageBoxImage for the build in MessageBoxResult For the custom MessageBoxImage enumeration, I have: public enum CustomBoxImage { Foo = new BitmapImage(new Uri(@"pack://application:,,,/MySoftware;component/Images/foo.png")) } and the MessageBoxResult, I have: MessageBoxResult mrb = MessageBox.Show( "This will kill you. Are you sure?", "Kill you", MessageBoxButton.YesNo, CustomBoxImage.Foo); But it gives me this error: Cannot convert from "...CustomBoxImage" to "System.Windows.MessageBoxImage' How can I insert a customized image enumeration into MessageBoxResult? Or, is it even possible? A: You can't customize the message boxes beyond the given options. If you need a fully customized one, you can use a 3rd party component. You can even make a window look fully like a message box and customize it if you really need to. A: You can't change the signature of the Show method but you can create a converter between your enumeration and the MessageBoxImage enumeration. if you want to use things that is not provide by the MessageBox, you can create your own messagebox.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dictionary component in Java I am looking for an open source dictionary, The user in my application enter city name in Hebrew, and I want to translate it to English. I have another component that can use only English city names. Where can I find such a component? A: Did you try to use one of the Map implementations? For example HashMap or TreeMap? I'd even say more: just store all localized names in resource files (properties format) and use ResourceBundle to access them. for example call your file towns.properties tel-aviv = Tel Aviv jerusalem = Jerusalem The Hebrew version of your file is towns-iw.properties tel-aviv = תל אביב jerusalem = ירושלים Now using ResourceBundle API create Map that contains direct associations between English and Hebrew names. Then just use it. A: I guess that your main problem is not how to match Hebrew names to English ones (once you have a list of pairs), but actually how to obtain the data of matchings between Hebrew and English names. I'll also guess that you are aiming for cities in Israel if you are speaking about hebrew names. Therefore I'd try the statistics from the central bureau of statistics - they have a table with hebrew city names, and their english corressponding names. You can find it here: http://www.cbs.gov.il/ishuvim/ishuvim_print.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7513091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show alert dialog in home screen? I am trying to run alarm which make alert dialog run in home screen showing . i.e when the application is closed, and when the event time is reached, the alert dialog shows the title of the event and rings alarm infinitely. If the button in alert dialog is clicked, then the alarm goes off, My code is as follows: void doReminderWork(Intent intent) { ToDoApplicationActivity ap = new ToDoApplicationActivity(); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); Intent notificationIntent = new Intent(this, ToDoApplicationActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT); Notification note = new Notification(R.drawable.alarm, "...Calendar Alarm...", System.currentTimeMillis()); note.setLatestEventInfo(this,"Event : ", ap.title1, pi); note.defaults |= Notification.DEFAULT_SOUND; note.flags |= Notification.FLAG_AUTO_CANCEL; int id = 123456789; manager.notify(id, note); Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(this, alert); } catch (IllegalArgumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalStateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) { mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mMediaPlayer.setLooping(false); try { mMediaPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mMediaPlayer.start(); } After this if i give alert dialog code to stop media player, i know it cant stop playing the alarm. Here, even when the application is closed, i need to show the alert dialog. I m trying this for past 2 days. I'm Getting Following Exception: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application Any help is highly appreciated and thanks in advance... A: When you get alarm notification then you can show alert dialog in the activity which has no view by starting the activity. This is what you wanted.? By showing alert in the activity with no view you will see only alert dialog on the home screen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Animating View - compatible for iPad 3.2 and 4.2 version Two views need to be resized when a button is clicked in iPad . I Tried it with following code [UIView animateWithDuration:1.0 animations:^{ //Target Rect of the View will be given here }]; It works fine with iPad4.2 ,but Crashes with 3.2 version(Incompatible). On Googling found that 3.2 version supports only Animating Views (W/O Blocks) Source: http://developer.apple.com/library/iOS/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/clm/UIView/beginAnimations:context: They have mentioned its not advisable to use it for 4.0 and later How can I achieve animating the views for both 3.2 and 4.2. A: I you really need to support versions below 4.0, you can use this: [UIView beginAnimations:@"animation" context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveLinear]; [UIView setAnimationDuration:1.0]; //In seconds //Here do your stuff int newPosY = myImage.frame.origin.y - 10; [myImage setFrame:CGRectMake(self.frame.origin.x, newPosY, myImage.frame.size.width, myImage.frame.size.height)]; [UIView commitAnimations]; That moves an UIImageView 10 pixels up. Also check UIView reference to see all the possibilities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Form with radio buttons & checkboxes sending to php Harmiih really helped me with my script (http://stackoverflow.com/questions/7510546/html-form-name-php-variable). Basically I have a table with questions. The form retrieves the questions from the table and then I need the selected answers to go to answer.php. Everything is working with the radio butttons but with the check boxes it's only sending the last selected checkbox. Can someone please help me? form $sql1="SELECT * FROM ex_question WHERE test_name = '$tid' AND q_type = 'mr' ORDER BY RAND() LIMIT 5"; $result1=mysql_query($sql1); echo "<form method='post' action='answer.php'>"; while($row1 = mysql_fetch_array($result1)) { $test_name=$row1['test_name']; $q_nr=$row1['q_nr']; $q_type=$row1['q_type']; $question=$row1['question']; $option1=$row1['option1']; $option2=$row1['option2']; echo "<P><strong>$q_nr $question</strong><BR>"; if ($q_type != 'mr') { if($option1!="") { echo "<input type='radio' name='question[$q_nr]' value='$option1'>$option1<BR>"; } else { echo ''; } if($option2!="") { echo "<input type='radio' name='question[$q_nr]' value='$option2'>$option2<BR>"; } else { echo ''; } } else { if($option1!="") { echo "<input type='checkbox' name='question[$q_nr]' value='$option1'>$option1<BR>"; } else { echo ''; } if($option2!="") { echo "<input type='checkbox' name='question[$q_nr]' value='$option2'>$option2<BR>"; } else { echo ''; } } echo "<BR>"; echo "<BR>"; echo "</p>"; } echo "<input type='submit' value='Send Form'>"; echo "</form>"; answer.php <?php //Key is $q_nr and $answer is selected $option foreach($_POST['question'] as $key => $answer) { echo $key; echo $answer; } ?> A: You need to have different name values in checkboxes. For example name='question1[$q_nr]' and name='question2[$q_nr]'. The same name works only with grouping elements witch radio buttons are. Or passing them as arrays: name='question[$q_nr][1]' and name='question[$q_nr][2]' A: You can use this as name: name="question[$q_nr][]" This will make sure you return an array containing all values of the selected checkboxes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hash to Array converting I need this Hash {"peter" => ["apple", "orange", "mango"], "sandra" => ["flowers", "bike"]} convert to this Array: [["peter", "apple"], ["peter", "orange"], ["peter", "mango"], ["sandra", "flowers"], ["sandra", "bike"]] Now I have got this solution my_hash.inject([]){|ar, (k,v)| ar << v.map{|c| [k,c]}}.flatten(1) But I believe here is more elegant solution with those zip or transpose magick :) A: You are right to be suspicious about Enumerable#inject solutions. In Ruby, inject/reduce is somewhat abused, we must be careful and choose the right abstraction (map, select, zip, flatten...) if they fit the problem at hand. In this case: h = {"peter" => ["apple", "orange", "mango"], "sandra" => ["flowers", "bike"]} h.map { |k, vs| vs.map { |v| [k, v] } }.flatten(1) #=> [["peter", "apple"], ["peter", "orange"], ["peter", "mango"], ["sandra", "flowers"], ["sandra", "bike"]] But if you want to use Enumerable#zip don't let anyone stop you ;-) h.map { |k, vs| [k].cycle(vs.size).zip(vs) }.flatten(1) And as @steenslag says, also: h.map { |k, vs| [k].product(vs) }.flatten(1) So at the end we can write: h.flat_map { |k, vs| [k].product(vs) } A: h.inject([]){|a,(k,vs)| a+vs.map {|v| [k,v]}} You could also use this version h.inject([]){|a,(k,vs)| a+=vs.map {|v| [k,v]}} Which is most efficient because it use the same list rather than creating a new one at each iteration. However it feels wrong (for me) to use inject and modify a variable in place. An each version would do the same. a = []; h.each {|k,vs| a+=vs.map {|v| [k,v]}} It's slightly shorter and as expressive. A: With zip hash.inject([]){ |ar, (k,v)| ar << ([k]*v.size).zip(v) } A plausible solution using transpose too: [ hash.keys.map{|k| [k]*hash[k].size }.flatten, hash.keys.map{|k| hash[k] }.flatten ].transpose Take into account that: * *hash.keys should return the keys in the same order in both cases, so don't use it in other language unless you are sure of this. *I would go with the first option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why undefined method "has_many" in Rspec example? I am playing around with an Example on testing a has_many through association in RSpec. I am getting a 1) Foo specifies items Failure/Error: subject.should have_many(:items) NoMethodError: undefined method `has_many?' for # # ./spec/models/foo_spec.rb:10 My question: Why would has_many be undefined? The spec is: describe Foo do it "specifies items" do subject.should have_many(:items) end end My models are: foo.rb: class Foo < ActiveRecord::Base has_many :bars has_many :items, :through => :bars end bar.rb: class Bar < ActiveRecord::Base belongs_to :foo belongs_to :item end and item.rb: class Item < ActiveRecord::Base has_many :foos, :through => :bars has_many :bars end A: Well, there is no has_many? method on model objects. And rspec-rails does not provide such matcher by default. However, shoulda-matchers gem does: describe Post do it { should belong_to(:user) } it { should have_many(:tags).through(:taggings) } end describe User do it { should have_many(:posts) } end (example from shoulda-matchers documentation) Just add gem 'shoulda-matchers' to your Gemfile and you will be able to use that syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: "Auto-Focus" feature for the "Camera" module of my Android application I have been working with the CAMERA module for my application since few days. I have customized the complete camera module instead of invoking the hardware inbuilt mobile camera through an intent. I have used the call backs for shutter, picture etc Now I am trying to add the ZOOM and AUTO-FOCUS features to this customized camera. Can anybody please let me know the way to add the ZOOM and AUTO-FOCUS features along with the required permissions which should be mentioned in the manifest file..hope i will be helped as soon as possible. A: Couple of observations from my end. 1) Camera.autoFocus is a one-time call, applicable when Camera.getParameters.getFocusMode() is either FOCUS-MODE-AUTO or FOCUS-MODE-MACRO, in other cases you don't need to invoke the autoFocus method. See the API Docs and follow them devotedly. 2) By one-time call, it means that this method does not register the AutoFocusCallback instance to receive notifications continuously. 3) Rather, FOCUS-MODE-AUTO isn't even a dynamic and continuous focus constant. Instead, you might want to use FOCUS-MODE-EDOF or FOCUS-MODE-CONTINUOUS-PICTURES depending on the API Level and the SDK version that you are using and building for. 4) There is every possibility that the actual Device Camera may not support some FOCUS-MODE constants, such as EDOF or INFINITE. Always make sure when you are creating the camera-parameters, you check for getSupportedFocusModes and use the applicable constants. 5) Calling camera.autoFocus just before camera.takePicture can bloat the resulting jpeg-byte-array in the PictureCallBack to at least 50% more than it's original size. Not calling autoFocus() explicitly may sometimes cause the previous autoFocus() to end at a very low-resolution that may result a jpeg-byte-array length of only a 10K bytes, resulting in a null image bitmap from the BitmapFactory. 6) Regarding auto-focus permissions, see the API Docs. 7) Regarding Zoom, it is not as complicated as implementing the Auto-focus feature. Depending on screen-interaction such as slider, or hardware keys such as volume-keys, you could implement a ZoomChangeListener that you can register with the Camera as soon as the Camera instance is received from open(int cameraId). A: For zoom (2x): Camera.Parameters parameters = camera.getParameters(); parameters.set("zoom", "2.0"); parameters.set("taking-picture-zoom", "20"); For api level > 5 use the api's like setZoom() etc For autofocussing (taken from zxing) public final boolean onKeyDown(int keyCode, KeyEvent event) { synchronized(this) { if (!bIsPictureTaking) { if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_CAMERA) { if (!bIsPictureTaking && !bIsAutoFocusStarted){ YourAutoFocusCallback autoFocusCallBack = new YourAutoFocusCallback(); camera.autoFocus(autoFocusCallBack); . final class YourAutoFocusCallback implements Camera.AutoFocusCallback { private static final long AUTOFOCUS_INTERVAL_MS = 1500L; private final CameraConfigurationManager configManager; private boolean reinitCamera; private Handler autoFocusHandler; private int autoFocusMessage; AutoFocusCallback(CameraConfigurationManager configManager) { this.configManager = configManager; } void setHandler(Handler autoFocusHandler, int autoFocusMessage) { this.autoFocusHandler = autoFocusHandler; this.autoFocusMessage = autoFocusMessage; } public void onAutoFocus(boolean success, Camera camera) { if (autoFocusHandler != null) { Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success); autoFocusHandler.sendMessageDelayed(message, AUTOFOCUS_INTERVAL_MS); autoFocusHandler = null; configManager.setDesiredCameraParameters(camera); } else { } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Represent a List of strings in GWT as widget in an editor I'm building a GWT app. I want to associate a list of items (List < String >) to an editor. Is there any built in widgets that support editing list of items? Something that will show comma separated values and will know how to render them back to the proxy. A: Yes, take a look at CellTable. A: You can use the CellList widget to display a list of items. If you want to present them horizontal add float:left as style to the individual items in the Celllist style items: cellListEvenItem and cellListOddItem. A: You can implement your custom class for CellList and/or CellTable adapting for your needs. All components from gwt extends Widget, and can be extended too. A: Ended up with this Facebook auto complete style http://raibledesigns.com/rd/entry/creating_a_facebook_style_autocomplete And demo http://demo.raibledesigns.com/gwt-autocomplete/
{ "language": "en", "url": "https://stackoverflow.com/questions/7513124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to convert array of words to make a sentence? I feel uncomfortable asking, but how do I convert an array of words to make a sentence ? I keep finding the other way round. Something like: var a = ['hello', 'world']; and obtain : hello world A: Just join the elements of the array into a string using a space as a separator: var sentence = a.join(" "); https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join A: This doesn't need jquery. Javascript has a very simple way of doing this with the join function: a.join(" "); A: Do you mean something like? arr.join(" ");
{ "language": "en", "url": "https://stackoverflow.com/questions/7513129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Run bash command in Cygwin from another application From a windows application written on C++ or python, how can I execute arbitrary shell commands? My installation of Cygwin is normally launched from the following bat file: @echo off C: chdir C:\cygwin\bin bash --login -i A: From Python, run bash with os.system, os.popen or subprocess and pass the appropriate command-line arguments. os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"') A: The following function will run Cygwin's Bash program while making sure the bin directory is in the system path, so you have access to non-built-in commands. This is an alternative to using the login (-l) option, which may redirect you to your home directory. def cygwin(command): """ Run a Bash command with Cygwin and return output. """ # Find Cygwin binary directory for cygwin_bin in [r'C:\cygwin\bin', r'C:\cygwin64\bin']: if os.path.isdir(cygwin_bin): break else: raise RuntimeError('Cygwin not found!') # Make sure Cygwin binary directory in path if cygwin_bin not in os.environ['PATH']: os.environ['PATH'] += ';' + cygwin_bin # Launch Bash p = subprocess.Popen( args=['bash', '-c', command], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() # Raise exception if return code indicates error if p.returncode != 0: raise RuntimeError(p.stderr.read().rstrip()) # Remove trailing newline from output return (p.stdout.read() + p.stderr.read()).rstrip() Example use: print cygwin('pwd') print cygwin('ls -l') print cygwin(r'dos2unix $(cygpath -u "C:\some\file.txt")') print cygwin(r'md5sum $(cygpath -u "C:\another\file")').split(' ')[0] A: Bash should accept a command from args when using the -c flag: C:\cygwin\bin\bash.exe -c "somecommand" Combine that with C++'s exec or python's os.system to run the command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Silverlight refresh an Image depending on a variable stored in IsolatedStorage I'm pretty new in silverlight and I have some problems with my application.I keep the application date in database and in IsolatedStorage. I have an Image control on the top of the UI where the user can always see the application current date.I'm using image because I've created some stylish images to represent the date in mm.yyyy format. I set the URI of the image control in mainpage Authentication_LoggedIn(): //setez luna curenta in isolatedStorage adminUtilizContext.GetSetariParticulare(4, 0, (op) => { foreach (var item in op.Value) { if (IsolatedStorageSettings.ApplicationSettings.Contains("lunaCurenta")) IsolatedStorageSettings.ApplicationSettings["lunaCurenta"] = item.Substring(2); else IsolatedStorageSettings.ApplicationSettings.Add("lunaCurenta", item.Substring(2)); Uri uri; uri = new Uri("/Indeco.SIEF;component/Images/Calendar/"+item.Substring(2)+".png", UriKind.RelativeOrAbsolute); dataLuna.Source = new BitmapImage(uri); } }, null); The xaml looks like this: <StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right"> <Image Name="dataLuna" HorizontalAlignment="Right"/> </StackPanel> It works fine, but the problem appears when the user changes the current date. In database and IsolatedStorage is stored correctly. I'm changing the image source but the new image doesn't appear until I manually refresh the page. Can you please tell me how can I do this automatically without having to manually refresh the page! Best regards. The code where the user changes the date is in ViewModel(CurrentConfigurationViewModel.cs) of the coresponding UI(CurrentConfigurations.xaml).There is a combobox with the months and SelectedItemChanged automatically updates the database and the IsolatedStorage.That's where I've put the code you saw in my previous comment.There is a NumericUpDown control for the year too that works the same.But for now let's talk about the month and after that i'll do it for the year myself:D! thank's again As you can see in this picture when the user logged in the application date was april 2011(up right) and after I modify the month it stil displays the old date and I verified in the Db, in isolated storage and it seems to be ok.There you can see the code I wrote to update the Image source too. A: You could try to set up a Property which holds the image and then bind the Image Source to this property. Your class needs to implement INotifyPropertyChanged interface and then you can inform your Image control that your Property Changed and it will reload the Image. I hope this helps. :) If that's your code then you are generating a whole new MainPage and setting it's dataLuna ImageSource, and not the original pages dataLuna controls. I'm happy i could help. A: My suggestion would be to fire an event from the page/control where the date change happens. In the main page you can subscribe to the event and reload the image. Hope this helps. A: Hi all of you guys and thanks again for you're interest!I've solved my problem like that: var mp = ((Application.Current.RootVisual as ContentControl).Content as UserControl).Content as Indeco.SIEF.MainPage; Debug.Assert(mp != null); Uri uri; uri = new Uri("/Indeco.SIEF;component/Images/Calendar/" + id.ToString() + ".png", UriKind.RelativeOrAbsolute); mp.dataLuna.Source = new BitmapImage(uri);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to stop PHP SoapClient converting s1:char arguments to 0 or 1 in request PHP's Soap client appears to be handling arguments with type s1:char incorrectly when building the request. The Soap API requires either 'Y' or 'N' but in the request XML I get '0'. (Passing Bool true results in '1' but that isn't accepted as API in place of 'Y'). I'm using PHP Version 5.3.8 with the native Soap Client Here's my PHP $this->soapClient = new SoapClient( $client->wsdl, array( 'soap_version' => SOAP_1_2, 'trace' => true ) ); $result = $this->soapClient->SomeSoapMethod(array( 'sSessionKey' => $sessionKey, // other string and int args that work fine here 'cReturnNonSeats' => 'Y' // API wants 'Y' or 'N' )); The relevant XML node in the request XML: <ns1:cReturnNonSeats>0</ns1:cReturnNonSeats> And from the WSDL: <s:complexType> <s:sequence> <s:element minOccurs="1" maxOccurs="1" name="cReturnNonSeats" type="s1:char" /> </s:sequence> </s:complexType> Without getting into building XML manually, is there a way I can have some control over how these arguments are typecast? A: This is how I got around it though I'd like to now why SoapClient is converting that string to int. Instead of 'Y' in my array of parameters, I used: new SoapVar('Y', XSD_ANYTYPE)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Online Forms: Making Drop Down Box(es) Available When Check Box Selected I'm looking for some help with forms! Having learned a decent bit of HTML and CSS, I'm still a bit of a newbie when it comes to forms and the server-side scripting behind them. I hope my question is fairly self-explanatory, but to clarify what I am trying to achieve: * *I would to create a form with the options 'Default' or 'Custom' colors on check boxes (or radio buttons) *If the user selects 'Custom' I would like a drop down menu to become available, with a list of the colors to choose from *Ideally I would like the drop down box to be present in the form, but 'greyed out' (i.e. non-selectable) until 'Custom' is checked, rather than just appearing (although this is a 'nice to have') My questions then, are 'what language would I use to achieve this? (i.e. PHP?)' and 'how!?' Thanks in advance for anyone that can help me. Obviously I'd like a solution that is 'good to go', but I'm happy to be pointed in the direction of further reading on the subject, as I like to learn and I just can't seem to find out what the 'right' language and learning is for this... Jim. A: You will need to learn something about javascript, nothing to do with server-side language (i.e. PHP). You have to watch for selected property for select boxes. An important note, all things you have mentioned are client side, but when you will press OK on your form what will happen after depends on your server-side language. And here is when PHP become useful. However you only asked for something that is client like, so start studying javascript before anything else. Good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7513140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RubyTest in Sublime Text 2 I am trying to get RubyTest to work in Sublime Text 2. I followed the Instruction on the Github Readme and get the following error. Does anyone know how I could fix this? /bin/sh: rspec: command not found A: This is most likely due to using RVM. What is the output of which rspec on your command line? Also of note, just because you've included rspec-rails in a Gemfile, does not mean that 'rspec' is an executable program that your system knows about. You can edit the RubyTest.sublime.settings to refer to your particular path to the rspec executable and it should work. Unfortunately, this has the nasty side effect of being tied to one particular version of Ruby. If you're using RVM to switch between versions, you'll have to update your sublime.settings. One work around, is to run Sublime from the command line. A: To get this to work you only need to change one setting in the RubyTest package in sb2. If you are using rvm, your rspec gem is installed through rvm and is not found in /bin/sh So you need to set the RubyTest package for Sublime Text 2 to automatically check for your rvm environment variables. What to change: 1) In Sublime Text 2, go to Preferences|Browse Packages. This will open up your packages directory. 2) Open the 'RubyTest' directory and look for the file 'RubyTest.sublime-settings'. 3) find the line that says: "check_for_rvm": false, and change it to: "check_for_rvm": true, save the change. 4) That's it. It should now work. Good Luck A: Running Sublime Text 2(2165) with RubyTest plugin. Ruby and Gems managed with rbenv (0.3.0). First attempt to use RubyTest gave the following error: /bin/sh: rspec: command not found From the command line I ran which rspec and it returned no results. After some digging, I read that bundle install does not put the executables in your $PATH. Alternative executable paths not picked up by shims sometimes In order to use the executible outside the app, I had to delete the gem installed by bundler and then install it manually. gem uninstall rspec gem install rspec followed by rbenv rehash (Note you will need to run bundle inside your app so it updates the location of the gem) This had to be performed for each version of ruby I have under rbenv control. Now when I run which rspec it is found in the path and RubyTest is able to grab it without any problems. fwiw, I had to repeat the steps for cucumber as well. To use all of RubyTests' features, ruby, cucumber and rspec executables need to be in your $PATH (for rbenv it is ~/.rbenv/shims/). A: This worked for me: If you're using RVM, open a project with command line from the project's folder: subl . Then, it'll hook the ruby version and gems. A: Try change the path to usr/local/bin/ I wrote a post on Sublime Text Build Scripts which should show you how to do this. http://wesbos.com/sublime-text-build-scripts/ A: Same issue for me. With rspec 1.3.2 what I just did to fix it is to edit the RubyTest.sublime.settings file in the plugin folder, changing the "ruby_rspec_exec" key from: "ruby_rspec_exec": "rspec" to "ruby_rspec_exec": "spec" It really depends on the location where you have your rspec executable file... A: I had the same problem after installing RubyTest by cloning from the repo. I simply uninstalled and reinstalled the package inside Sublime using Package Control, then everything worked fine. A: You can see a summary of this issue here: https://github.com/maltize/sublime-text-2-ruby-tests/issues/36 Essentially, what Jim said was correct, you're running RVM or some other ruby vm manager that similarly monkeys with your PATH. Following the directions from this issue I did the following: Install the binaries in my project bundle install --binstubs Add the path to my .bashrc and source it echo 'export PATH="./bin:$PATH"' >> ~/.bashrc source ~/.bashrc Open the sublime project from the command line (so that PATH is available in Sublime Text 2) subl . A: The following steps worked for me (I encountered the same error as OP): * *Install the RubyTest plugin through the package control manager. Note* If you don't have the package manager installed - I highly recommend it for managing sublime plugins - more info here. *Be sure to add the code here to your RubyTest.sublime-settings file. This file can be found at (from the menu): Preferences -> Package settings -> RubyTest -> Settings User *Save file, close Sublime and restart Sublime from the terminal in your project's folder using (so PATH is available in Sublime): subl . A: No, you don't need to change paths, run sublime from command line etc. If you are using RVM, you only have to do this: Go to Sublime Text 2, go to preferances-> package settings -> RubyTests and pick settings-user or settings-default (depending what you are using) and change line: "run_rspec_command": "rspec {relative_path}" to "run_rspec_command": "bundle exec rspec {relative_path}" And so forth - add bundle exec to all commands A: I spent many hours struggling with this same problem! I could not get rspec to run within Sublime Text 2, using the Michael Hartl "Ruby on Rails Tutorial." It kept saying: /bin/sh: rspec: command not found I finally realized that the RubyTest package (https://github.com/maltize/sublime-text-2-ruby-tests) was looking in the WRONG PLACE for my RVM! On my Mac, the path for RubyTest is /Library/Application Support/Sublime Text 2/Packages/Ruby Test First, to make RubyTest seek the RVM, I changed the parameter in RubyTest.sublime-settings from "check_for_rvm": false, to "check_for_rvm": true, Then I dug into the Python code of run_ruby_test.py: https://github.com/maltize/sublime-text-2-ruby-tests/blob/master/run_ruby_test.py At line 151, inside class BaseRubyTask, it had the wrong path for my RVM: rvm_cmd = os.path.expanduser('~/.rvm/bin/rvm-auto-ruby') I changed it to the full correct path: rvm_cmd = os.path.expanduser('/usr/local/rvm/bin/rvm-auto-ruby') If this is not your path, find the correct path by typing $ which rvm-auto-ruby and substitute that instead. After saving run_ruby_test.py, I went to Terminal, cd to my Rails application directory, and ran spork Finally, I opened static_pages_spec.rb in Sublime Text 2. Now all the tests work from it! A: I'm using rbenv and found that adding the following to my .bashrc did the trick /Users/user/.rbenv/shims/rspec
{ "language": "en", "url": "https://stackoverflow.com/questions/7513142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: How to get Dropdownlist selected value How to get dropdownList selected Item from CSHTML page. <div class="editor-field"> @Html.DropDownList("ROUTE_GROUP_ID", String.Empty) @Html.ValidationMessageFor(model => model.ROUTE_GROUP_ID) </div> A: If you want its value in jquery you can do like this $('#ROUTE_GROUP_ID').val(); or if you want its value in controller you can access it from Request.Form["ROUTE_GROUP_ID"] or if your controller have a formcollection object then access the value like formcollectionobj["ROUTE_GROUP_ID"] A: From your example, i don't see how you would get any selected value, since you haven't defined the SelectList from which your DropDownList will get it's values. I'd suggest you to create a ViewModel, fill a SelectItemList with your RouteGroup, passing it's ID as value. Like this: public class RouteGroupViewModel { public string SelectedRouteGroup { get; set; } public List<SelectListItem> RouteGroup { get; set; } public void FillRouteGroup() { //Fill your SelectList with your RouteGroup values } } On your view: @Html.DropDownListFor(item => item.SelectedRouteGroup, new SelectList(Model.RouteGroup, "Value", "Text")) And on your Controller: public ActionResult RouteGroup(RouteGroupViewModel rgVM) { //To Do your controller operations } With that you can get the DropDownList selected value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Main page condition in Ruby on Rails I need to display advertisement only on main page of my website (example.com). I've set up a root_url to posts controller: map.root :controller => "posts", :action => "index" I have global layout and I want to place in that view IF statement. The problem is that I have no idea how to check that root_url is displaying in certain moment. A: This looks like a better solution to me: Test for some flag in the view to display the section in question. Set the flag in the controller's action you want it to show for (here PostsController#index). See discussion here: * *Ruby on Rails: conditionally display a partial It's better, because with the same initial effort, later on you can set the flag based on more involved conditions (not only the page address), and for other actions. Also, keep logic out of views as much as possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find out the number of calls to the nCr function What is the solution of the following recursive equation? T(n, 0) = 1, T(n, n) = 1, T(n, r) = T(n-1, r-1) + T(n-1, r) + 1 I got this while trying to find out the number of calls to the function nCr, in the following definition of nCr int nCr ( int n, int r ) { if( n == r || r == 0 ) return 0; return nCr( n-1, r-1 ) + nCr( n-1, r ); } Is this recursive equation appropriate for the purpose? A: I think your recursive equation is perfectly right (the function you have defined does indeed always return 0, but it is not relevant to the number of calls that are made). So as to solve it, you should see that it is very close the recursion behind Pascal's triangle, so the value of T(n,r) should be related to the binomial coefficient C(n,r). If you try to write down the first few lines of this new triangle, you would get: 1 1 1 1 3 1 1 5 5 1 1 7 11 7 1 1 9 19 19 9 1 1 11 29 39 29 11 1 ... From this you can either use the OEIS, or figure out yourself that T(n,r) = 2 * C(n,r) - 1. You can then prove it using induction: if r = 0 or r = n, the relation is true, else T(n,r) = T(n-1,r) + T(n-1,r-1) + 1 = (2 * C(n-1,r) - 1) + (2 * C(n-1,r-1) - 1) + 1 = 2 * (C(n-1,r) + C(n-1,r-1)) - 1 = 2 * C(n,r) - 1 Hope this helps. A: shouldn't it be int nCr ( int n, int r ) { if( n == r || r == 0 ) **return 1;** return nCr( n-1, r-1 ) + nCr( n-1, r ); } A: I think you're on the right track (seriously), except that your function would always return zero. It's trivial to fix though. A: There's a tutorial for solving recurrence relations with more than one variable here. The papir pencil method. http://www.cs.ucr.edu/~jiang/cs141/recur-tut.txt If you want to know how many times your function is called, simple add a counter int counter = 0; int nCr ( int n, int r ) { counter++; if( n == r || r == 0 ) return 0; return nCr( n-1, r-1 ) + nCr( n-1, r ); } A: (As pointed out by others, the return value should be 1.) The result of the function call is basically nCr(n,r)=1+1+1+...+1+1. The total number of calls which return 1 is the number of ones in the above sum, nCr(n,r). The total number of calls which add two values is the number of +'s in the above sum, nCr(n,r)-1. Thus the total number of function calls is 2*nCr(n,r)-1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem controlling an existing service from an activity I am an Android newbie. I am starting a service at Phone Boot Up. I would like to control this service from an activity I would launch later. I however am unable to do so. Is it because I am launching the service from the BroadCastReceiver and there is some problem with the context? Can you let me know what I am doing wrong and how I should proceed. I would appreciate if anyone could explain how to proceed in this problem. Here are my files: MyPhoneBoot.java package phone.Boot; import android.content.Context; import android.content.Intent; import android.util.Log; public class MyPhoneBoot extends android.content.BroadcastReceiver { @Override public void onReceive(Context context, Intent intent){ Log.d("MyPhoneBoot", "Phone Boot Captured"); Intent expIntent=new Intent(context,MyService.class); context.startService(expIntent); } } MyService.Java package phone.Boot; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.util.Log; public class MyService extends Service { public static String TAG="MyNewService"; public static int service_running=999; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { service_running=2; Log.d(TAG, "onCreate"); Log.d(TAG, "Value " + MyService.service_running); } @Override public void onDestroy() { service_running=(-2); Log.d(TAG, "onDestroy"); Log.d(TAG, "Value " + MyService.service_running); } @Override public void onStart(Intent intent, int startid) { service_running=1; Log.d(TAG, "Value " + MyService.service_running); Log.d(TAG, "Service has been started!"); } public void onStop(Intent intent, int startid) { service_running=(-1); Log.d(TAG, "Value " + MyService.service_running); Log.d(TAG, "Service has been stopped!"); } } MyActivity.Java package phone.Boot; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MyActivity extends Activity implements OnClickListener{ @Override public void onCreate(Bundle savedInstanceState) { Log.d("MyActivity", "MyActivity running!" + MyService.service_running); super.onCreate(savedInstanceState); setContentView(R.layout.main); Button myButton, myButton2; myButton = (Button) this.findViewById(R.id.button_1); myButton.setOnClickListener(this); myButton2 = (Button) this.findViewById(R.id.button_2); myButton2.setOnClickListener(this); /* changes done for binding service */ } @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch(arg0.getId()){ case R.id.button_1: switch (MyService.service_running) { case 2: Log.d("MyActivity", "Starting already created service!"); Toast.makeText(this, "Alrdy created -> Starting now!", Toast.LENGTH_SHORT).show(); startService(new Intent(this,MyService.class)); break; case 1: Log.d("MyActivity", "Trying to start existing service!"); Toast.makeText(this, "Alrdy Running!", Toast.LENGTH_LONG).show(); break; case -2: case 999: Log.d("MyActivity", "Re-Starting Service"); Toast.makeText(this, "Re-Starting Service!", Toast.LENGTH_SHORT).show(); startService(new Intent(this,MyService.class)); break; } break; case R.id.button_2: if(MyService.service_running == -1 || MyService.service_running == -2 || MyService.service_running == 999) { Log.d("MyActivity", "No Service To Stop!"); Toast.makeText(this, "Nothing to Stop! x-(", Toast.LENGTH_LONG).show(); } else if(MyService.service_running == 1 || MyService.service_running == 2) { Log.d("MyActivity", "Halting Service!!"); Toast.makeText(this, "Stopping Service!", Toast.LENGTH_LONG).show(); stopService(new Intent(this,MyService.class)); } break; } } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="phone.Boot" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name="MyPhoneBoot"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver> <service android:enabled="true" android:name=".MyService" /> <activity android:name="phone.Boot.MyActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> </manifest> A: what exactly you want is not clear. Do you want to stop the service or you want to start the service from the activity again and you are not getting the desired result. This post may help you. A: I am also a noobie, but I've created something similar to you and it works great. First of all, since the service and activity are part of the same project, you can start and stop the service fine from the activity. Launching on boot doesn't make a difference (I stop and start my boot services fine from my activity). A couple of things: What do you mean "it doesn't work"? Does the app crash? What value do you get from service_running when you try to access it from the activity? Also, I'm not too sure about the service lifecycle. Though you don't explicitly stop it, it only runs code once. The service has long since completed its code by the time you've finished your boot process and accessed your activity. If you can't access the service_running variable, I'm guessing the service is dead and it has ceased to exist, though I could be wrong - I'm a noob after all :-) Try creating a repetitive service (like a GPS listener which will run forever), and see if that keeps it alive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open movie stream in another view I have in my app a tab view with many tabs, and in one of them I have a button that when is clicked, I want to show a movie stream in a view. I have this code: NSString *moviePath = @"http://10.0.0.4/prog_index.m3u8"; theMovie = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:moviePath]]; [theMovie.view setFrame:CGRectMake(0, 0, (self.view.frame.size.width), (self.view.frame.size.height))]; theMovie.view.backgroundColor = [UIColor grayColor]; theMovie.view.tag = 9999; [self.view addSubview:[theMovie view]]; [theMovie play]; The view appears, but the video doesn't start. What is wrong? A: You're passing to the MPMoviePlayerController an URL pointing to a m3u8 file. That is a playlist. To play media with MPMoviePlayerController, you have to set it an actual video file. You should parse the playlist to get the link to the real video and then init your MPMoviePlayerController with the real link. Check M3U - Wikipedia and MPMoviePlayerController reference Also check this related question EDIT: Thanks to Hugo Silva, I realized that MPMoviePlayerController is able to play live streams in m3u8 format, since I've not seen anything wrong in your code, I suggest you to check if it's a problem of your stream. Try using one of the samples provided by Apple. Also make sure that your stream meets Apple's requirements for HTTP Streaming
{ "language": "en", "url": "https://stackoverflow.com/questions/7513168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to enable a select_tag based on the option from the check box I have a Ruby On Rails application. I want to enable the drop down list only if the check box is enabled. Please let me know a way to do this. Thanks, Ramya. A: Do it with jQuery. Add a click handler to your element, and do your checks inside that. Here's an example of checking the checkbox: http://jquery-howto.blogspot.com/2008/12/how-to-check-if-checkbox-is-checked.html EDIT: code could be like this: $("#id_of_checkbox").live("click",function() { var is_checked = $(this).is(":checked"); if(is_checked) { // disable } else { // enable } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7513172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stored Procedure Inserts date value one less than the actual date in the XML string I am using XML to insert/update/delete records in table. But when I insert the row, the date value is inserted one less than the actual value. Below is the code for my Stored Procedure IF(@Mode='UPDATE_TABLE') BEGIN ;WITH XmlData AS ( SELECT NDS.DT.value('(ClaimExpenseID)[1]', 'int') AS 'ClaimExpenseID', NDS.DT.value('(ClaimID)[1]', 'int') AS 'ClaimID', NDS.DT.value('(POrderID)[1]', 'int') AS 'POrderID', NDS.DT.value('(SiteID)[1]', 'int') AS 'SiteID', NDS.DT.value('(FromDate)[1]', 'datetime') AS 'FromDate', NDS.DT.value('(ToDate)[1]', 'datetime') AS 'ToDate', NDS.DT.value('(ParticularID)[1]', 'int') AS 'ParticularID', NDS.DT.value('(Description)[1]', 'varchar(200)') AS 'Description', NDS.DT.value('(SubmittedAmount)[1]', 'int') AS 'SubmittedAmount', NDS.DT.value('(CreatedDate)[1]', 'datetime') AS 'CreatedDate', NDS.DT.value('(ApprovedAmount)[1]', 'int') AS 'ApprovedAmount', NDS.DT.value('(ApprovedDate)[1]', 'datetime') AS 'ApprovedDate', NDS.DT.value('(Remark)[1]', 'varchar(300)') AS 'Remark', NDS.DT.value('(ApproveBy)[1]', 'int') AS 'ApproveBy', NDS.DT.value('(RowInfo)[1]', 'varchar(20)') AS 'RowInfo' FROM @xmlString.nodes('/NewDataSet/DataTable') AS NDS(DT) ) MERGE INTO dbo.ClaimExpenseTRS CET USING XmlData x ON CET.ClaimExpenseID = x.ClaimExpenseID WHEN MATCHED AND x.RowInfo = 'UPDATE' THEN UPDATE SET CET.ClaimID=x.ClaimID, CET.CreatedDate=x.CreatedDate, CET.POrderID=x.POrderID, CET.SiteID=x.SiteID, CET.FromDate=x.FromDate, CET.ToDate=x.ToDate, CET.ParticularID=x.ParticularID, CET.Description=x.Description, CET.SubmittedAmount=x.SubmittedAmount, CET.ApprovedAmount=x.ApprovedAmount, CET.Remarks=x.Remark, CET.ApproveBy=x.ApproveBy, CET.ApprovedDate=x.ApprovedDate WHEN MATCHED AND x.RowInfo = 'DELETE'AND CET.ClaimExpenseID = x.ClaimExpenseID THEN DELETE WHEN NOT MATCHED AND x.RowInfo = 'NEW' THEN INSERT(ClaimID, CreatedDate, POrderID, SiteID,FromDate,ToDate,ParticularID, Description,SubmittedAmount,ApprovedAmount,Remarks,ApproveBy,ApprovedDate) VALUES(x.ClaimID,x.CreatedDate,x.POrderID,x.SiteID,x.FromDate,x.ToDate,x. ParticularID,x.Description,x.SubmittedAmount,x.ApprovedAmount,x.Remark,x. ApproveBy,x.ApprovedDate); END This is the XML string.. <NewDataSet> <DataTable> <ClaimExpenseID>5</ClaimExpenseID> <ClaimID>1</ClaimID> <CreatedDate>2011-08-01T00:00:00+05:30</CreatedDate> <POrderID>11</POrderID> <SiteID>4</SiteID> <FromDate>2011-08-07T00:00:00+05:30</FromDate> <ToDate>2011-08-08T00:00:00+05:30</ToDate> <NoOfDays>1</NoOfDays> <ParticularID>1</ParticularID> <Description>test</Description> <SubmittedAmount>500</SubmittedAmount> <Month>August</Month> <Year>2011</Year> <POrderNo>PO0002</POrderNo> <SiteName>SITE 2</SiteName> <ParticulerName>Food</ParticulerName> <RowInfo>UNCHANGED</RowInfo> <TableRowIndex>3</TableRowIndex> </DataTable> <DataTable> <ClaimID>1</ClaimID> <CreatedDate>2011-09-22T00:00:00+05:30</CreatedDate> <POrderID>26</POrderID> <SiteID>1</SiteID> <FromDate>2011-09-22T00:00:00+05:30</FromDate> <ToDate>2011-09-30T00:00:00+05:30</ToDate> <NoOfDays>8</NoOfDays> <ParticularID>1</ParticularID> <Description>dinner</Description> <SubmittedAmount>200</SubmittedAmount> <POrderNo>PO-01</POrderNo> <SiteName>ALKAPURI</SiteName> <ParticulerName>Food</ParticulerName> <RowInfo>NEW</RowInfo> <TableRowIndex>4</TableRowIndex> </DataTable> </NewDataSet> In second data table the from date value is 2011-09-22 and To date value is 2011-09-30 but when the value inserted in the database table it becomes 2011-09-21 and 2011-09-29 respectively.. A: Could this be your +5:30 timezone? Is this the same as your database or is your database trying to work out the time in a different timezone and coming up with the previous day? Edit: I just confirmed this. If I read your date time: 2011-09-30T00:00:00+05:30 into my machine (based in the UK), I get a return of 2011-09-29 18:30:00.000 The code I used for the conversion was : select cast('' as xml).value('xs:dateTime("2011-09-30T00:00:00+05:30")', 'datetime')
{ "language": "en", "url": "https://stackoverflow.com/questions/7513180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unknown symbol in while loading a kernel module I need help understanding why I get an error when I insert a module. I have tried this with no success. $ sudo modprobe lpfc_scst FATAL: Error inserting lpfc_scst (/lib/modules/2.6.32-33-generic/extra/lpfc_scst.ko): Unknown symbol in module, or unknown parameter (see dmesg) $ dmesg | tail [ 1201.262842] lpfc_scst: Unknown symbol scst_register_target [ 1201.262949] lpfc_scst: Unknown symbol lpfc_tm_term [ 1201.263161] lpfc_scst: no symbol version for scst_register_session [ 1201.263164] lpfc_scst: Unknown symbol scst_register_session [ 1201.263284] lpfc_scst: no symbol version for scst_rx_mgmt_fn [ 1201.263286] lpfc_scst: Unknown symbol scst_rx_mgmt_fn [ 1201.263395] lpfc_scst: no symbol version for scst_unregister_session [ 1201.263398] lpfc_scst: Unknown symbol scst_unregister_session [ 1201.263573] lpfc_scst: no symbol version for scst_rx_data [ 1201.263575] lpfc_scst: Unknown symbol scst_rx_data $ cat /proc/kallsyms | grep scst_register_target dffd2a10 r __ksymtab_scst_register_target [scst] dffd302e r __kstrtab_scst_register_target [scst] dffd2b34 r __kcrctab_scst_register_target [scst] dffd2a20 r __ksymtab___scst_register_target_template_non_gpl [scst] dffd3063 r __kstrtab___scst_register_target_template_non_gpl [scst] dffd2b3c r __kcrctab___scst_register_target_template_non_gpl [scst] dffd2c10 r __ksymtab___scst_register_target_template [scst] dffd308b r __kstrtab___scst_register_target_template [scst] dffd2de8 r __kcrctab___scst_register_target_template [scst] dff913a0 t __scst_register_target_template [scst] dff90dd0 T scst_register_target [scst] dff91840 T __scst_register_target_template_non_gpl [scst] $ Many thanks. A: If you are trying to insmod a module that was build against a kernel source tree/headers that are not the actual source of the running kernel, the most likely cause is that some kernel configuration is different between the running kernel and the one you built the module against. The linker inside the Linux kernel actually looks at a bunch of things besides the symbol name for matching symbols, including possibly a hash of the function parameter and return value, various config option (preempt / non preempt) when trying to match symbol names. I guess that in your case it does not find the right match due to different config options A: This means that the kernel isn't allowing modules to see that variable. It does look like you haven't added your variables to the list of symbols that the kernel exports: EXPORT_SYMBOL_NOVERS(scst_register_target); A: I have solved this problem as suggested on this forum: * *Compiled scst. *Appended the generated Module.symvers to existent /lib/modules/<version>/build/Module.symvers (Hack. Do not know why the kernel did not see the exported symbols). *Copied the scst to /lib/modules/<version>/extra. *depmod -a. *Compiled lpfc_scst. *Inserted module lpfc_scst with no problems. Have a nice day.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: What are ReservedCodeCacheSize and InitialCodeCacheSize? Can someone please explain what the JVM option ReservedCodeCacheSize and InitialCodeCacheSize are? Specifically when/why would I want to change it? How do I decide what the right size is? This is what the docs say: -XX:ReservedCodeCacheSize=32m Reserved code cache size (in bytes) - maximum code cache size. [Solaris 64-bit, amd64, and -server x86: 2048m; in 1.5.0_06 and earlier, Solaris 64-bit and and64: 1024m.] A: ReservedCodeCacheSize (and InitialCodeCacheSize) is an option for the (just-in-time) compiler of the Java Hotspot VM. Basically it sets the maximum size for the compiler's code cache. The cache can become full, which results in warnings like the following: Java HotSpot(TM) 64-Bit Server VM warning: CodeCache is full. Compiler has been disabled. Java HotSpot(TM) 64-Bit Server VM warning: Try increasing the code cache size using -XX:ReservedCodeCacheSize= Code Cache [0x000000010958f000, 0x000000010c52f000, 0x000000010c58f000) total_blobs=15406 nmethods=14989 adapters=362 free_code_cache=835Kb largest_free_block=449792 It's much worse when followed by Java HotSpot(TM) Client VM warning: Exception java.lang.OutOfMemoryError occurred dispatching signal SIGINT to handler- the VM may need to be forcibly terminated. When to set this option? * *when having Hotspot compiler failures *to reduce memory needed by the JVM (and hence risking JIT compiler failures) Normally you'd not change this value. I think the default values are quite good balanced because this problems occur on very rare occasions only (in my experince). A: A good learning experience from Indeed engineering team and challenges they faced when migrating to jdk 8. http://engineering.indeedblog.com/blog/2016/09/job-search-web-app-java-8-migration/ Conclusion : Jdk 8 needs more code cache han JDK 7 The default codecache size for JRE 8 is about 250MB, about five times larger than the 48MB default for JRE 7. Our experience is that JRE 8 needs that extra codecache. We have switched about ten services to JRE 8 so far, and all of them use about four times more codecache than before. A: @jeha answers everything I wanted to know from this question, apart from what value to set the parameters to. As I didn't write the code I was deploying I didn't have much visibility into the memory footprint it had. However, you can use jconsole to attach to your running java process, and then use the 'Memory' tab to find out the Code Cache size. For completeness, the steps are (Linux VM environment, though I'm sure other environments are similar): * *Fire up jconsole on your machine *Find the right process ID and attach jconsole to it (this will take a few moments) *Navigate to the 'Memory' tab *From the 'Chart:' drop-down list, select 'Memory Pool "Code Cache"' *Again, this may take a few moments for the screen to refresh, and then you should see something like: As you can see, my code cache is using approx 49 MB. At this point I still had the default which the documentation (and @jeha) says is 48 MB. Certainly a great motivation for me to increase the setting! Ben. 1024 MB by default probably was overdoing it, but 48 MB by default seems to be underdoing it... A: from https://blogs.oracle.com/poonam/entry/why_do_i_get_message: The following are two known problems in jdk7u4+ with respect to the CodeCache flushing: * *The compiler may not get restarted even after the CodeCache occupancy drops down to almost half after the emergency flushing. *The emergency flushing may cause high CPU usage by the compiler threads leading to overall performance degradation. This performance issue, and the problem of the compiler not getting re-enabled again has been addressed in JDK8. To workaround these in JDK7u4+, we can increase the code cache size using ReservedCodeCacheSize option by setting it to a value larger than the compiled-code footprint so that the CodeCache never becomes full. Another solution to this is to disable the CodeCache Flushing using -XX:-UseCodeCacheFlushing JVM option. The above mentioned issues have been fixed in JDK8 and its updates. So that information might be worth mentioning for systems running on JDK 6 (having code flushing disabled) and 7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "94" }
Q: Problem handling correctly strip_tag/substr in preview and expanded post I need to show a 4 line context all without tags and the rest of it only with <br> tag. What I though for the first part is the following that runs correctly as I want: * *I strip_tags description and save it to $post *Get only 320 chars and save it to $preview code $post = strip_tags($entry->description); $preview = mb_substr($post, 0, 320, "UTF-8"); My problem is with the expanded preview, as I said it needs to start where $preview stopped and show only <br> tags What I did is this but it is not working correctly $expanded = mb_substr($entry->description, 321, 9999999, "UTF-8"); $expanded = strip_tags($expanded, '<br>'); The reason that is not working correctly is because when I echo $preview.$expanded; when the $preview ends, it usually continues with a break tag and then the text. this is the `$preview` and here goes `$expanded` that it does not continues from where `$preview` ended, usually with a half tag p1BHvrI/AAAAAAAABm0/kMxU6nXgXSo/s320/20110921_125449.JPG" width="320" /> here goes the rest of the `$expanded` My question is how $expanded starts correctly right after $preview ends without any "broken tags" as above? UPDATE as said because this is a tricky situation, maybe a possible solution is to replace $preview (320 chars) with $expanded (full content). This is my expanding mechanism http://fiddle.jshell.net/r4F8Q/22/ A: It's tricky to know how to handle this. Like you say there is a good chance that you will end up with a broken tag doing it the way you are above, because if your mb_substr ends up in the middle of a tag, strip_tags() won't remove it correctly. Without seeing exactly how the mechanics of the expansion work at the client side I can't say for sure, but I think you would want to do something more like this: $preview = htmlspecialchars(mb_substr(strip_tags($entry->description), 0, 320, "UTF-8")); $description = strip_tags($entry->description,'<br>'); ...and when you do the expansion, replace $preview with $description, rather than appending $description description to the end of $preview. There is something else to consider here though - you should probably pass both strings through htmlspecialchars() and if you do that with $description, the <> around the line breaks will be escaped as well, where you don't want them to be. I can;t come up with an effective solution to this part, it probably needs some kind of horrible regex...
{ "language": "en", "url": "https://stackoverflow.com/questions/7513186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoid max char limit c# To exceed the max path limit in c# you apparently need to concatenate your drive path with @"\\?\" at the beginning of it. If I do this then I get a drive path with the following at the front \\\\?\\\\\\server\\share\\... Now if I look for the file/folder it will fail because of illegal charachters in the path (I assume the ?) so how can I adopt the approach outlined on Microsoft's website (http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx) correctly? foreach (string filePath in Directory.GetFiles(folder)) { String s = @"\\?\" + filePath; if (filePath.Length > 255) { Console.WriteLine(filePath); } if (File.Exists(filePath)) { FileInfo finfo = new FileInfo(s); folderSize += finfo.Length; } } foreach (string dir in Directory.GetDirectories(folder)) folderSize += GetDirectorySize(dir); A: Standard System.IO doesn't support path longer than 260 characters. But it seems there's a library with extended-length path support: http://alphafs.codeplex.com/ I personally haven't tried it so far. A: I don't think you should add all those slashes before the path, I think you did not understand everything what was written in MSDN here: Maximum Path Length Limitation In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string" where "" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.) Note: File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\?\" prefix as detailed in the following sections. The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. This type of path is composed of components separated by backslashes, each up to the value returned in the lpMaximumComponentLength parameter of the GetVolumeInformation function (this value is commonly 255 characters). To specify an extended-length path, use the "\?\" prefix. For example, "\?\D:\very long path". Note: The maximum path of 32,767 characters is approximate, because the "\?\" prefix may be expanded to a longer string by the system at run time, and this expansion applies to the total length. as you can read there,: The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. this is the key for your issue, if you need to create or access to a path longer than ~260 chars you should use specific Windows APIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: php: wordwrap text file contents to fit it in letter-size print page ( each line to Pixel width) I want to print simple text file (no style, formatting ) ,such that it fits in letter-size page and any overflow should be wrap to next line etc. wordwrap() php wordwrap function is doing what needed , but I am not sure how much character at maximum that fit on single line of letter-size page. I hope this is not silly question . Do I need to look other way e.g px /font-size / max page size in pixels etc . thanks in advance for any kind of help :) Note: printing will be done from desktop application like notepad , wordpad or whatever text editing application available A: Note: printing will be done from desktop application like notepad , wordpad or whatever text editing application available You won't be able to predict at what size the text is going to be printed out on client side, so this will be completely impossible to do in PHP. You'll have to rely on the client doing the line breaks. If you need full control over the printed result on that level, consider generating a PDF file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force open links in same window on same domain could someone help me with this problem. There is requirement to open all links when they are on external domains in _blank. But links in same domain must be opened in same window. I having issue, because I working in 2 domains one is https://www and other just http:// without www, how to open link in same windows on link without www? function externalLinks() { var h = window.location.host; jQuery("a[href^='http']").not("[href*='" + h + "']").not(".forceSameWindow").attr('target', '_blank'); } now all links exept https://www.something.com opening in blank example: http://something.com I must do this in jquery/js. I done this by doing hardcoded domain, but what do do nicely! Thanks for your help! A: Just change var h = window.location.host; to var h = window.location.host.replace(/^www/,''); that way it doesn't matter if you are on the www host or not A: You have to force apache to add www. Add this to your .htaccess file: RewriteEngine on RewriteCond %{HTTP_HOST} !^www.your_domain.com$ RewriteRule ^(.*)$ http://www.your_domain.com/$1 [R=301] A: var externalLinks = function(){ var anchors = document.getElementsByTagName('a'); var length = anchors.length; for(var i=0; i<length;i++){ var href = anchor[i].href; if(href.indexOf('http://h4kr.com/') || href.indexOf('http://www.h4kr.com/')){ return; } else{ anchor[i].target='_blank'; } } }; This should work :) A: This is based off your original post $("a").each(function($a){ $a=$(this); if(!~this.href.indexOf(document.location.host)||!$a.hasClass('forceSameWindow')){ $a.attr('target','_blank'); } }) Assuming all links are not set up to _blank initially
{ "language": "en", "url": "https://stackoverflow.com/questions/7513204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Associative style arrays in Javascript? I'm trying to assign an object in the style of an associate array in JS but it's failing, saying 'task.id' is undefined. Why is this? var response = Object(); $('.task-list').each(function() { response[this.id][$('#' + this.id).sortable('toArray')]; }); A: You are referencing the object as a two dimensional array. You should do it more like this: var response = {}; $(".task-list").each(function () { response[this.id] = $(this).sortable('toArray'); } Also, when you say the error is "task.id is undefined", do you mean "this.id is undefined"? If you are selecting elements based on class, they may not have an explicit id. <span class="task-list">myTask</span> You may want to include an id: <span class="task-list" id="myTask">myTask</span> A: You are trying to access a property that you haven't created yet. Although it's not actually clear what you are trying to do from your example. I'm assuming you want to set the value of response[this.id] to $('#' + this.id).sortable('toArray')? Try this instead: var response = {}; $('.task-list').each(function() { response[this.id] = $(this).sortable('toArray'); }); Also changed it to use $(this) instead of $('#' + this.id) as it's cleaner imo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using LocationTextExtractionStrategy in itextSharp for text coordinate My goal is to retrieve data from PDF which may be in table structure to an excel file. using LocationTextExtractionStrategy with iTextSharp we can get the string data in plain text with page content in left to right manner. How can I move forward such that during PdfTextExtractor.GetTextFromPage(reader, i, new LocationTextExtractionStrategy()) I could make the text retain its coordinate in the resulting string. As for instance if the first line in the pdf has text aligned to right, then the resulting string must be containing trailing space or spaces keeping the content right aligned. Please give some suggestions, how I may proceed to achieve the same. A: Its very important to understand that PDFs have no support for tables. Anything that looks like a table is really just a bunch of text placed at specific locations over a background of lines. This is very important and you need to keep this in mind as you work on this. That said, you need to subclass TextExtractionStrategy and pass that into GetTextFromPage(). See this post for a simple example of that. Then see this post for a more complex example of subclassing. The latter isn't completely relevant to your goal but it does show some more complex things that you can do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Clicking submit clears file field instead of submitting the form (IE9) I got a weird error I hope you guys can help with. Sometimes when the user tries to submit a form the file upload field image just clears and nothing happens. I doesn't seems like the form get submitted at all. Then the day after everything works fine. The error occurs on random days/times. First I thought it was a problem with the users computer but this happens on two different computers the customer has. One of the computers has Windows 7 professional & Internet Explorer 9. I don't have the setup on the other one. I have tried with Google Chrome, Firefox 6.0.2, Internet Explorer 9, 8 (browser compatibility mode), 7 (browser compatibility mode) on windows 7 home with no problems at all on my computer. Here is the form: <form action="/user/image" method="post" accept-charset="utf-8" class="form_default" enctype="multipart/form-data"> <fieldset> <ol> <li> <button type="submit" name="save" value="submit" class="button">Save</button> </li> <li> <label for="image">Profile image</label><input type="file" id="image" name="image" /> </li> <li> <button type="submit" name="save" value="submit" class="button">Save</button> </li> </ol> </fieldset> </form> A: There should be only 1 submit button per form. So keep 1 save button as type="submit" ,change another to type="button" A: Try using input instead of button, good luck! ex <input type="submit" name="mysubmit" value="Click!" /> A: you should use: <input type="button" onclick="customFunction" /> write what you want to do in customFunction(javascript) A: There is no clever workarounds for this, IE9 does not allow a file to be tampered with via JavaScript probably for security reasons. A: First of all, pls let us see your php coding to send this form.... Usually form submission errors such as this have server-side coding errors.. Maybe you should check out your PHP coding and see what happens in your $_POST['save'] area.... Hope this helps... :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: In Watin, how to wait until a form has been processed by the server? I'm submitting a form to my server via JavaScript in the view, in order to start a server-side job. The view detects that the job has finished by a JavaScript callback being called. The exact details of the JavaScript communication between server and client should be outside of the scope of this problem (I think), but let me know if you need more details. If it helps, I am using the Comet-like SignalR library, rather than standard Ajax. Now, I want to test this view in Watin (2.1.0). How can I make Watin wait until the server-side job has finished processing? Should I perhaps update an attribute in the view when it detects the job has finished? A: Depends how your js and html code looks. It's not that simple. Try to use WaitUntil... methods. Let's say that after job has finished new div elements with id foo appears. To wait for that use this code: ie.Div("foo").WaitUntilExists(); But sometimes it's not that simple. Let's say, that after job has finished, the content of the table changes, ie. old rows are removed, and new rows appears. If so: //Get cell reference var cell = ie.Table("bar").OwnTableRow(Find.First()).OwnTableCell(Find.First()); var cellRef = cell.GetJavascriptElementReference(); //Change text of that cell using javascript. jQuery could be used if it's used on that page //If you are 100% sure, that something will change, just assign cell.Text to text. If so, you don't even //need cellRef var text = "Dummy text or random or whatever"; ie.RunScript(cellRef + ".childNodes[0].nodeValue = '" + text + "'"); //TODO: //Do something here to fire ajax request //Wait until table will be updated, ie. wait until first cell will not contains assigned dummy text. //This could be done in many ways. ie.Table("bar").WaitUntil(t => t.OwnTableRow(Find.First()).OwnTableCell(Find.First()).Text != text); //or just: //cell.WaitUntil(c => c.Text != text), but maybe it will not work in your case Anyhow, this is just some tips. It's almost always a pain, so don't show me your actual code ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PsExec hangs without output when not using -d or -i I'm starting PsExec inside a WCF web service to execute a remote command and capture it's output. It's being run while impersonating a certain user. When trying to run a non-GUI command (like ping, tracert..), PsExec just hangs unless I use -d or -i. Because I need to get the output, using those parameters is not an option. GUI apps (mspaint, calc, ..) start just fine. Any idea what's going on? A: I haven't done enough testing yet, but I just hit this problem myself. It seems to me that the following link is a confirmation of the same behavior i am seeing. As soon as I commented out my output, everything started to work again. http://forum.sysinternals.com/nested-psexec-hangs-if-multiline-command-output_topic21520.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7513216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IE CSS Issue with nest LI tags The footer in the folowing site contains a sitemap: http://www.openawards.org.uk/ It doesn't look right in IE and I can't figure it out can anyone A: Remove float:left from #explore ul li a A: The problem is with your float left for the a tags. Try looking at the before pseudo selector such as ... #explore ul li a:before { clear: left; } A: It looks like IE is having a problem with the width of your lis, so it is not clearing the shorter links. Set a width to the lis and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Opening a new window from asp.net chart control I am firing JS window.open command from the asp.net chart control but that is not getting fired up. Below is the code of an .aspx page that would build a pyramid. <div> <asp:Chart ID="Chart1" runat="server" Height="416px" ImageType="Jpeg" Width="525px" IsMapAreaAttributesEncoded="True" Palette="None" PaletteCustomColors="Navy; DarkBlue; DarkBlue; DarkBlue; DarkBlue; DarkBlue; DarkBlue" TextAntiAliasingQuality="SystemDefault" ImageStorageMode="UseImageLocation"> <Series> <asp:Series BackGradientStyle="DiagonalRight" BackSecondaryColor="Black" BorderColor="Black" ChartType="Pyramid" Color="Transparent" CustomProperties="Pyramid3DRotationAngle=8, PyramidMinPointHeight=60, PyramidPointGap=3, PyramidLabelStyle=Inside" Font="Verdana, 8pt, style=Bold" IsValueShownAsLabel="True" Name="Series1" ShadowColor="Black" LabelForeColor="White" Palette="Grayscale"> <Points> <asp:DataPoint CustomProperties="PyramidInsideLabelAlignment=Top" Label=" xxxxxx Column-1" ToolTip="1111" YValues="40"/> <asp:DataPoint CustomProperties="PyramidInsideLabelAlignment=Top" Label="xxxxxx Column-2" MapAreaAttributes="" ToolTip="2222" YValues="40" /> <asp:DataPoint CustomProperties="PyramidInsideLabelAlignment=Top" Label="xxxxxx Column-3" MapAreaAttributes="" ToolTip="" Url="" YValues="40" /> <asp:DataPoint CustomProperties="PyramidInsideLabelAlignment=Top" Label=" xxxxxx Col4" MapAreaAttributes="" ToolTip="" Url="" YValues="40" /> <asp:DataPoint Label=" xxxxxx Col5" MapAreaAttributes="" ToolTip="" Url="" YValues="40" /> <asp:DataPoint Label=" xxxxxx Col6" MapAreaAttributes="onClick='javascript:OpenPage();'" ToolTip="" Url="" YValues="40" /> <asp:DataPoint CustomProperties="PyramidInsideLabelAlignment=Bottom" Label="xx Col7" MapAreaAttributes="" ToolTip="" Url="" YValues="40" /> </Points> </asp:Series> </Series> <ChartAreas> <asp:ChartArea Name="ChartArea1"> <Area3DStyle Enable3D="True" IsRightAngleAxes="False" Perspective="30" Inclination="45" PointGapDepth="1000" Rotation="60" /> </asp:ChartArea> </ChartAreas> </asp:Chart> </div> Below is the code behind; protected void Page_Load(object sender, EventArgs e) { string statusClicked = string.Empty; Series series = new Series("MySeries"); series.ChartType = SeriesChartType.Pyramid; series.BorderWidth = 3; DataTable dt = new DataTable(); dt.Columns.Add("Column-1", typeof(int)); dt.Columns.Add("Column-2", typeof(int)); dt.Columns.Add("Column-3.", typeof(int)); dt.Columns.Add("Column-4", typeof(int)); dt.Columns.Add("Column-5", typeof(int)); dt.Columns.Add("Column-6", typeof(int)); dt.Columns.Add("Column-7", typeof(int)); dt.Rows.Add(1400, 2240, 7660, 3410, 15, 4, 9); int colCount = dt.Columns.Count; List<string> xaxis = new List<string>(); List<double> yaxis = new List<double>(); Chart1.Series[0].Points[0].MapAreaAttributes = "onclick=\"javascript:window.open('http://www.google.com');\""; } Ideally, on the click of any series in the chart, google link should get open and status assigned wouldbe the one obtained from code. But the code never works. The URL that it opens is something like; http://localhost:1450/javascript%3avar+win%3dwindow.open('http%3a%2f%2fwww.google.com%3fstatus%3dTestStatus')%3b here as you can see that the status is Test Status and so the link that should open is http://www.google.com/?status=TestStatus NOTE: the labelURL property would take URL only. A: Not tested but you can use the MapAreaAttributes. Something like; Chart1.Series[0].Points[i].LabelUrl = "http://www.google.co.in?status=" + dt.Columns[i].ColumnName.ToString(); series.MapAreaAttributes = "target=\"_blank\""; or you can do something like (without querystring); foreach (Series series in Chart1.Series) { series.MapAreaAttributes = "onclick=\"javascript:window.open('http://www.google.com');\""; } Here is more info on the keywords that can help with your querystring parameter passing. In your case, you can also use MapAreaAttributes for the DataPointCollection Chart1.Series[0].Points[i].MapAreaAttributes = "onclick=\"javascript:window.open('http://www.google.co.in?status=" + dtSample.Columns[4].ColumnName.ToString() + "');\"";
{ "language": "en", "url": "https://stackoverflow.com/questions/7513226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why use private lock over intrinsic lock? While reading about synchronization, I came across "monitor pattern" to encapsulate mutable states. The following is the sample code public class MonitorLock { private final Object myLock = new Object(); Widget widget; void someMethod() { synchronized(myLock) { // Access or modify the state of widget } } } Is it better in any way to have a private lock instead of the intrinsic lock? A: Yes - it means you can see all the code which could possibly acquire that lock (leaving aside the possibility of reflection). If you lock on this (which is what I assume you're referring to by "the intrinsic lock") then other code can do: MonitorLock foo = new MonitorLock(); synchronized(foo) { // Do some stuff } This code may be a long way away from MonitorLock itself, and may call other methods which in turn take out monitors. It's easy to get into deadlock territory here, because you can't easily see what's going to acquire which locks. With a "private" lock, you can easily see every piece of code which acquires that lock, because it's all within MonitorLock. It's therefore easier to reason about that lock.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Remove unwanted section breaks from Word? I am trying to create an envelope in MS Word. The following code will create an envelope, but I get "section break (Next Page)" at the top of that page. I would like to remove that. oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Activate(); object ExtractAddress = false; object Address = "Address" ; object AutoText = "AutoText" ; object OmitReturnAddress = false; object ReturnAddress = "ReturnAddress" ; object ReturnAutoText = "ReturnAutoText"; object PrintBarCode = false; object PrintFIMA = false; object Size = "E65"; object Height = 110; object Width = 220; object FeedSource = true; object AddressFromLeft = 2; object AddressFromTop = 2; object ReturnAddressFromLeft = 2; object ReturnAddressFromTop = 2; object DefaultFaceUp = true; object DefaultOrientation = Microsoft.Office.Interop.Word.WdEnvelopeOrientation.wdCenterPortrait; object PrintEPostage = false; object Vertical = false; object RecipientNamefromLeft = Missing.Value; object RecipientNamefromTop = Missing.Value; object RecipientPostalfromLeft = Missing.Value; object RecipientPostalfromTop = Missing.Value; object SenderNamefromLeft = Missing.Value; object SenderNamefromTop = Missing.Value; object SenderPostalfromLeft = Missing.Value; object SenderPostalfromTop = Missing.Value; oDoc.Envelope.Insert(ref ExtractAddress, ref Address, ref AutoText, ref OmitReturnAddress, ref ReturnAddress, ref ReturnAutoText, ref PrintBarCode, ref PrintFIMA, ref Size, ref Height, ref Width, ref FeedSource, ref AddressFromLeft, ref AddressFromTop, ref ReturnAddressFromLeft, ref ReturnAddressFromTop, ref DefaultFaceUp, ref DefaultOrientation, ref PrintEPostage, ref Vertical, ref RecipientNamefromLeft, ref RecipientNamefromTop, ref RecipientPostalfromLeft, ref RecipientPostalfromTop, ref SenderNamefromLeft, ref SenderNamefromTop, ref SenderPostalfromLeft, ref SenderPostalfromTop); A: After fiddeling around with the envelope feature of Word, I noticed that this is not a programming question (although you made it looking like one). If you insert an envelope manually into a document, you will get also a section break, which splits the envelope part from the rest of the document, since both have different paper sizes. I did not find an easy way to get rid of that section break easily while still keeping the envelope size intact, so here is my advice to get this right: * *don't use the "envelope" feature of Word *adjust paper size and margins manually (in Word, using the menus/ribbons), and place your Address and return address at the positions where you want them to be *use the macro recorder to record the VBA commands to do this *port the VBA code to C#
{ "language": "en", "url": "https://stackoverflow.com/questions/7513229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: IBus: Couldn't receive data from agent I load ibus in Emacs, but I active ibus fail. The note is IBus: Couldn't receive data from agent. Thank A: I think you need to set up LC_CTYPE. As I used Chinese input with ibus, I just set LC_CTYPE=zh_CN.UTF-8 . Without such setting, it seems not possible to trigger ibus-mode properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does json support arabic characters? i want to ask quick question, is json support arabic characters i mean when i search for something like following $values = $database->get_by_name('معاً'); echo json_encode(array('returnedFromValue' => $value."<br/>")); also I'm looking for arabic result from the database, the returned values will be like this {"returnedFromValue":"\u0627\u0644\u0645\u0639\u0627\u062f\u0649<br\/>"}{"returnedFromValue":"\u0627\u0644\u0645\u0639\u0627\u062f\u0649<br\/>"} what I'm missing here ? is it better to use XML in term of supporting the arabic characters A: JSON is, just like XML, some kind of data-interchange-format. it's not addicted to a special charset, so arabic characters should be fine if u use a charset that supports these characters (UFT-8 for example). A: PHP 5.4.0 will support a special option for json_encode() called JSON_UNESCAPED_UNICODE. This stops the default behaviour of converting characters to their \uXXXX form. $value = 'معاً'; echo json_encode($value, JSON_UNESCAPED_UNICODE); // Outputs: "معاً" A: These \u0627-numbers are the Unicode-codepoints for your arabic letters. PHP uses them rather than the raw UTF-8 serialization, but they are there. So yes, JSON does support it. If the result string was printed out client-side (using Javascript) you would see the letters again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: asp.NET - Custom Error Messages I have this code in my web.config file: <customErrors defaultRedirect="~/GeneralError.aspx" mode="On"> <error statusCode="401" redirect="401.aspx" /> <error statusCode="404" redirect="404.aspx" /> </customErrors> This works perfectly on my local machine while running IIS and it redirects to my error pages, however when I run it on the server, IIS's default error pages pop in instead of mine. Why is this? How can I fix this? Is this something related from the code, or is this some setting on the server? A: This may not be the right solution for your issue, but double check IIS settings (Error Pages) http://blogs.iis.net/rakkimk/archive/2008/10/03/iis7-enabling-custom-error-pages.aspx IIS error pages settings override application config. A: This format was working for me <customErrors defaultRedirect="~/GeneralError.aspx" mode="On"> <error statusCode="401" redirect="~/GeneralError.aspx" /> <error statusCode="404" redirect="~/GeneralError.aspx" /> </customErrors> or <error statusCode="404" redirect="filenotfound.htm" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7513236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: problem with background image of Bar Button Item I have a Bar Button Item and I wanna set a background image for it. Both the button and the background image are set in the xib file. Here how it looks like: As you can see the image doesn't covers the whole width of the button. Now, I tried setting up as background a larger image and here is how the result looks like: The button gets larger itself and still the image doesn't fits its size. Anyone any idea of how to make this work? A: Try this, it works very well in these cases: UIImage *btnImg = [UIImage imageNamed:@"myImg.png"]; UIImage *btnGreyImg = [btnImg stretchableImageWithLeftCapWidth:12 topCapHeight:0]; [myBtn setBackgroundImage:btnGreyImg forState:UIControlStateNormal]; Of course, you can write this in one line or two lines, I just wanted to show it clearly... A: In my case, I made the outlet of the BarButtonItem as backBack and in viewDidLoad: method I wrote this code: UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom]; btnBack.frame = CGRectMake(0, 0, 250, 300); [btnBack setImage:[UIImage imageNamed:@"sample.png"] forState:UIControlStateNormal]; [btnBack addTarget:self action:@selector(callMethod:) forControlEvents:UIControlEventTouchUpInside]; backButton.customView = btnBack; I hope this is helpful in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JBOSS 7 - Osgi Bundles not present in JNDI TREE I have a bundle in JBOSS7 Bundle Repository. I want to lookup it from a WAR class throw JNDI, but in my JBOSS7.0.1.Final AS there is any trace of osgi in JNDI tree. In JNDI tree I found only "java:" and "java:jboss", I think that when I deploy a bundle the AS should add the "osgi:" leaf to the tree. Why not? Osgi Alliance specific says that when an osgi bundle is deployed it should be reachable throw JNDI... Some ideas? Thanks a lot! A: You are right, this part of the OSGi-JNDI spec is not yet done, you can track the progress here https://issues.jboss.org/browse/JBOSGI-81 Note: there is a way to get this working, see here for more details: Can't lookup OSGI services through JNDI
{ "language": "en", "url": "https://stackoverflow.com/questions/7513242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Save feature in AS3 I'm currently developing a project manager in AS3 and I want to save them into files. I found this tutorial (http://www.purplesquirrels.com.au/?p=1297) to create and read my own file types, but its using AIR. I want to put some instances inside it too, because I need to know how the objects are positioning in my Main MovieClip. Is it possible to do in AS3/Flash CS5? Thanks! EDIT: I found XML type. Can I write instances into XML files? A: Yes this is possible. The shared object provided by flash allows you to store data on the user's pc. Have a look at this: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7513243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to zoom a MapView so it always includes two geopoints? I have two geo points that vary intermittently, and want the MapView to resize and translate to make sure both points are always visible. I can easily re-centre the map on the point mid-way between the two, but how do I set the zoom level to ensure my two points are visible? A: Check out his answer in a different post: Google Map V2 how to set ZoomToSpan? It solves it without much hassle. Note that you can only use that function AFTER the map has been loaded at least once. If not use function with specified map size on screen LatLngBounds bounds = new LatLngBounds.Builder() .include(new LatLng(CURRENTSTOP.latitude, CURRENTSTOP.longitude)) .include(new LatLng(MYPOSITION.latitude, MYPOSITION.longitude)).build(); Point displaySize = new Point(); getWindowManager().getDefaultDisplay().getSize(displaySize); map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, displaySize.x, 250, 30)); Works like a charm and very dynamic! A: Try this and see: double latitudeSpan = Math.round(Math.abs(firstLat - secLat)); double longitudeSpan = Math.round(Math.abs(firstLong - secLong)); double currentLatitudeSpan = (double)mapView.getLatitudeSpan(); double currentLongitudeSpan = (double)mapView.getLongitudeSpan(); double ratio = currentLongitudeSpan/currentLatitudeSpan; if(longitudeSpan < (double)(latitudeSpan+2E7) * ratio){ longitudeSpan = ((double)(latitudeSpan+2E7) * ratio); } mapController.zoomToSpan((int)(latitudeSpan*2), (int)(longitudeSpan*2)); mapView.invalidate(); A: in the new Maps API (v2) you can do it this way: LatLng southwest = new LatLng(Math.min(laglng1.latitude, laglng2.latitude), Math.min(laglng1.longitude, laglng2.longitude)); LatLng northeast = new LatLng(Math.max(laglng1.latitude, laglng2.latitude), Math.max(laglng1.longitude, laglng2.longitude)); googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds(southwest, northeast),500,500, 0));
{ "language": "en", "url": "https://stackoverflow.com/questions/7513247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Add class on button click using javascript I am trying to check the username is available or not using button click event in javascript but when the user hits directly the button without entering anything in the textbox it's showing me as available. So I want to make as "please enter some text" message when the user doesn't enter anything in the textbox and hits the button. So how do I do that? Here is my code: <script type="text/javascript"> $(function () { $("#<% =btnavailable.ClientID %>").click(function () { $("#dvMsg").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow"); $.post("LoginHandler.ashx", { uname: $("#<% =txtUserName.ClientID %>").val() }, function (result) { if (result == "1") { $("#dvMsg").html('Already exists!').addClass('messageboxerror').fadeTo(900, 1); } else if (result == "0") { $("#dvMsg").html('Available').addClass('messageboxok').fadeTo(900, 1); } else { $("#dvMsg").html("Error!").addClass('messageboxerror').fadeTo(900, 1); } }); }); $("#<% =btnavailable.ClientID %>").ajaxError(function (event, request, settings, error) { alert("Error requesting page " + settings.url + " Error:" + error); }); }); </script> And this is my Css: <style> .messagebox { position:absolute; width:100px; margin-left:30px; border:1px solid #c93; background:#ffc; padding:3px; } .messageboxok { position:absolute; width:auto; margin-left:30px; border:1px solid #349534; background:#C9FFCA; padding:3px; font-weight:bold; color:#008000; } .messageboxerror { position:absolute; width:auto; margin-left:30px; border:1px solid #CC0000; background:#F7CBCA; padding:3px; font-weight:bold; color:#CC0000; } #dvMsg { height: 15px; width: 142px; z-index: 1; left: 172px; top: 126px; position: absolute; } </style> A: use an if statement like this: if($("#yourUserNameTextFieldID").val().length > 0) { //execute your test } else { // show a message } You can also test server-side. A: You verify the txtUserName is empty and display a message. <script type="text/javascript"> $(function () { $("#<% =btnavailable.ClientID %>").click(function () { if ($("#<% =txtUserName.ClientID %>").val() == "") { $("#dvMsg").removeClass().addClass('messageboxerror').text('please enter some text').fadeIn("slow"); } else { $("#dvMsg").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow"); $.post("LoginHandler.ashx", { uname: $("#<% =txtUserName.ClientID %>").val() }, function (result) { if (result == "1") { $("#dvMsg").html('Already exists!').addClass('messageboxerror').fadeTo(900, 1); } else if (result == "0") { $("#dvMsg").html('Available').addClass('messageboxok').fadeTo(900, 1); } else { $("#dvMsg").html("Error!").addClass('messageboxerror').fadeTo(900, 1); } }); } }); $("#<% =btnavailable.ClientID %>").ajaxError(function (event, request, settings, error) { alert("Error requesting page " + settings.url + " Error:" + error); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7513248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: achartengine draw axis without data? It is possible to draw only x and y axis without data? (because in my app I must draw line after 5sec). I set min and max values for axis, but without any data graph doesn't want redraw. A: You can just add empty Arraylist to dataset. A: What toni means, is adding and empty data series to the dataset, i.e. something like this: GraphicalView mChartView; XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset(); XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer(); mRenderer.addSeriesRenderer(new XYSeriesRenderer()); mDataset.addSeries(new XYSeries("some name")); However, in that case there are only graph lines without labels, ticks, grid, etc. Only after I add one (at least) data point these things show up to form a proper graph: mXYSeries.add(0, 0); This additional series has to be deleted right after you get real data because it shows up in the legend and produce other unwanted side effects. Unfortunately I don't know any better way of creating the axis lines with AChartEngine without data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# How to detect if an external application has popped up a window? I keep getting multiple verification prompt from a 3rd party application where on many instances I have to select the prompt window, type my password and click on Ok. I thought of writing a simple application in WHITE framework which can capture the window, enter my password and deliver a click automatically. I need to detect whenever a new window has popped up in Windows environment. I don't want to use either a timer or a loop. Can I get an event when ever a new window appears (registers) ? -- Regards Akshay Mishra A: Outside of managed code you could use global WindowHooks, however this involves injecting a DLL into another process space. This is not easily done with managed DLLs (read: assemblies). (It can be done, see here) I wrote an article on CodeProject a while ago on how to create a sort of managed global hook for WM_CREATE and WM_DESTROY messages. It includes full source code and it probably has what you need. Your application will need administrator privileges for this!
{ "language": "en", "url": "https://stackoverflow.com/questions/7513259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generating a non-guid unique key outside of a database I have a situation where I need to create some kind of uniqueness between 'entities', but it is not a GUID, and it is not saved in a database (It is saved, however. Just not by a database). The basic use of the key is a mere redundancy check. It does not have to be as scalable as a real 'primary key', but in the simplest terms I can think of , this is how it works. [receiver] has List<possibilities>. possibilities exist independently, but many will have the same values (impossible to predict. This is by design) Frequently, the receivers list of possibilities will have to be emptied and then refilled (this is a business requirement). The key is basically used to add a very lightweight redundancy check. In other words, sometimes the same possibility will be repeated, sometimes it should only appear once in the receiver's list. I basically want to use something very light and simple. A string is sufficient. I was just wanting to figure out a modest algorithm to accomplish this. I thought about using the GetHashCode() method, but I am not certain about how reliable that is. Can I get some thoughts? A: Try this for generating Guid. VBScript Function to Generate a UUID/GUID If you are on Windows, you can use the simple VBScript below to generate a UUID. Just save the code to a file called createguid.vbs, and then run cscript createguid.vbs at a command prompt. Set TypeLib = CreateObject("Scriptlet.TypeLib") NewGUID = TypeLib.Guid WScript.Echo(left(NewGUID, len(NewGUID)-2)) Set TypeLib = Nothing Create a UUID/GUID via the Windows Command Line If you have the Microsoft SDK installed on your system, you can use the utility uuidgen.exe, which is located in the "C:\Program Files\Microsoft SDK\Bin" directory or try the same for more info. Link I would say go for the Windows command line as it is more reliable. A: If you can use GetHashCode() at a first glance, you can probably use an MD5 hash as well, obtaining less collision probability. The resulting MD5 can be stored as a 24 charachter string by encoding it base 64, let see this example: public static class MD5Gen { static MD5 hash = MD5.Create(); public static string Encode(string toEncode) { return Convert.ToBase64String( hash.ComputeHash(Encoding.UTF8.GetBytes(toEncode))); } } with this you encode a source string in an md5 hash in string format too. You just have to write the "possibility" class in term of string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: matplotlib large set of colors for plots I have a lot of graphs I want to plot in one plot. I've just started with matplotlib and can't find a good way to generate a lot of distinguishable colors :( Maybe cycling over HSV with SV at maximum? I'm thinking of something like args=[] for i,(x,y) in enumerate(data): args.extend([x,y,hsv(i)]) plot(*args) Any suggestions? :) A: I think you have the right idea, except that the colors will be more distinguishable if you pass the colormap hsv numbers which are spread out over the range (0,1): hsv = plt.get_cmap('hsv') hsv(float(i)/(len(data)-1)) or, using NumPy: colors = hsv(np.linspace(0, 1.0, len(kinds))) For example: import datetime as DT import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import scipy.interpolate as interpolate dates = [DT.date(year, 9, 1) for year in range(2003, 2009)] t = list(map(mdates.date2num, dates)) jec = (100, 70, 125, 150, 300, 250) plt.plot(dates, jec, 'k.', markersize = 20) new_t = np.linspace(min(t), max(t), 80) new_dates = map(mdates.num2date, new_t) kinds = ('cubic', 'quadratic', 'slinear', 'nearest', 'linear', 'zero', 4, 5) cmap = plt.get_cmap('jet') colors = cmap(np.linspace(0, 1.0, len(kinds))) for kind, color in zip(kinds, colors): new_jec = interpolate.interp1d(t, jec, kind=kind)(new_t) plt.plot(new_t, new_jec, '-', label=str(kind), color=color) plt.legend(loc = 'best') plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/7513262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Maven pom.xml - build modules + self build I have the next project structure: app module1 module2 ... moduleN parent-pom Project app contains only properties files and JasperReports's reports templates. Pom.xml of app: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>my-group</groupId> <artifactId>parent-pom</artifactId> <version>1.0.0</version> <relativePath>../parent-pom</relativePath> </parent> <artifactId>app</artifactId> <version>${app-version}</version> <packaging>pom</packaging> <modules> <module>../module1</module> <module>../module2</module> ... <module>../moduleN</module> </modules> I want to add jasperreports-maven-plugin for project app. I've tried next code (before <modules> section), but it doesn't work (self build wasn't called): <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jasperreports-maven-plugin</artifactId> <configuration> <sourceDirectory>${basedir}/config/templates</sourceDirectory> <outputDirectory>${basedir}/config/templates</outputDirectory> </configuration> <executions> <execution> <goals> <goal>compile-reports</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>${jasperreports.version}</version> </dependency> </dependencies> </plugin> </plugins> </build> Is it possible to add self build to pom with modules? A: The app project packaging is set to pom - so it can't have any other artifacts. You will need to move the jasper reports to one of the other modules or a separate module.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the tools to draw icon for winform application? I'm new to programming and to winform. I want to create an icon for my winform application. What are the common tools to create icon for winform? A: Once I had worked in 3d animation field for few years. So I am pretty hands on with Adobe Photoshop and in general I use Photoshop to create icons for me. Its pretty simple and user friendly software for basic needs. Just create and export the icon in desired size. But its a paid software. If you wish to work on a free software, one can go for Gimp editor. But honestly i have never used it. Hope it helps. A: In Visual Studio you can add a new icon file. It will open an icon editor. Then in the project properties you can select the icon file to use for your application. A: You can take any raster image editing program that has the capability of exporting icon files and be done with it. Windows Forms is in no way different than any other application framework in that regard. Visual Studio also provides an (albeit crude) icon editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: I want to backup all my android phone book contacts into an XML file How can I store and reload my Android contacts in XML format. Please can you give me some suggestions or some sample code? A: E.g. this post might be helpful for reading contact data. This one for writing XML.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I customize a single edge of a UIView? I know by setting the borderWidth and borderColor property of the layer of an UIView allow me to customize the whole border.But now I just want to change an edge of the border, can anyone know how to do that? A: I think an easy solution is to add a sub layer on your view's CALayer to simulate a border, like: float borderWidth = 5.0; CALayer *mockBorder = [CALayer layer]; [mockBorder setBorderColor:[[UIColor blueColor] CGColor]]; [mockBorder setBorderWidth:borderWidth]; [mockBorder setFrame:CGRectMake(-1.0 * borderWidth, 0.0, yourView.frame.size.width + 2 * borderWidth, yourView.frame.size.height + borderWidth)]; [[yourView layer] addSublayer:mockBorder]; The sample above simulates a up-only-border. By tweaking the parameters in CGRectMake you can create various combinations such as up+left, up+down, etc. Don't forget to update the frame of the sub layer when the screen rotates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoid data redundancy in ASP.NET page I have an asp.net page which uses a listview to show 2 columns of data. The first column has just labels and the second one has dropdowns. My concern is, the dropdowns in second column has same items 100% of the time, they never change and since it is databound, and datasource to these dropdown is also same. As these dropdowns are in a list view this repetition happens on each row added to my list view! So, I was thinking of removing this data redundancy being transported over the wire. Any ideas? A: If your datasource is a database call then you can reduce that by storing the result of the call in a DataView object, and then binding your dropdowns to that object rather than making the call to the database for each dropdown. A: If you are using an ObjectDataSource, you can reduce the load time enabling the cache: <asp:objectdatasource ID="ObjectDataSource1" runat="server" EnableCaching="true" .... > </asp:objectDataSource> A: You could use the following approach: It loads the items in to the very first DropDownList and then uses JQuery to retrieve that DropDownList and and replicate the items into all of the others. Markup <div id="listViewContainer"> <asp:ListView ID="listView1" runat="server"> <ItemTemplate> <div><asp:DropDownList ID="dropDownList1" runat="server"></asp:DropDownList></div> </ItemTemplate> </asp:ListView> </div> Script $(function () { var sourceDropDown = $('#listViewContainer').find('select').first(); $('#listViewContainer').find('select').not(sourceDropDown).each(function () { var dropdown = $(this); dropdown.find('option').remove(); sourceDropDown.find('option').each(function () { var option = $(this); dropdown.append($('<option />').text(option.text()).val(option.val())); }); }); }); Code void listView1_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.DisplayIndex == 0) { DropDownList dropDownList1 = (DropDownList)e.Item.FindControl("dropDownList1"); dropDownList1.DataSource = dataTable; dropDownList1.DataTextField = "Text"; dropDownList1.DataValueField = "Value"; dropDownList1.DataBind(); } } Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android- location application optimizing I have created a location application which will show the current location in the google maps api on my device, but i am confused in using network provider and gps provider. I want my application to use the network provider when the application is opened, so it can quickly point the location. then it should search for gps provider, once gps is available then it should use the gps provider. during running the application if I loose gps connectivity it should go back to network provider and wait until gps is available. my source code is public class MyGoogleMap1Activity extends MapActivity { private static final long min_distance = 1; // in Meters private static final long min_time = 1000; // in Milliseconds protected LocationManager locationManager; protected MyLocationListener locationListener; HelloItemizedOverlay itemizedoverlay; List<Overlay> mapOverlays; MapView mapView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapOverlays = mapView.getOverlays(); Drawable drawable = this.getResources().getDrawable(R.drawable.google_maps_pin); itemizedoverlay = new HelloItemizedOverlay(drawable); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new MyLocationListener(); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, min_time,min_distance ,locationListener); } catch(Exception e) { Toast.makeText(MyGoogleMap1Activity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } @Override protected boolean isRouteDisplayed() { return false; } private class MyLocationListener implements LocationListener { public void onLocationChanged(Location location) { try { if (location != null) { int lat = (int) ( location.getLatitude() * 1E6); //coordinates are in microdegrees int lng = (int) ( location.getLongitude() * 1E6); GeoPoint point = new GeoPoint( lat, lng); OverlayItem overlayitem = new OverlayItem(point, "", ""); itemizedoverlay.addOverlay(overlayitem); mapOverlays.add(itemizedoverlay); MapController myMapController = mapView.getController(); myMapController.animateTo(point); myMapController.setZoom(16); } String message = String.format("Current Location \n Longitude: %1$s \n Latitude: 2$s",location.getLongitude(), location.getLatitude()); Toast.makeText(MyGoogleMap1Activity.this,message, Toast.LENGTH_LONG).show(); } catch(Exception e) { Toast.makeText(MyGoogleMap1Activity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } public void onStatusChanged(String provider, int status, Bundle extras) { Toast.makeText(MyGoogleMap1Activity.this,"Status Changed",Toast.LENGTH_LONG).show(); } public void onProviderDisabled(String s) { Toast.makeText(MyGoogleMap1Activity.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_LONG).show(); } public void onProviderEnabled(String s) { Toast.makeText(MyGoogleMap1Activity.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show(); } } } A: Here is an article by Google on how to juggle between various location providers Remeber that the network provider is very inaccurate. It relies on cell-site information. Compared to GPS accuracy of 10 to 50 meters, the Network providers accuracy is 100 to 3000m. GPS providers satellite visibility is impaired in buildings or dense forests/urban areas. However since the introduction of assisted GPS, you don't have to rely on satellite visibility. GPS provider will always be the better choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript function declaration. When to use what? Possible Duplicate: Javascript: var functionName = function() {} vs function functionName() {} What is the reason you would do: somename = function(param1, param2) { } In stead of doing: function somename(param1, param2) { } A: Well since the 1st syntax is a variable declaration and the 2nd is an actual function declaration, i would stick to the 2nd unless I truly needed the 1st. Try to read up on scoping and variable hoisting and you will see that the 2nd syntax can sometimes create trouble for you :) http://www.dustindiaz.com/javascript-function-declaration-ambiguity/ http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting Btw, you might want to browser this thread and look for more good stuff: var functionName = function() {} vs function functionName() {} A: $fn = function(param1, param2) By using the above form you are able to pass $fn to any function as a parameter, or you could create a new object from that: function doSomethingWithFn($fn); or $fnObject = new $fn(param1, param2) You can use the second form when you just need a utility function, or for closures: function utilityFn(str) { return str.indexOf('a') } var str = utilityFn('abc'); or $('#element').click(function() { utiliyFn($('#element').html()) }) A: The first method creates a function object that you can then pass as parameter to other functions. For example, if you want to execute some code when a text box value changes, you can set a callback like this (using jQuery): var onChange = function() { /* ... */ } $("#username").change(onChange);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to convert the result of jQuery .find() function to an array? What does jQuery .find() method return? a object OR a array list of objects? If it returns an object which contain all the matched elements. How to convert this object to an array? If it returns a array of elements, why $(xml).find("DATE").sort(mySortFunc); does not work, it seems the jQuery .find() returns an object which can not apply Javascript sort() method which is supposed to be applied on array. Generally, I need to sort the objects find by $(xml).find("DATE") , but when I use sort function, it raised an error that the object can not be resolved. A: If you call .get() on a jQuery object without a parameter, it will return a regular array of DOM elements. A: The majority of jQuery methods returns a jQuery object, which can be accessed like it is an array (e.g. it has a .length attribute, elements can be accessed using the square bracket notation ([0]), and it supports some array methods (slice())). jQuery has a method called toArray() which can be used to convert the jQuery object to a real array. You can also use get() with no arguments to achieve the same effect (and save you a few key presses). In future, you can checkout the jQuery API, and the return type for all jQuery methods is listed in the relevant documentation (e.g. for find(), the return type is "jQuery") A: jQuery already acts like an array, and thus you can apply array like functionality to it. Try to change $(xml).find("DATE").sort(mySortFunc); with Array.prototype.sort.apply($(xml).find("DATE"), mySortFunc); and you should get what you need
{ "language": "en", "url": "https://stackoverflow.com/questions/7513292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Strange limitation in the implementation of internal interface I have code internal interface IFoo { void foo(); } public class A : IFoo { // error CS0737: 'A' does not implement interface member 'IFoo.foo()'. //'A.foo()' cannot implement an interface member because it is not public. internal void foo() { Console.WriteLine("A"); } } Why such strange limitation? I have internal interface and why I can't create internal method in interface realization? A: This is because interfaces can't specify anything about the visibility of members, only the members themselves. All members that implement an interface must be public. The same happens when you implement a private interface. One solution might be explicitly implementing the interface: internal interface IFoo { void foo(); } public class A : IFoo { void IFoo.foo() { Console.WriteLine("A"); } } In the above code, you must have an instance of A cast to IFoo to be able to call foo(), but you can only do such a cast if you are internal compared to the class and hence have access to IFoo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can i do paging in asp.net mvc3? I am working on asp.net mvc3 application and have many records coming from database. I want to display only 10 records first then user can click on button to see next 10 records and so on... Like facebook wall posting more records. How can I implement this thing in my application using jQuery and ajax? How can I control display data in view using paging? I am using this to get 10 records but I want to display all records using more record button var Entity = (from a in context.Data where <Condition> select a).Take(10); A: The following articles should give you an idea : http://weblogs.asp.net/andrewrea/archive/2008/07/01/asp-net-mvc-quot-pager-quot-html-helper.aspx http://weblogs.asp.net/gunnarpeipman/archive/2010/02/21/simple-pager-for-asp-net-mvc.aspx On the other hand, you can implement it like this : Get the nuget package called TugberkUg.MVC Then, your controller should look like below : public ActionResult Index(int page = 0) { const int pageSize = 10; #region _filter the model IQueryable<myModel> model = _myrepo.GetAll() #endregion #region _convert the model to paginatedList var paginatedModel = new TugberkUg.MVC.Helpers.PaginatedList<myModel>(model, page, pageSize); #endregion return View(paginatedModel); } And, here how your controller should look like : @model TugberkUg.MVC.Helpers.PaginatedList<myModel> @foreach(var item in Model) { <p>@item.id</p> } You need to handle the pager as well and here is a sample for you : ASP.NET MVC PaginatedList Pager - Put wise "..." after certain point This TugberkUg.MVC.Helpers.PaginatedList class will provide all the necessary fields for pager. A: I'm not aware of any .net library that will do pagination for you out of the box, so I will roll out a DIY solution for you to think about. How can i implement this thing in my application using jquery and ajax? It is probably wise to have a specific Controller for ajax requests. Just have a separate Area (Ajax), and send your ajax requests to that url you set up. How can i control display data in view using paging? Set up a controller that takes in a "page" parameter. public ActionResult GetData(int? page){ // page is nullable to allow for default page // Do your query here to get the specific page. } I'm not sure if you require more information other than this. If I were trying to do what you were doing, this is what I would do. Hope that helps. A: If your are using Webgrid to display data then rowsperpage will do. var grid = new WebGrid(source: Model, selectionFieldName: "SelectedRow", rowsPerPage: 10, canPage: true, canSort: true); A: I would suggest using a telerik mvc control. They are really easy to use, powerful and free. www.telerik.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7513301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reflection to avoid System.Web reference I have a shared reporting dll that is used in both windows and web. I am now trying to move the windows programs to .NET 4 client profile so need to avoid System.Web references. At some points the code needs to get the directory of the website or the directory of the dll. I used code something like this: string path; if (HttpContext.Current != null) { path = HttpContext.Current.Server.MapPath("default.aspx"); } else { path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } Is there a way to use reflection or similar to avoid the System.Web reference so I can still get the appropriate path? If so how do I do it? Any alternatives? EDIT The reason I want to do this is I use a reporting system that can take a stylesheet file and apply it to reports (I do this for all reports). As a setting I previously had in the dll itself mystylesheet.repss.So if I wanted to change styles I just change it in the dll and it is applied to all reports. It was then just a case of dropping the appropriate repss file into the root directory on windows and the website. And finding the appropriate path to them. Trying to use relative paths with the dll results in issues. Passing the report.\mystylesheet.repss works fine in Windows but trying ~/mystylesheet.repss .\mystylesheet.repss or anything else I can think of from the dll in web ends up looking in the wrong directory "c:\windows\system32\inetsrv". I could move the setting out to each different windows and web app and pass it in with the full path worked out it seems backwards to do it that way when it is really an internal setting for the dll. Hope that has all made sense. A: Why don't you use paths relative to AppDomain.BaseDirectory. This will be the root directory of the web application for ASP.NET, and the directory containing your executable for a Console or WinForms application. For other application types, it will generally be a sensible default location: for example, in a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your app, not, say, the path to the Excel executable. If appropriate, you could support an optional configuration setting (e.g. appSetting) to allow the caller of your DLL to specify an alternate location, while defaulting to the base directory. Another option is to allow your callers to specify a path to the stylesheet file, which can be absolute or relative. If relative, make it relative to AppDomain.BaseDirectory. if (!Path.IsPathRooted(stylesheetPath)) { stylesheetPath = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, stylesheetPath); } ... Note that if you use a relative path, it will be relative to the current working directory, which can change during the lifetime of an application, and is not the same as the application base directory. A: If the mechanism for determining the location should depend on the context, it sounds like it would be appropriate for the caller to pass it in as a constructor or method parameter or something similar. Whether that's just as a straight path or something like a Func<string, string> as a "path resolver" will depend on exactly what you need to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse - Install New Software not working I am using Eclipse 3.5(Galileo). When I choose Help-> Install New Software, It does not Popup any dialog box to process further. Is anything I have to check to work on this? A: You need to add the libraries: go to: Properties-> Java Build Path->Libraries->Add Librariy
{ "language": "en", "url": "https://stackoverflow.com/questions/7513309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to control the transparency of a view in a RelativeLayout in android? I have a RelativeLayout that holds a set of views and i would like that one of the views will appear in front of all the other views? how can i do that ? Thanks EDIT : OK, i will be more specific. here is the code of my relativelayout, this is where i put all of my view. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#cfff" android:id="@+id/myMap"> i'm adding view to this relativelayout this way : creating different views...... relativelayout.addView(view); now, some of the view intersect with each other and when this happens i want to control which view will be on top of the other one. so how can i do that ? Thanks. A: The view will be ordered on the Z-axis in the order that they are added. So the first view will be the further in your layout. The next view added will be on top of the first view and so on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Response encryption problem I get the response as follow: TIMESTAMP=2011%2d09%2d22T10%3a20%3a24Z&CORRELATIONID=fa0181684fd81&ACK=Success &VERSION=65%2e0&BUILD=2133933&AMT=0%2e12&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M &TRANSACTIONID=6PT23270XK626941N" in this encrypted format How can I get original text string? This is my code for Parsing the URL : NSString *parameterString = [[NSString stringWithFormat:@"USER=mercha_1316582882_biz_api1.ifuturz.com" "&PWD=1316582974" "&SIGNATURE=Az-qrCDOk-pVcMVvJLOJY7DrGESBAgSH4RGOILESJSsYaBlWVZ3mNfJB" "&METHOD=DoDirectPayment" "&CREDITCARDTYPE=Visa" "&ACCT=%@" "&EXPDATE=092016 " "&CVV2=111" "&AMT=%@" "&FIRSTNAME=%@" "&LASTNAME=%@" "&STREET=%@" "&CITY=%@" "&STATE=%@" "&ZIP=%@" "&COUNTRYCODE=IN" "&CURRENCYCODE=USD" "&PAYMENTACTION=Sale" "&VERSION=65.0", txtCreditCardNo.text, strAmount, txtName.text, txtName.text, txtAddress.text, txtCity.text, txtState.text, txtZipCode.text ] retain]; NSLog(@"Soap : %@",parameterString); NSURL *url = [NSURL URLWithString:@"https://api-3t.sandbox.paypal.com/nvp"]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]]; [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"]; [theRequest setHTTPMethod:@"POST"]; [theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]]; NSError *err; NSURLResponse *resp; NSData *response = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&resp error:&err]; if (resp != nil) { NSString *stringResponse = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; NSLog(@"---------------------- %@",stringResponse); SBJSON *jsonParser = [SBJSON new]; NSMutableDictionary *json = [[NSMutableDictionary alloc] init]; json = [jsonParser objectWithString:stringResponse error:NULL]; NSLog(@"\n \n JSN Dic : %@",[json description]); } else if (err != nil) { NSLog(@"\n \n Nill"); } A: It is not encrypted, it is URL Encoded, that is troublesome characters are replaced with their hex values. Ex: '%2d' is '-'. NSString *stringToDecode = @"TIMESTAMP=2011%2d09%2d22T10%3a20%3a24Z&CORRELATIONID=fa0181684fd81&ACK=Success&VERSION=65%2e0&BUILD=2133933&AMT=0%2e12&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=6PT23270XK626941N"; NSString *decodedString = [stringToDecode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"decodedString: %@", decodedString); NSLog output: decodedString: TIMESTAMP=2011-09-22T10:20:24Z&CORRELATIONID=fa0181684fd81&ACK=Success&VERSION=65.0&BUILD=2133933&AMT=0.12&CURRENCYCODE=USD&AVSCODE=X&CVV2MATCH=M&TRANSACTIONID=6PT23270XK626941N
{ "language": "en", "url": "https://stackoverflow.com/questions/7513312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to render a helper I've built a helper which returns the string which I supposed to insert into HTML. I'm using Haml, so html.haml file has this line: = build_filetree 'small' It rendered the result into this: &lt;ul class=&quot;filetree&quot;&gt;&lt;li&gt;&lt;span class=&quot;folder&quot;&gt; folder&lt;/span&gt;&lt;/li&gt;&lt;ul&gt;&lt;li&gt;&lt; span class=&quot;file&quot;&gt;nested_file1.rb&lt;/span&gt;&lt;/li&gt;&lt;li&gt;&lt; spanclass=&quot;file&quot;&gt;nested_file2.rb&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt; li&gt;&lt;span class=&quot;file&quot;&gt;file1.rb&lt;/span&gt;&lt;/li&gt;&lt;li&gt; &lt;span class=&quot;file&quot;&gt;file2.rb&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt; But I expected this: <ul class="filetree"> <li><span class="folder">folder</span></li> <ul> <li><span class="file">nested_file1.rb</span></li> <li><span class="file">nested_file2.rb</span></li> </ul> <li><span class="file">file1.rb</span></li> <li><span class="file">file2.rb</span></li> </ul> What is the problem and how to fix it? Thanks A: Just use raw helper. For example: raw(“<ul class="filetree">...</ul>”)
{ "language": "en", "url": "https://stackoverflow.com/questions/7513314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making a responsive HTML5 mobile app I have recently started using LinkedIn and Google's mobile apps like Gmail/G+ etc and they are so fast, intuitive and simple to use. My question is what steps the engineers would have taken to make such apps? Are they rendering entire HTML or just update the portion of it? A: "fast, intuitive and simple to use" - This isn't entirely a technology based question. A lot of design and user experience design would have gone into the building of these app. Which is what makes them "intuitive and simple to use". To answer your questions within your question. Yes a lot of the new apps are HTML5 apps. Which uses the new HTML5 spec as well as a lot of JavaScript and CSS. A: Ajax is used extensively to develop those applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set this layout? I am going to implement the Calculator type application. In that I have set the Different button as like below code: <RelativeLayout android:id="@+id/linear_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_centerInParent="true" android:gravity="center_horizontal"> <!-- First row Start --> <Button android:id="@+id/sevenNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="7" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <Button android:id="@+id/eightNumber" android:layout_toRightOf="@+id/sevenNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="8" android:textColor="#ffffff" android:textSize="22dp" android:background="@drawable/selector_button" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/> <Button android:id="@+id/nineNumber" android:layout_toRightOf="@+id/eightNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="9" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <Button android:id="@+id/acButton" android:layout_toRightOf="@+id/nineNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="AC" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/brown_button"/> <!-- First row Finish --> <!-- Second row Start --> <Button android:id="@+id/fourNumber" android:layout_below="@+id/sevenNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="4" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <Button android:id="@+id/fiveNumber" android:layout_toRightOf="@+id/fourNumber" android:layout_below="@+id/eightNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="5" android:textColor="#ffffff" android:textSize="22dp" android:background="@drawable/selector_button" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp"/> <Button android:id="@+id/sixNumber" android:layout_toRightOf="@+id/fiveNumber" android:layout_below="@+id/nineNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="6" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <Button android:id="@+id/crearButton" android:layout_toRightOf="@+id/sixNumber" android:layout_below="@+id/acButton" android:layout_height="wrap_content" android:layout_width="50dp" android:text="C" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/brown_button"/> <!-- Second row finish --> <!-- Third row Start --> <Button android:id="@+id/firstNumber" android:layout_below="@+id/fourNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="1" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <Button android:id="@+id/secondNumber" android:layout_toRightOf="@+id/firstNumber" android:layout_below="@+id/fiveNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="2" android:textColor="#ffffff" android:textSize="22dp" android:background="@drawable/selector_button" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp"/> <Button android:id="@+id/threeNumber" android:layout_toRightOf="@+id/secondNumber" android:layout_below="@+id/sixNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="3" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <!-- Third row finish --> <!-- Fourth row Start --> <Button android:id="@+id/zeroNumber" android:layout_below="@+id/firstNumber" android:layout_height="wrap_content" android:layout_width="110dp" android:text="0" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:background="@drawable/selector_button"/> <Button android:id="@+id/dotNumber" android:layout_toRightOf="@+id/zeroNumber" android:layout_below="@+id/threeNumber" android:layout_height="wrap_content" android:layout_width="50dp" android:text="." android:textColor="#ffffff" android:textSize="22dp" android:background="@drawable/selector_button" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/> <Button android:id="@+id/doNothing" android:layout_toRightOf="@+id/threeNumber" android:layout_below="@+id/crearButton" android:layout_height="wrap_content" android:layout_width="50dp" android:textColor="#ffffff" android:textSize="22dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:background="@drawable/do_nothing_button" android:layout_alignBottom="@+id/dotNumber"/> <!-- Third row finish --> </RelativeLayout> Now, rightnow i have set the first row of Linearlayout as android:gravity="center_horizontal" which contain the button like "7","8","9" and "AC" button. But i want it to set autometicaly to fit with the device width. I think i have to use the weight property. but where and How i have to use it that i dont know So Please Help me regardin it. Thanks. A: First Set your LinearLayout width as fill_parent, and remove the gravity , and also put android:layout_weight=1 for each of your children to share the equal width. set layout_width parameter of each of the children to 0dp A: Remove android:layout_centerInParent="true" from LinearLayout. Set android:layout_width="fill_parent" for LinearLayout and Buttons. Try setting android:layout_weight="1" for every Button. A: use the weightSum property in your layout tag and in your buttons tag also. Set it to 1 in your layout tag and divide it in the way you want to set your button and set this value to button like if you want 4 buttons to be displayed with equal proportion then 1/4=0.25, set 0.25 to each button tag. Refer this and this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing command line arguments from Maven as properties in pom.xml Is it possible to pass arguments from command line to properties in pom.xml file ? for example I run mvn ... argument and in pom.xml <properties> <myproperty> here should add argument from command line</myproperty> </properties> Thank you for the help. A: mvn clean package -DpropEnv=PROD Then using like this in POM.xml <properties> <myproperty>${propEnv}</myproperty> </properties> A: You can give variable names as project files. For instance in you plugin configuration give only one tag as below:- <projectFile>${projectName}</projectFile> Then on command line you can pass the project name as parameter:- mvn [your-command] -DprojectName=[name of project] A: I used the properties plugin to solve this. Properties are defined in the pom, and written out to a my.properties file, where they can then be accessed from your Java code. In my case it is test code that needs to access this properties file, so in the pom the properties file is written to maven's testOutputDirectory: <configuration> <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile> </configuration> Use outputDirectory if you want properties to be accessible by your app code: <configuration> <outputFile>${project.build.outputDirectory}/my.properties</outputFile> </configuration> For those looking for a fuller example (it took me a bit of fiddling to get this working as I didn't understand how naming of properties tags affects ability to retrieve them elsewhere in the pom file), my pom looks as follows: <dependencies> <dependency> ... </dependency> </dependencies> <properties> <app.env>${app.env}</app.env> <app.port>${app.port}</app.port> <app.domain>${app.domain}</app.domain> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.20</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>properties-maven-plugin</artifactId> <version>1.0.0</version> <executions> <execution> <phase>generate-resources</phase> <goals> <goal>write-project-properties</goal> </goals> <configuration> <outputFile>${project.build.testOutputDirectory}/my.properties</outputFile> </configuration> </execution> </executions> </plugin> </plugins> </build> And on the command line: mvn clean test -Dapp.env=LOCAL -Dapp.domain=localhost -Dapp.port=9901 So these properties can be accessed from the Java code: java.io.InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("my.properties"); java.util.Properties properties = new Properties(); properties.load(inputStream); appPort = properties.getProperty("app.port"); appDomain = properties.getProperty("app.domain"); A: For your property example do: mvn install "-Dmyproperty=my property from command line" Note quotes around whole property definition. You'll need them if your property contains spaces. A: Inside pom.xml <project> ..... <profiles> <profile> <id>linux64</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <build_os>linux</build_os> <build_ws>gtk</build_ws> <build_arch>x86_64</build_arch> </properties> </profile> <profile> <id>win64</id> <activation> <property> <name>env</name> <value>win64</value> </property> </activation> <properties> <build_os>win32</build_os> <build_ws>win32</build_ws> <build_arch>x86_64</build_arch> </properties> </profile> </profiles> ..... <plugin> <groupId>org.eclipse.tycho</groupId> <artifactId>target-platform-configuration</artifactId> <version>${tycho.version}</version> <configuration> <environments> <environment> <os>${build_os}</os> <ws>${build_ws}</ws> <arch>${build_arch}</arch> </environment> </environments> </configuration> </plugin> ..... In this example when you run the pom without any argument mvn clean install default profile will execute. When executed with mvn -Denv=win64 clean install win64 profile will executed. Please refer http://maven.apache.org/guides/introduction/introduction-to-profiles.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7513319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "123" }
Q: getting a mysql array? Not sure really what to call it. But in my mysql database I have tons of values like this : a:2:{i:5;s:10:"likes";i:10;s:10:"likes";} a:3:{i:5;s:10:"likes";i:10;s:10:"likes";i:11;s:10:"likes";} I was under the assumption this is a form of an array and I have seen this before in another databse so I figured it was pretty standard, but kinda stumped now and my question is what would be a query to retrieve the largest of these arrays. so that a:MAXNUM{"likes";} is returned. If you need me to explain more please ask. A: This is serialized strings. You can unserialize them and they will be objects or arrays. When you unserialize that strings you can simply calculate likes count and max count by yourself. If serialized string was an array you can just do that with simple PHP functions if you used that. Strings you provide seems to be PHP serialized strings. More about serialization in PHP you can find here. Anyway you can't unserialize that strings using only MySQL. You need server-side laguage to do that, PHP for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read cookie values through javascript or jquery I have called one asp page inside the iframe You can check here: https://www.fiestacups.com/ProductDetails.asp?ProductCode=DUMMY If customer select font and select clip art image or upload image for clip art then I have store all that values in cookies. Now I want to get that cookies values in java-script variable on the another page. How can I do this? Please help me.... A: Using jquery cookies plugin is quiet simple: // read $.cookie('whatever') // write $.cookie('whatever', 'my whatever value') A: function get_cookie ( cookie_name ) { var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' ); if ( results ) return ( unescape ( results[2] ) ); else return null; } function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure ) { var cookie_string = name + "=" + escape ( value ); if ( exp_y ) { var expires = new Date ( exp_y, exp_m, exp_d ); cookie_string += "; expires=" + expires.toGMTString(); } if ( path ) cookie_string += "; path=" + escape ( path ); if ( domain ) cookie_string += "; domain=" + escape ( domain ); if ( secure ) cookie_string += "; secure"; document.cookie = cookie_string; } set_cookie ( "iframeURL", "hello" ); var test=get_cookie ( "iframeURL" ); A: on another page you can use to read the value stored in cookie :- var value = document.cookie("name_of_cookie");
{ "language": "en", "url": "https://stackoverflow.com/questions/7513338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Consistent UI rather than constant UI across platforms using sencha touch I was wondering how do i create consistent UI across all the platform rather than constant UI. Here by consistent i mean UI should look native to that particular platform. For example a tab bar in iOS is at the bottom and has particular look and feel whereas tab bar in Android is at the top and has different look. If i create tab bar in sencha it is by default at the bottom and provides a blue look and feel much similar to iOS, but it won't work for Android because with default look I will loose the Android app feel, it will be like iOS app inside Android. So how do i address this issue? Do i write if else conditions for all the platforms to layout components correctly and apply specific CSS or I can do it through theming and if yes to what extend i can do things using theming?? Note my aim is not only having different branding of components but also changing their positions/ orientations etc. The answers of these kind of questions are must as these would decide whether we should adopt sencha as cross platform tool or not. I would be grateful if i can get any working example of this kind which runs on iPhone/iPad/Android phone/ Android Pads providing their platform specific UIs. Thanks, Tarun. A: You can use themes to get the native colors. Sencha touch comes with 4 css - android.css, apple.css, bb6.css and sencha-touch.css. If you are not satisfied with those you can make a custom one with sass and compass. On theming - http://vimeo.com/17879651 So if you are doing a web app then you should detect what kind of device is and send the appropriate css. If you are doing a phonegap like app then you can pack different css for each platform. To get the native positions and orientations you can use sencha's profiles. Read all about them in this tutorial: http://www.sencha.com/learn/idiomatic-layouts-with-sencha-touch/ - Basically you check what type of device is and you save that to profile object, after you have if/else statements that check that object. Here you can find some of the apps made with sencha touch - http://www.sencha.com/apps/
{ "language": "en", "url": "https://stackoverflow.com/questions/7513339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: For google map route do we really need internet connection I am working on a assignment in which there is a need to calculate latitude and longitude of source and destination and based on source and destination lat long, i need to draw a route on google map between source and destination. so to complete this assignment, do i really need internet? if yes, so at what point i need internet connection while completing this project? A: * *GPS does not need an internet connection *display the map might not need internet in case that the area is in the cache of the google map application, otherwise internet is necessary *calculating a route between two points does need an internet connection A: Mainly used in google map itself need to use internet first thing than the another thing was find the route between two point. Other thing like calculate the distance that was comes in the direction in google map also you can get the more detail about this route for this two point of location. and to draw the route between this two point no another need to use Internet. for query the direction route you need to use internet for google direction api A: GPS does not need internet (though if you provide internet you will get a location faster). You can get the latitude and longitude information and record it the way you like to. But when you want to display this recorded route on Google Maps, you will need teh internets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to deploy MVVM WPf N-tier application so , my users suddenly changed their minds and decided to go for a networked application , I have views and viewmodels on the same project (UI) , a BLL layer dll in a ClassLibrary project and my DAL was generated using EF in another ClassLibrary project, In my development machine all these projects are on the same Solution and thus the BLL is referncing the DAL dll and the UI project(view and viewmodels) references the BLL dll ,now I want to deploy the UI project in the client machine and make it to reference the BLL dll which is located on the server where we also have the DAL dll and the database itself. the UI make a call to the BLL on the server and the BLL ask the DAL for some data, the DAL connets to the Database and get the data back, is it possible ? if yes how can I make my client to reference a dll located on another machine (the Server) Thanks in Advance A: Create a WCF Service which will use your BLL and deploy WCF on a server which is accessible to your clients then consume WCF in your WPF application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: System.threading.timer not working in Windows Service I am using System.threading.timer in Windows Service. But the timer is not successfully executed.Below is the code. protected override void OnStart(string[] args) { try { eventLog1.WriteEntry("In OnStart"); TimeSpan dueMinutes = TimeSpan.FromMinutes(1); TimeSpan fromMinutes = TimeSpan.FromMinutes(1); System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(CallBack), null, dueMinutes, fromMinutes); /* System.Timers.Timer timer = new System.Timers.Timer(5 * 60 * 1000); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); DBSyncHandler sync = new DBSyncHandler(); sync.startSync(); */ } catch (Exception ex) { if (!System.Diagnostics.EventLog.SourceExists("MySource")) { System.Diagnostics.EventLog.CreateEventSource("MySource", "MyEventLog"); } eventLog1.Source = "MySource"; eventLog1.Log = "MyEventLog"; eventLog1.WriteEntry("Error : " + ex.Message); } } public static void CallBack(object sender) { try { DBSyncHandler sync = new DBSyncHandler(); sync.startSync(); } catch (Exception ex) { EventLog eventLog1 = new EventLog(); if (!System.Diagnostics.EventLog.SourceExists("MySource")) { System.Diagnostics.EventLog.CreateEventSource("MySource", "MyEventLog"); } eventLog1.Source = "MySource"; eventLog1.Log = "MyEventLog"; eventLog1.WriteEntry("Error : " + ex.Message); } } After successfull installation .My workstation is restarted.On restarting the machine ,the service is called successfully.But once the service is called first time ,it is not repeating for next time duration i.e. the service is not called again. A: Your timer variable needs to be at the class level. Once it goes out of scope, it won't run anymore. Microsoft's recommendation is to use System.Timers.Timer in server code. Further information is available on the MSDN web site. http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx A: Read the notes on MSDN: http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected. System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features. I think that your timer object created in the OnStart is gc collected or disposed. it should not be a local variable in that method as it runs out of scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: socket connect timeout in c using poll I have an existing multi-threaded application which uses blocking connect() call. However, I want to introduce connect timeout for application where if server does not respond to our query in x milliseconds, application will stop trying and give error. However, I am not able to figure out how to do that using poll. @caf 's non blocking connect using select has been of great help. But I have read that select in slow compared to poll, hence I want to use poll. Could you please tell me if that is true? I am pasting his code from the post here int main(int argc, char **argv) { u_short port; /* user specified port number */ char *addr; /* will be a pointer to the address */ struct sockaddr_in address; /* the libc network address data structure */ short int sock = -1; /* file descriptor for the network socket */ fd_set fdset; struct timeval tv; if (argc != 3) { fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]); return EXIT_FAILURE; } port = atoi(argv[1]); addr = argv[2]; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(addr); /* assign the address */ address.sin_port = htons(port); /* translate int2port num */ sock = socket(AF_INET, SOCK_STREAM, 0); fcntl(sock, F_SETFL, O_NONBLOCK); connect(sock, (struct sockaddr *)&address, sizeof(address)); FD_ZERO(&fdset); FD_SET(sock, &fdset); tv.tv_sec = 10; /* 10 second timeout */ tv.tv_usec = 0; if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1) { int so_error; socklen_t len = sizeof so_error; getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len); if (so_error == 0) { printf("%s:%d is open\n", addr, port); } } close(sock); return 0; } Could you please help me to write similar functionality using poll. I am on RHEL and using gcc 4.5.x version. Update: For current code, how can change socket to blocking mode once app creates connections to server. I am not able to find a way to unset this O_NONBLOCK. Update 2: fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL) & ~O_NONBLOCK); One post has pointed that we can do this with above command. Didn't get the login though. A: The performance of select() and poll() relative to other system-dependent polling APIs is equivalent if there are only a few file descriptors that are being polled. They both scale poorly, but can perform just fine when the program is only listening to a few fds. An advantage of other system-specific polling APIs tends to be that they push associated state into the kernel so that each polling syscall does not require a copy of state from userspace to kernelspace. With only a few events, this copy and scan overhead is insignificant, and this benefit does not exist. Just stick with select() unless you need to scale to handling hundreds or more fds. If you really will be handling many fds, and you must support both Linux and Solaris, consider using a library like libevent or libev to abstract away the kernel-specific efficient wait APIs. A: select won't be slower than poll. But even if it were, it's unlikely that the minimal difference would matter in your application. For doing a nonblocking timeout connect you can copy from existing applications that provide such functionality. (see for example here, for an idea on how to do it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7513348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Sever Execution time-out vs .NET SqlCommand.CommandTimeout. Who wins? I tried to find the answer search this page and google with no luck! If I change the "Execution time-out" on the SQL Server instance (Tools->Options->Query Execution) and sets the SqlCommand.CommandTimeout in the .NET code using the SQL Server. Which property wins? Cheers --Jocke A: Timeout is a connection-level property - it applies to each individual connection. When you go to 'Tools->Options->Execution timeout' you affect only newly created connection in SQL Server Management Studio - it does not apply to SQL Server Instance you're running queries against. So SqlCommand.CommandTimeout will certainly 'win'. A: When you go to "Tools->Options->Execution timeout" in SSMS this sets SqlCommand.CommandTimeout for SSMS. No more, no less. There is no equivalent setting in the SQL Server engine to SqlCommand.CommandTimeout: SQL Server will not abort a query for a command timeout because it doesn't issue the command. The client does
{ "language": "en", "url": "https://stackoverflow.com/questions/7513351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Java Spring 3.0 @NumberFormat annotation I'm currently working on a small project trying to get Java spring validation working on a web form. It does work, however I have one input for inputting age, which I then convert to number format using this annotation, if I input letters it causes this to be displayed next to the input box when the form is submitted: "Failed to convert property value of type java.lang.String to required type java.lang.Integer for property age; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "dasdf" from type java.lang.String to type java.lang.Integer; nested exception is java.lang.IllegalArgumentException: Unable to parse dasdf" Is there any way to change this message, I'm sure it's simple, but have searched and can't find it. This is the validation code currently: @NotNull @NumberFormat(style = Style.NUMBER) @Min(1) @Max(110) private Integer age; Cheers, David A: I found the answer, inputting this into my messages.properties file overrides the default error message. typeMismatch.age=Input should be a number I knew it would be simple, but took a long time to find the syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple NSUrlConnection Run Simultaneous In my apps, there is a function which will download a file via HTTP URLConnection and write and append the data received to the files. That is some music files which needs couple minutes to complete the download. During the download, user may need to request some other JSON data from the server. And the problem is, what i am encountering is the request is delayed until the first connection (download the music file) is done. Both of it is separated to 2 different object and call by different class. I do also try start them with NSThread [NSThread detachNewThreadSelector: @selector(threadDownload) toTarget: self withObject: nil ]; However, the 2nd request is still waiting for the 1st request to be done, and because the downloading is taking too long time, the 2nd request get time out and error. Hope for your opinion on how to overcome such issue? A: Honestly I don't understand your complaints, since NSURLConnection is asynchronous by default, unless you are explicitly using sendSynchronousRequest:returningResponse:error:. For a "normal use", that is: initialize with initWithRequest:delegate: then call start, the class will handle all the process in a background thread and returns to the main thread only to invoke the designated delegate. A: Use GCD, it is really easy, all the threading is done transparently. Example: __block NSMutableArray *imageURLList = [NSMutableArray array]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); for (Helper *siteURL in list) { dispatch_async(queue, ^{ NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:siteURL]]; NSURLResponse *response; NSError *error; NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (urlData.length) [imageURLList urlData]; }); } Note that the block is executed async so it is alright to use sendSynchronousRequest:. If a loop is does not work for you just make individual requests. A: Best bet for this stuff is to use ASIHTTPRequest. It's easy to integrate and will handle all the concurrent background stuff for you. Here's the url: http://allseeing-i.com/ASIHTTPRequest/ A: You can try this library called: ASIHTTPRequest, it can do lots of things (i just posted same answer to a questions few mins ago). You can have multiple requests (asynchronous), this should solve your problems. Its very easy to use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Example of SOA model in real world would you please show me a SOA model in real world?(Service Provider,Service Broker,Service Requester) Thank you A: It is difficult to show you examples of real world. But here is an some of the articles I have written to show such integration using ESB and BPS. http://wso2.org/library/articles/2011/04/integrate-rules-soa http://wso2.org/library/articles/2011/06/securing-web-service-integration http://wso2.org/library/articles/2011/05/integrate-business-rules-bpel
{ "language": "en", "url": "https://stackoverflow.com/questions/7513371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DB2: converting date values to varchar I am new to databases, in fact this is first time. I want to select the date column from a table and the date to be printed as an output in some given format, like is there a way i can specify the format of output of this conversion. eg: date: 01/01/2011 output : Jan 1 2011 or 1st January 2011 Is there a function or way to do so? My guess is there must be? Thanks A: Try this: VARCHAR_FORMAT(DATE, 'MON DD YYYY') VARCHAR_FORMAT
{ "language": "en", "url": "https://stackoverflow.com/questions/7513376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java class/interface naming convention Possible Duplicate: What is standard for Interface naming in java api Why is a *able word used for a class such as Throwable, since this convention is primarily used for interfaces (e.g., Cloneable, Serializable, etc.)? A: I don't think there is a convention that says that the able suffix can only be used for interface. Its just a suffix to denote what the class would be capable of. A: Many of the classes which don't appear to follow convention date back to Java 1.0. i.e. before the conventions were established. E.g. Cloneable is an interface is associated with the method clone() which its says in its Javadoc should be made public, but doesn't include it in its interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: vim change :x function to delete buffer instead of save & quit I want to set :x in vim gui-mode to delete buffer because I always kill the whole gvim, which is kind of annoying. I know i can specifically set gui problems with if has("gui running") but don't know how to remap :x thanks in advance ps.: maybe the tag/term remap is wrong but I don't know the correct term, that's why google didn't provide any help at all. A: This is not as easy as it looks. :map won't work with commands and :command only accepts commands that start with an uppercase letter. But you can use :cabbrev: if has("gui_running") cabbrev x bd endif UPDATE: :cmap could actually be used: :cmap x bd, but it doesn't work right: each occurrence of x in a command is immediately replaced by bd. EDIT: This question is a duplicate of Can I (re)map Ex commands in vim?. A: I find the safest alternative is to use an expression abbreviation: cnoreabbrev <expr> x getcmdtype() == ":" && getcmdline() == 'x' ? 'bd' : 'x' This will ensure the abbreviation will only be expanded to bd when :x is used otherwise just expand to x. For more help: :h map-<expr> :h getcmdtype() :h getcmdline() Upon further inspection there appears to be a plugin that does exactly this by Hari Krishna Dara called cmdalias.vim. It uses a variation of the technique above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Pass initial value to a modelform in django How can I pass an initial value for a field to a model form. I have something like the following code class ScreeningForm(forms.ModelForm): class Meta: model = Screening def __init__(self, *args, **kwargs): super(ScreeningForm, self).__init__(*args, **kwargs) self.fields['blood_screen_type'] = CommaSeparatedCharField( label=self.fields['blood_screen_type'].label, initial=self.fields['blood_screen_type'].initial, required=False, widget=CommaSeparatedSelectMultiple(choices=BLOOD_SCREEN_TYPE_CHOICES) ) class ScreeningAdmin(admin.ModelAdmin): #form = ScreeningForm form = ScreeningForm(initial={'log_user':get_current_user()}) Now I want to pass an initial value for a field of the Person class. How can I do that? A: You can pass initial value to a ModelForm like this: form = PersonForm(initial={'fieldname': value}) For example, if you wanted to set initial age to 24 and name to "John Doe": form = PersonForm(initial={'age': 24, 'name': 'John Doe'}) Update I think this addresses your actual question: def my_form_factory(user_object): class PersonForm(forms.ModelForm): # however you define your form field, you can pass the initial here log_user = models.ChoiceField(choices=SOME_CHOICES, initial=user_object) ... return PersonForm class PersonAdmin(admin.ModelAdmin): form = my_form_factory(get_current_user()) A: In case anyone is still wondering, the following works to set initial values for an Admin form: class PersonAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(PersonAdmin, self).get_form(request, obj=obj, **kwargs) form.base_fields['log_user'].initial = get_current_user() return form Note that you can also set initial values via URL parameters: e.g. /admin/person/add?log_user=me A: As your ModelForm is bound to the Person-Model, you could either pass a Person-Instance: form = PersonForm(instance=Person.objects.get(foo=bar) or overwrite the ModelForm's init-method: class PersonForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PersonForm, self).__init__(*args, **kwargs) self.fields['foo'].value = 'bar' class Meta: model = Person exclude = ['name'] This is untested. I'm not sure whether "value" is correct, I'm not having a Django-Installation here, but basically this is the way it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: NewGuid vs System.Guid.NewGuid().ToString("D"); Is there a difference when you generate a GUID using NewGuid(); vs System.Guid.NewGuid().ToString("D"); or they are the same thing? A: Using System.Guid.NewGuid() you will get a object of Guid type Using System.Guid.NewGuid().ToString("D"); you will get the string representation of Guid object Also as I know no difference between .ToString("D") and .ToString() A: The generation algorithm has to be the same for both, because System.Guid.NewGuid().ToString("D") is calling System.Guid.NewGuid(), and then calling ToString on the result, i.e., both of your examples are calling the same method to generate the guid. As to comparing the "format" - this does not make sense because System.Guid.NewGuid() does not have a "format" in the same way as System.Guid.NewGuid().ToString("D") - it is only by calling the ToString method that you give the internal representation of the guid an external, string format. The format the string takes will depend on the argument you pass to the string method. A: Guid.NewGuid().ToString() is string representation of GUID, i.e. returns string object, while Guid.NewGuid() returns Guid datatype. A: I realize that this question already has an accepted answer, but I thought it would be useful to share some information about formatting guids. The ToString() (no parameters) method formats a guid using this format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx The ToString(string format) method formats a guid in one of several ways: "N" - xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 digits) "D" - xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (32 digits separated by hyphens) "B" - {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} (same as "D" with addition of braces) "P" - (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) (same as "D" with addition of parentheses) "X" - {0x00000000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}} Calling Guid.ToString("D") yields the same result as calling Guid.ToString(). As mentioned in the other answers, the guid itself has no format. It is just a value. Note, that you can create guids using NewGuid or using the guid's constructor. Using NewGuid, you have no control over the value of the guid. Using the guid's constructor, you can control the value. Using the constructor is useful if you already have a string representation of a guid (maybe you read it from a database) or if you want to make it easier to interpret a guid during development. You can also use the Parse, ParseExact, TryParse, and TryParseExact methods. So, you can create guids like this: Guid g1 = Guid.NewGuid(); //Get a Guid without any control over the contents Guid g2 = new Guid(new string('A',32)); //Get a Guid where all digits == 'A' Guid g3 = Guid.Parse(g1.ToString()); Guid g4 = Guid.ParseExact(g1.ToString("D"),"D"); Guid g5; bool b1 = Guid.TryParse(g1.ToString(), out g5); Guid g6; bool b2 = Guid.TryParseExact(g1.ToString("D"),"D", out g6);
{ "language": "en", "url": "https://stackoverflow.com/questions/7513391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: check if a movieclip exists on a specific location relative to event.currentTarget How can I check if the stage contains a movieclip on a specific x and y location on the stage? I'm building a colour-guessing game. The purpose is to walk a path through a generated field of hexagons, each assigned a random colour (yellow, red, blue or green), based on what soundfile you hear. So if you hear "yellow", you have to click a yellow tile etc. But because I want it to be a path, and the colours of the tiles are randomly generated, I have to check which colours border the currently active tile. I literally have no idea how to do this. I thought this might work but it doesnt: if ((this.tile.y == (event.currentTarget.y - 64)) != null) { //add the colour of this tile to array } I also see some problems in how to check if the next tile clicked borders on the previously active tile :( It's getting slightly overcomplicated for me. I would really appreciate your views on this. So my current question is: how do I check if a tile exists on stage that borders my active tile? Edit again: the game should be a simpler version of this one: http://elt.oup.com/student/i-spy/games/colour A: I'm not 100% sure about the situation, but I think you should add an eventListener on these tiles so that if you click on them, the color is checked with the current color that has to be clicked. Are you working actionscript 3 based? This shouldn't be to hard but it's hard to explain. A: When you randomly generate your tiles, store them. You may find that a linked list or doubly linked list works well for this--if you have a reference to the tile, you automatically have a reference to the bordering tile(s) http://www.developria.com/2009/12/iterative-data-storage-in-as3.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7513392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what's the right Windows folder to exchange data between local users? I want to write a file in app running under local regular user account and read it in service. What's the right folder? I'd like to avoid %APPDATA% (CSIDL_APPDATA) folder because service would need to realize where's this folder are (service is running under system account). I checked %ALLUSERSPROFILE% (is it CSIDL_COMMON_APPDATA?), it points to c:\ProgramData on my Win7 x64. But this folder doesn't allows modification for regular local users (I checked in folder properties, security tab). The same about %CommonProgramFiles%. I need to support WinXP and up. A: I found no such folder when I was in similar situation. The simple solution is to create a folder in CSIDL_COMMON_APPDATA folder during installation (or from the service) with special permissions that allow normal users to write to this folder. A: I think you need CSIDL_COMMON_DOCUMENTS (or FOLDERID_PublicDocuments), that is the Shared Documents folder. Under XP it would be something like c:\Documents and Settings\All Users\Documents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: crystal report for vs2010 Which version of Crystal Reports is compatible with VS 2010, and where can I get it? How do I install it with VS 2010? If you have any tutorials please give me links. A: I had to install it on my enterprise last week. VS2010 uses the version 13.0 so that you have to install the crystal report runtime for it - here you have its direct download links: CRVS2010 13.0.2000.0 (Links Updated in 29/10/2012) CRRuntime_32bit_13_0_3.msi Download Link CRRuntime_64bit_13_0_3.msi Download Link For WIN XP, WIN 2003, WIN 2008, WIN Vista, WIN 7 2.0, 3.0, 3.5, 4.0 *Source: http://wiki.sdn.sap.com/wiki/pages/viewpage.action?pageId=56787567 A: Check out these links: * *http://thedatafarm.com/blog/tools/visual-studio-2010-rc-and-crystal-reports-2008-ndash-just-works/ *http://anthonystechblog.wordpress.com/2010/10/29/crystal-reports-for-visual-studio-2010/ *http://support.microsoft.com/kb/317789 *http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_install_guide_2010_en.pdf *http://www.sourcehints.com/articles/how-to-use-crystal-report-2010-in-vs2010.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7513399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create custom reports with crystal reports and entity framework 4 I want to allow users of a asp.net mvc 2 application, creating dynamicly reports. In a SQLServer Database is a table with all tasks for a user. Every task depends on a project and a user. What I want to do is to create some reports like "show me all tasks for the project X" or "Show me all my tasks" but also something like "Show me all my tasks with the status X for project Y". This lists should be exportable as PDF or CSV. And it would be also nice if it is possible to show this lists in a asp.net mvc view. I read a lot about crystal reports and it seems that what I want is possible with it. I found some tutorials which explain how to show all columns of a table in the report. But what I don't understand is how I can set some conditions "on the fly". It would be very nice if something like the following pseudocode will do what I want: // Load the tasks with Entity Framework by reference to some Condition List<Task> tasks = GetTasks(userId); // Load the reportfile var report = GetChristalReport("Name of the .rpt report file"); // Set the loaded entities to the report report.setData(tasks); // Export it to pdf or do what you want with the rendered report var pdf = report.ExportToPdf(); I hope you can help me and say if this is possible with chrystal reports and how I can implement this. A: Everything you mention is not only possible but relatively easy to do in CR. Most of what you need to do is to create a ReportDocument object, call repDoc.Load("myReport.rpt"); and then repDoc.ExportToDisk(fileFormat, fileName); and you're done. If you want to view it in the asp as an rpt file you need to create a ReportViewer object which is a little difficult but ASP natively supports viewing pdf in browser. I hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7513408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I detect when a user is at the maximum zoom level? (google maps v3) I am clustering my markers together. When a user zooms in to the highest level I need to break the clusters up so that the user can view information for individual items. Given that the number of zoom levels is different depending on the type of map used and that 'maxZoom' may have been explicitly set in mapOptions, how do I detect when the user cannot zoom any further (i.e. the zoom slider is at its highest point)? Is there just a zoom level number I can use for this (21 perhaps)? Or is this number variable depending on different scenarios? What would these scenarios be? I do not need to know this value prior to zooming in: only when the user REACHES the max level. A: google maps api have a service for that, you could use it like that: (new google.maps.MaxZoomService()).getMaxZoomAtLatLng(map.getCenter(), function(response) { if (response.status != google.maps.MaxZoomStatus.OK) { alert("Error in MaxZoomService"); return; } else { if (map.getZoom() >= response.zoom) { //do sth with your clusterer //probably markerClusterer.setMaxZoom(response.zoom - 1); //or markerClusterer.setMap(null); } } }); EDIT: there is also a solution I found in markerclusterer.js (from google maps utility library), but it recently started to cause errors and I am not sure if it is reliable: map.mapTypes[map.getMapTypeId()].maxZoom; A: From a quick test, looks like z=19 is the most zoomed in before you get to street view level. Tested in a couple of countries, it hasn't changed. A: Most city maps will zoom to 18, but some go beyond that, and there are isolated satellite views up to level 23.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: c# linq keep only matching dictionary values based on list I have one composite dictionary and one list Dictionary<Point, List<int>> GroupedIndex int[] TobeMatched Now I want to check for every key, whether there are any matching values in the TobeMatched array. If it is matching, then keep only matching values for that key and remove other values. If there is no match, then delete the key. Example: GroupedIndex: [0] -> Key [X=1;Y=1]; Values [0] -> 5, [1] -> 10 [1] -> Key [X=1;Y=2]; Values [0] -> 1, [1] -> 3, [2] -> 6 TobeMatched: {1,2,6} Result expected: New dictionary: [0] -> Key[X=1;Y=2]; Values [0] -> 1, [1] -> 6 is it possible to achieve this in linq? A: It's not possible to modify your original dictionary with LINQ, because LINQ is composed of pure operations (i.e. does not mutate the values it works on). With pure LINQ it is possible to simply get a new dictionary with your specifications: var newGroupedIndex = GroupedIndex .Select(pair => new { Key = pair.Key, Matched = pair.Value.Intersect(TobeMatched).ToList() }) .Where(o => o.Matched.Count != 0) .ToDictionary(o => o.Key, o => o.Matched); See it in action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't I run an app after installing .NET Framework 4? Please use simple English, my language skills are not as good as yours! :) I installed .NET Framework 4 for one app but when I run the setup for that app, I see this error: Installer information Microsoft .NET framework 3.5 SP1 or greater needs to be installed! I installed .NET Framework 4 and 3 SP1 but I can't insatll my app! The app programer said that just .NET Framwork 4 should be installed! A: the Installer for .NET 4 does not include the installer for .NET 3.5 you need to install the .NET 3.5 framework as well as the .NET 4 framework. Here's the link for the standalone installer: http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/7513433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert a double array to a float array I have a double[][] array, and I want to get one row into a float[] array. Casting didn't worked at first, so I looked for something different. I found here in stackoverflow an elegant solution to convert Object[] to String[], which also would work if I were converting Object[] to float[]. So: is there any elegant way of converting double[] to float[], or a double[] to Object[] so I can use the code at the other post? I'll provide an example code of what I'm doing, even I think it's not neccesary: double[][] datos = serie.toArray(); double[][] testArray = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}}; double[] doubleArray = Arrays.copyOf(testArray[1], testArray[1].length); // This would be great but doesn't exist: //float[] floatArray = Arrays.copyOf(doubleArray, doubleArray.length, float[].class); A: Here is a function you could place in a library and use over and over again: float[] toFloatArray(double[] arr) { if (arr == null) return null; int n = arr.length; float[] ret = new float[n]; for (int i = 0; i < n; i++) { ret[i] = (float)arr[i]; } return ret; } A: For future reference; this can also be done a bit more concisely by using Guava, like this: double[] values = new double[]{1,2,3}; float[] floatValues = Floats.toArray(Doubles.asList(values)); A: No, casting the array won't work. You need to explicitly convert each item: float[] floatArray = new float[doubleArray.length]; for (int i = 0 ; i < doubleArray.length; i++) { floatArray[i] = (float) doubleArray[i]; } A: With Kotlin you can try something like this: val doubleArray = arrayOf(2.0, 3.0, 5.0) val floatArray = doubleArray.map { it.toFloat() }.toFloatArray() or val floatArray = arrayOf(2.0, 3.0, 5.0).map { it.toFloat() }.toFloatArray() A: I created this class for my own personal use but i think it can help you with your problem. import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class ArrayUtils { private static final Logger log = LoggerFactory.getLogger(ArrayUtils.class); private static final Map<Class, Class> primitiveMapping = new HashMap<Class, Class>(); private static final Map<Class, Method> primitiveParseMethodLookup = new HashMap<Class, Method>(); private static final Map<Class, Method> primitiveArrayGetMethodLookup = new HashMap<Class, Method>(); private static final Map<Class, Method> valueOfMethodLookup = new HashMap<Class, Method>(); static { // Initialize primitive mappings primitiveMapping.put(boolean.class, Boolean.class); primitiveMapping.put(byte.class, Byte.class); primitiveMapping.put(short.class, Short.class); primitiveMapping.put(int.class, Integer.class); primitiveMapping.put(float.class, Float.class); primitiveMapping.put(long.class, Long.class); primitiveMapping.put(double.class, Double.class); // Initialize parse, valueOf and get method lookup // We do that in advance because the lookup of the method takes the longest time // Compared to the normal method call it's 20x higher // So we use just the reflective method call which takes double the time of a normal method call try { primitiveParseMethodLookup.put(boolean.class, Boolean.class.getMethod("parseBoolean", new Class[]{String.class})); primitiveParseMethodLookup.put(byte.class, Byte.class.getMethod("parseByte", new Class[]{String.class})); primitiveParseMethodLookup.put(short.class, Short.class.getMethod("parseShort", new Class[]{String.class})); primitiveParseMethodLookup.put(int.class, Integer.class.getMethod("parseInt", String.class)); primitiveParseMethodLookup.put(float.class, Float.class.getMethod("parseFloat", String.class)); primitiveParseMethodLookup.put(long.class, Long.class.getMethod("parseLong", String.class)); primitiveParseMethodLookup.put(double.class, Double.class.getMethod("parseDouble", String.class)); valueOfMethodLookup.put(Boolean.class, Boolean.class.getMethod("valueOf", new Class[]{String.class})); valueOfMethodLookup.put(Byte.class, Byte.class.getMethod("valueOf", new Class[]{String.class})); valueOfMethodLookup.put(Short.class, Short.class.getMethod("valueOf", new Class[]{String.class})); valueOfMethodLookup.put(Integer.class, Integer.class.getMethod("valueOf", String.class)); valueOfMethodLookup.put(Float.class, Float.class.getMethod("valueOf", String.class)); valueOfMethodLookup.put(Long.class, Long.class.getMethod("valueOf", String.class)); valueOfMethodLookup.put(Double.class, Double.class.getMethod("valueOf", String.class)); primitiveArrayGetMethodLookup.put(boolean.class, Array.class.getMethod("getBoolean", new Class[]{Object.class, int.class})); primitiveArrayGetMethodLookup.put(byte.class, Array.class.getMethod("getByte", new Class[]{Object.class, int.class})); primitiveArrayGetMethodLookup.put(short.class, Array.class.getMethod("getShort", new Class[]{Object.class, int.class})); primitiveArrayGetMethodLookup.put(int.class, Array.class.getMethod("getInt", Object.class, int.class)); primitiveArrayGetMethodLookup.put(float.class, Array.class.getMethod("getFloat", Object.class, int.class)); primitiveArrayGetMethodLookup.put(long.class, Array.class.getMethod("getLong", Object.class, int.class)); primitiveArrayGetMethodLookup.put(double.class, Array.class.getMethod("getDouble", Object.class, int.class)); } catch (NoSuchMethodException e) { //****************************** // This can never happen //****************************** } } public static boolean isArrayOfPrimitives(Object object) { if (object.getClass().isArray()) { return object.getClass().getComponentType().isPrimitive(); } return false; } public static boolean isArrayOf(Object object, Class clazz) { if (object.getClass().isArray()) { return clazz.isAssignableFrom(object.getClass().getComponentType()); } return false; } /** * Convert any array of primitives(excluding char), strings or numbers into any other array * of strings or numbers. * * @param array Array of primitives(excluding char), strings or numbers * @param convertedArrayComponentType Converted array component type (String or Number) * @param <T> To allow implicit casting * @return Array of convertedArrayComponentType */ public static <T> T[] convertArray(Object array, Class<T> convertedArrayComponentType) { // Collect data regarding arguments final boolean arrayOfPrimitives = isArrayOfPrimitives(array); final boolean arrayOfCharPrimitives = isArrayOf(array, char.class); final boolean arrayOfCharacters = isArrayOf(array, Character.class); final boolean arrayOfStrings = isArrayOf(array, String.class); final boolean arrayOfNumbers = isArrayOf(array, Number.class); // Check if array is an array of strings, primitives or wrapped primitives if (!arrayOfPrimitives && !arrayOfNumbers && !arrayOfStrings || arrayOfCharPrimitives || arrayOfCharacters) { throw new IllegalArgumentException(array + " must be an array of of strings, primitives or boxed primitives (byte, boolean, short, int, float, long, double)"); } // Check if it's assignable from Number of String if (!Number.class.isAssignableFrom(convertedArrayComponentType) && !String.class.isAssignableFrom(convertedArrayComponentType)) { throw new IllegalArgumentException(convertedArrayComponentType + " must be a Number or a String"); } try { return (T[]) convertArrayInternal(array, convertedArrayComponentType); } catch (InvocationTargetException e) { // This can happen due to errors in conversion throw (RuntimeException) e.getTargetException(); } catch (Exception e) { // This should never happen log.error("Something went really wrong in ArrayUtils.convertArray method.", e); } // To satisfy the compiler return null; } /** * Convert any array of primitives(excluding char), strings or numbers into an array * of primitives(excluding char). * * @param array Array of primitives(excluding char), strings or numbers * @param convertedArrayComponentType Converted array component type primitive(excluding char) * @return Array of convertedArrayComponentType */ public static Object convertToPrimitiveArray(Object array, Class convertedArrayComponentType) { // Collect data regarding arguments final boolean arrayOfPrimitives = isArrayOfPrimitives(array); final boolean arrayOfCharPrimitives = isArrayOf(array, char.class); final boolean arrayOfCharacters = isArrayOf(array, Character.class); final boolean arrayOfStrings = isArrayOf(array, String.class); final boolean arrayOfNumbers = isArrayOf(array, Number.class); // Check if array is an array of strings, primitives or wrapped primitives if (!arrayOfPrimitives && !arrayOfNumbers && !arrayOfStrings || arrayOfCharPrimitives || arrayOfCharacters) { throw new IllegalArgumentException(array + " must be an array of of strings, primitives or boxed primitives (byte, boolean, short, int, float, long, double)"); } // Check if it's assignable from Number of String if (!convertedArrayComponentType.isPrimitive() || convertedArrayComponentType.isAssignableFrom(char.class)) { throw new IllegalArgumentException(convertedArrayComponentType + " must be a primitive(excluding char)"); } try { return convertArrayInternal(array, convertedArrayComponentType); } catch (InvocationTargetException e) { // This can happen due to errors in conversion throw (RuntimeException) e.getTargetException(); } catch (Exception e) { // This should never happen log.error("Something went really wrong in ArrayUtils.convertArray method.", e); } // To satisfy the compiler return null; } private static Object convertArrayInternal(Object array, Class convertedArrayComponentType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Lookup the primitive parse method or the boxed primitive valueOf method final Method convertMethod; if (convertedArrayComponentType.isPrimitive()) { convertMethod = primitiveParseMethodLookup.get(convertedArrayComponentType); } else { convertMethod = valueOfMethodLookup.get(convertedArrayComponentType); } // If the array is an array of primitives lookup the get method final Method primitiveArrayGetMethod = primitiveArrayGetMethodLookup.get(array.getClass().getComponentType()); // Get length and create new array final int arrayLength = Array.getLength(array); final Object castedArray = Array.newInstance(convertedArrayComponentType, arrayLength); for (int i = 0; i < arrayLength; i++) { final Object value; if (primitiveArrayGetMethod != null) { value = primitiveArrayGetMethod.invoke(null, array, i); } else { value = Array.get(array, i); } final String stringValue = String.valueOf(value); final Object castedValue = convertMethod.invoke(null, stringValue); Array.set(castedArray, i, castedValue); } return castedArray; } } It can be used like this: double[][] testArray = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}}; double[] doubleArray = Arrays.copyOf(testArray[1], testArray[1].length); float[] floatArray = (float[]) ArrayUtils.convertToPrimitiveArray(doubleArray, float.class); A: Swift 5 extension Collection where Iterator.Element == Float { var convertToDouble: [Double] { return compactMap { Double($0) } } } extension Collection where Iterator.Element == Double { var convertToFloat: [Float] { return compactMap { Float($0) } } } A: Kotlin val doubleArray = arrayOf(2.0, 3.0, 5.0) val floatArray = FloatArray(doubleArray.size) { i -> doubleArray[i].toFloat() }
{ "language": "en", "url": "https://stackoverflow.com/questions/7513434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: JPA Annotations for many-to-many relation between objects of the same entity I want to implement a Role Hierarchy but am rather new to JPA Annotations. I have a Role Entity with a name and an id(implicit via AbstractPersistable): @Entity @Table(name="role") public class Role extends AbstractPersistable<Long> { private static final long serialVersionUID = 8127092070228048914L; private String name; Now I want to be able to define the following relationships: * *a Role can have many child roles *a Role can be child to many roles How would I do that with Hibernate annotations? Can I define this inside the Role Entity @ManyToMany(cascade = CascadeType.MERGE) @JoinTable( name = "role_hierarchy", joinColumns = { @JoinColumn(name = "role_id")}, inverseJoinColumns={@JoinColumn(name="child_role_id")}) private List<Role> roles; @ManyToMany(cascade = CascadeType.MERGE) @JoinTable( name = "role_hierarchy", joinColumns = { @JoinColumn(name = "child_role_id")}, inverseJoinColumns={@JoinColumn(name="role_id")}) private List<Role> children; Am I on the right track? What am I missing? Thank's a lot for your help! EDIT: - removed as it has been solved - EDIT 2: Looks like I have some bug in my application stack. On the model defining level the role_hierarchy is working out just fine, so never mind EDIT 1... BUT: Both ways seem to work (that is createing the m:n table entry, cascading delete and retrieval of parents and children for an entity): * *my proposal of defining a join column for both sides with no mappedBy property at the @ManyToMany annotation *as well as defining an owning side and an inverse side. What's the difference? Does it matter? A: Bidirectional relationship consists of owning and inverse sides. At the owning side you declare physical properties of the relationship: @ManyToMany(cascade = CascadeType.MERGE) @JoinTable(name = "role_hierarchy", joinColumns = { @JoinColumn(name = "role_id")}, inverseJoinColumns={@JoinColumn(name="child_role_id")}) private List<Role> roles; At the inverse side you point at the corresponding owning side with mappedBy attribute: @ManyToMany(cascade = CascadeType.MERGE, mappedBy = "roles") private List<Role> children; For many-to-many relationships it doesn't matter which side is the owning side (as long as you modify both sides consistently, since only changes at the owning side are propagated to the database). See also: * *2.2.5.3.2. Many-to-many
{ "language": "en", "url": "https://stackoverflow.com/questions/7513440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Does Excel 2007 supports plugins written in Java? Possible Duplicate: I want to write a plugin for Excel 2007 in JAVA I want to extend some functionality of Excel 2007. So I want to write my code in Java, will it be supported in Excel? A: It's not easy as Java "applications" run inside a Java virtual machine and is ... a challenge to find a way to call class or instance methods from outside. The XLLoop framework looks promising to me. That's at least one way to code and use java based functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Do not restore passwords inserted in iOS Keychain issue I'm developing an application for an iPad2 that needs to write some items in Keychain but I don't want it replicates in every computer I plug, doing a backup/restore of the device. I'm using kSecAttrAccessible key to select the kind of accesibility I want with kSecAttrAccessibleWhenUnlockedThisDeviceOnly value to be sure that if I do a backup of all things that are in the device, the Keychain is not going to be present in that backup. So I proceed in this way: I reset the Keychain, insert a item in Keychain and dump all the content of Keychain, so I see that the item is there. Then I do a backup of the iPad. I reset the Keychain and restore the backup so no key should be in the Keychain as long as the restore procedure doesn't deal with the Keychain. Next time I run the application, I dump the contents of the Keychain and the key is there, so it's not working as it should. I'm using iphone-lib (http://code.google.com/p/iphone-lib/) to dump and reset credentials in my iPad. My SDK version is 4.3. The code I use to insert the item in the Keychain is the following: NSMutableDictionary *dic = [NSMutableDictionary dictionary]; NSData* identifier = [@"mypassword" dataUsingEncoding: NSASCIIStringEncoding]; [dic setObject:(id)kSecAttrAccessibleWhenUnlockedThisDeviceOnly forKey:(id)kSecAttrAccessible]; [dic setObject:identifier forKey:(id)kSecAttrGeneric]; [dic setObject:@"myaccount" forKey:(id)kSecAttrAccount]; [dic setObject:@"myservice" forKey:(id)kSecAttrService]; [dic setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass]; [dic setObject:identifier forKey:(id)kSecValueData]; OSStatus error = SecItemAdd((CFDictionaryRef)dic, NULL); Thank you! A: There two cool examples (with working sample code) from Apple, that helped me to understand how keychain service works on iOS. I suggest you to look at them, and hope they will help you to resolve your issue: * *Generic Keychain : This sample shows how to add, query for, remove, and update a keychain item of generic class type. Also demonstrates the use of shared keychain items. All classes exhibit very similar behavior so the included examples will scale to the other classes of Keychain Item: Internet Password, Certificate, Key, and Identity. *AdvancedURLConnections : This sample demonstrates various advanced networking techniques with NSURLConnection. Specifically, it demonstrates how to respond to authentication challenges, how to modify the default server trust evaluation (for example, to support a server with a self-signed certificate), and how to provide client identities. A: kSecAttrAccessibleWhenUnlockedThisDeviceOnly maybe the reason. Can you try something else? eg. kSecAttrAccessibleWhenUnlocked
{ "language": "en", "url": "https://stackoverflow.com/questions/7513446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to block the accept method of socket when server is waiting for the connection from client? how to block the accept method of socket when server is waiting for the connection from client? my code is here: ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444, 100); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); // Thread input = new InputThread(clientSocket.getInputStream()); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } I want to block the accept method which is waiting for the client.. A: serverSocket.accept() itself is blocking and blocks until a connection is made.
{ "language": "en", "url": "https://stackoverflow.com/questions/7513447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Weld CDI: how to make one bean class satisfy any of multiple qualifiers? From reading the Weld docs I don't think this can be done, but I could really do with it, so thought I'd ask - if there's not a way with CDI, maybe there's a pattern workaround... I've created a custom qualifier with a member: @Qualifier @Target({TYPE, METHOD, FIELD, PARAMETER}) @Retention(RUNTIME) public @interface JobBinding { JobType value(); } JobType is an enum: public enum JobType { JOB_A, JOB_B, // etc - there are quite a few Say most jobs need building in a slightly different way, so I have builder classes related to the jobs. These are annotated with a JobBinding annotation given the relevant JobType: @JobBinding(JobType.JOB_A) public class JobABuilder implements JobBuilder { .... When I need to build, I use programmatic lookup: @Inject @Any private Instance<JobBuilder> builderSource; private JobType myJobType; ... builderSource.select(new JobBindingQualifier(myJobType).get(); JobBindingQualifier is a custom class: public class JobBindingQualifier extends AnnotationLiteral<JobBinding> implements JobBinding { private static final long serialVersionUID = -822150300665931157L; private JobType type; public JobBindingQualifier(JobType type) { this.type = type; } @Override public JobType value() { return type; } } So far, great - CDI working brilliantly. However, what if 2 of these jobs, JOB_X and JOB_Y, are built in exactly the same way? I only need one builder class, which I'd like to be instantiated for either of those options - new JobBindingQualifier(JobType.JOB_X) or new JobBindingQualifier(JobType.JOB_Y). If I annotate JobXAndYBuilder with both @JobBinding(JOB_X) and @JobBinding(JOB_Y), I get a compiler error about the duplicated annotation. To get around this I could change the value of the annotation to an array of JobTypes, and you would annotate the builder like @JobBinding(JobType.JOB_X, JobType.JOB_Y) with the constructor called there using an ellipsis to produce the array. However, if I did that, how could I look that up programmatically using either of the jobTypes? Weld docs suggest that you would have to have both; I'd need to provide the exact arguments: builderSource.select(new JobBindingQualifier(JobType.JOB_X, JobType.JOB_Y).get(); when I want either to be sufficient to lookup the class: builderSource.select(new JobBindingQualifier(JobType.JOB_X).get(); //or builderSource.select(new JobBindingQualifier(JobType.JOB_Y).get(); Using the array really just changes the value that you have to match when looking up. I really need a way of annotating a class twice with the same qualifier annotation, and then being able to look it up with any combination of them. Otherwise I'll have to provide a builder class each for X and Y, when one would suffice. Any ideas? Thanks in advance! A: As I said in my comment there is no straight way to have an OR relation when you have two or more qualifiers on a bean class. So the solution to have the same Bean with another qualifier is to use the Producer mechanism. In your example you can create you first class as usual : @JobBinding(JobType.JOB_X) public class JobABuilder implements JobBuilder { .... } and after that create a producer method in either in the first class or in a dedicated producers class like that public class MoreJobsProducer { @Produces @JobBinding(JobType.JOB_Y) protected JobBuilder prodJobYBuilder(@New @JobBinding(JobType.JOB_X) JobBuilder theJob) { return theJob; } } In the paramaters of the producer method you Inject your former bean with its own qualifier and the @Newqualifier which create a new instance of the bean to be sure you avoid some scoping issues (read the Weld doc for more info). It should do the "Job".
{ "language": "en", "url": "https://stackoverflow.com/questions/7513454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Border, Label for a line segment WPF I am trying to create effects like rail track and streets-with-border-and-label in WPF. How do I add a border to a line segment and a label that is along the line segment? I tried Border class, but it creates a rectangular border. For the label, I tried Text on a path but it takes long time for processing as I have > 5000 lines in the canvas. Any pointers to resources, hints, examples would be very helpful and appreciated. Thanks! A: I am not sure to understand what's your goal, but the vector way is mandatory, IMHO. Anyway, if the WPF way is too heavy, you may try to create by yourself with the GraphicsPath of GDI+, that allows to manipulate an arbitrary path. The lines are a lot, but maybe once created an optimized version in memory, the calculation could be faster than WPF (which suffers of the animation capability, thus is heavy). http://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.graphicspath.aspx Just in case, describe a bit better what's your target project. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7513462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }