text
stringlengths
8
267k
meta
dict
Q: Counting the number of shortest paths through a node in a DAG I'm looking for an algorithm to count the number of paths crossing a specific node in a DAG (similar to the concept of 'betweenness'), with the following conditions and constraints: I need to do the counting for a set of source/destination nodes in the graph, and not all nodes, i.e. for a middle node n, I want to know how many distinct shortest paths from set of nodes S to set of nodes D pass through n (and by distinct, I mean every two paths that have at least one non-common node) What are the algorithms you may suggest to do this, considering that the DAG may be very large but sparse in edges, and hence preference is not given to deep nested loops on nodes. A: You could use a breadth first search for each pair of Src/Dest nodes and see which of those have your given node in the path. You would have to modify the search slightly such that once you've found your shortest path, you continue to empty the queue until you reach a path that causes you to increase the size. In this way you're not bound by random chance if there are multiple shortest paths. This is only an option with non-weighted graphs, of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: CouchRest Model use a custom value instead of guid for _id field I wonder if there is a way to use a custom string value (e.g. name of the object) as the _id field instead of a guid in CouchRest Model. E.g. class Cat < CouchRest::Model::Base property :name end By default, it will use a guid as _id field. But I just want to use the name property as _id. A: You could try using unique_id as follows class Cat < CouchRest::Model::Base property :name unique_id :name end unique_id will call any method before the document is first saved, and assign that as the _id of the document. However you'll then have a Cat documents with both the _id and name fields set. They might even come out of sync if the name is changed. A possibly better option would be to create a getter and setter which would simply change the _id attribute of the document class Cat < CouchRest::Model::Base def name self['_id'] end def name=(value) self['_id']=value end end Seeing as there is no extra property in this case, name will always return the id of the document. However, it won't be possible to change the name once the document is written as reassigning the _id will have no effect. For more information: Here's the rdoc for unique_id. You can also check out couch rest models' wiki entry for validations
{ "language": "en", "url": "https://stackoverflow.com/questions/7534552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Drawing textures with variable transparency I am a moderately experienced C# developer, but I'm new to XNA and graphics in general. I'm making a 2D game and I'm trying to draw a texture that partially transparent. The desired transparency value is stored in a float variable. The only solution I've found is to directly edit the alpha values in the texture each frame, but that seems inefficient. I've tried using alpha blending, but I haven't been able to figure out how to use my own transparency value. Is there a better way to do it? Edit: Added more information. A: if you are using spritebatch is easy: float alpha = desired_alpha; spritebatch.Draw(texture, pos, source, Color.White * alpha); A: You could try using this Color constructor to pass in your alpha value: http://msdn.microsoft.com/en-us/library/dd231957(v=xnagamestudio.31).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7534554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Current_user devise method returns nil outside the user controller Is this a scope/routes problem? The current_user works in the user controller. Outside, in another controller/view, this returns nil. Even if the user is logged in, the user_signed_in? method returns false. I know I am missing something, just not able to point my finger. What is the right way to do this? A: It works for me in other controllers. A wild guess: maybe the other controller needs: before_filter :authenticate_user! A: Found the problem. It was the sessions. Apparently, the current_user and other methods were not behaving right because of cookies. I had subdomains and the problem was because of that https://github.com/fortuity/rails3-subdomain-devise/wiki/Tutorial-%28Walkthrough%29. This git tutorial helped. Thanks! A: I was having the same problem, I needed to put this in my layout, I was using a different layout than application: = csrf_meta_tags A: Same thing happened to me but the problem was when I made an ajax request. This fixed it (in haml). This makes sure that all ajax request carry the csrf token: :coffee require ['jquery'], ($)-> $.ajaxSetup headers: 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') Make sure this is in the header: = csrf_meta_tags
{ "language": "en", "url": "https://stackoverflow.com/questions/7534558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Massive URL Decode in MySQL I have a MySQL table with 10,000+ entries. There are four columns in the table. One of them is URL. Some of the URL values are encoded, some are decoded. I want to have them all be decoded. How can I do this either with PHP directly or MySQL? Thanks! A: Is this what you want? $result = $db->query("SELECT encoded_url FROM table"); while($row = mysql_fetch_assoc($result)){ $decoded = your_function_to_decode($row['encoded_url']); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl trapping Ctrl-C with threads in bash While I see how to have Perl trap Ctrl-C (sigint) in bash; I'm getting lost at why does it fail with threads; I'm trying the following script: #!/usr/bin/env perl use threads; use threads::shared; # for shared variables my $cnt :shared = 0; sub counter() { while (1) { $cnt++; print "thread: $cnt \n"; sleep 1; } } sub finisher{ ### Thread exit! ... print "IIII"; threads->exit(); die; }; # any of these will cause stop of reaction to Ctrl-C $SIG{INT} = \&finisher; $SIG{INT} = sub {print "EEE\n" ;} ; $SIG{INT} = 'IGNORE'; # setting to DEFAULT, brings usual behavior back #~ $SIG{INT} = 'DEFAULT'; my $mthr = threads->create(\&counter); $mthr->join(); ... and as soon as the SIGINT handler is set to anything else than the default (where Ctrl-C causes exit), it basically causes for the script to stop reacting on Ctrl-C any longer: $ ./test.pl thread: 1 ^Cthread: 2 ^C^Cthread: 3 ^C^C^C^Cthread: 4 thread: 5 thread: 6 thread: 7 thread: 8 Terminated ... and I have to sudo killall perl in order to terminate the script. There is a bit on threads and Ctrl-C in these links: * *Sending sig INT ( control C ) to threads - Dev Shed *SOLVED: Is this a bug of perl threads ? - Perl Monks *How do we capture CTRL ^ C - Perl Monks *Is the signal handler supposed to work like this? ... but I cannot say if it conclusively answers whether "capturing" Ctrl-C under perl in bash is definitely impossible? Thanks in advance for any answers, Cheers! Ok, I think I got it (but I'm leaving the previous entry (below) for reference ...) The trick turns out to be that, from the main SIGINT handler, one must signal the thread via kill - AND then thread also needs to have a separate SIGINT handler (from the first link in OP); AND instead of just join(), one needs to use the code in the answer by @ikegami: #!/usr/bin/env perl use threads; use threads::shared; # for shared variables my $cnt :shared = 0; my $toexit :shared = 0; sub counter() { $SIG{'INT'} = sub { print "Thread exit\n"; threads->exit(); }; my $lexit = 0; while (not($lexit)) { { lock($toexit); $lexit = $toexit; } $cnt++; print "thread: $cnt \n"; sleep 1; } print "out\n"; } my $mthr; sub finisher{ { lock($toexit); $toexit = 1; } $mthr->kill('INT'); }; $SIG{INT} = \&finisher; $mthr = threads->create(\&counter); print "prejoin\n"; #~ $mthr->join(); while (threads->list()) { my @joinable = threads->list(threads::joinable); if (@joinable) { $_->join for @joinable; } else { sleep(0.050); } } print "postjoin\n"; I may be overkilling it with the $toexit there, but at least now this is the result: $ ./test.pl prejoin thread: 1 thread: 2 thread: 3 ^CThread exit postjoin Many thanks to all for the solution :) Cheers!   Thanks to the suggestion by @mob for PERL_SIGNALS to unsafe (note, Perl 5.14 does not allow "internal" setting of $ENV{'PERL_SIGNALS'}), I'm getting somewhere - now Ctrl-C is detected - but it either terminates with a segfault, or with error: #!/usr/bin/env perl use threads; use threads::shared; # for shared variables my $cnt :shared = 0; my $toexit :shared = 0; sub counter() { my $lexit = 0; while (not($lexit)) { { lock($toexit); $lexit = $toexit; } $cnt++; print "thread: $cnt \n"; sleep 1; } print "out\n"; #~ threads->detach(); # Thread 1 terminated abnormally: Cannot detach a joined thread #~ exit; } my $mthr; # [http://code.activestate.com/lists/perl5-porters/164923/ [perl #92246] Perl 5.14 does not allow "internal" setting of $ENV ...] sub finisher{ ### Thread exit! ... #~ print "IIII"; # anything here results with: Perl exited with active threads: #~ threads->exit(); #~ threads->join(); #~ $mthr->exit(); #~ $mthr->join(); #~ $mthr->detach(); #~ $mthr->kill(); #~ threads->exit() if threads->can('exit'); # Thread friendly #~ die; { lock($toexit); $toexit = 1; } #~ threads->join(); # }; # any of these will cause stop of reaction to Ctrl-C $SIG{INT} = \&finisher; #~ $SIG{INT} = sub {print "EEE\n" ; die; } ; #~ $SIG{INT} = 'IGNORE'; # setting to DEFAULT, brings usual behavior back #~ $SIG{INT} = 'DEFAULT'; $mthr = threads->create(\&counter); print "prejoin\n"; $mthr->join(); print "postjoin\n"; With the comments as above, that code react with: $ PERL_SIGNALS="unsafe" ./testloop06.pl prejoin thread: 1 thread: 2 thread: 3 ^Cthread: 4 out Segmentation fault Result is the same if I add the following that uses Perl::Signals::Unsafe: $mthr = threads->create(\&counter); UNSAFE_SIGNALS { $mthr->join(); }; Almost there, hopefully someone can chime in ... :) A: Signal handlers are only called between Perl opcodes. Your code is blocked in $mthr->join();, so it never gets to handle the signal. Possible solution: use Time::HiRes qw( sleep ); # Interruptable << $_->join() for threads->list; >> while (threads->list()) { my @joinable = threads->list(threads::joinable); if (@joinable) { $_->join for @joinable; } else { sleep(0.050); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: make: -c: Command not found First of all, I'm trying to get used to makefiles but yet I#m new with this. The following file is supposed to, first, compile all ./src/*.cpp files to ./src/*.o (where the filename survives) and afterwards complete compilation with simulation.cpp and linking the whole stuff together. Now, make returns the error message: make: -c: Command not found I have literally no clue how to proceed! Would the wildcard-construct even work in the way desired? Thanks a lot for your effort! #basic stuff TRUE = 1 FALSE = 0 SHELL := #!/bin/bash # path names SRCPATH = ./src/ CLEANPATH = ./res/ \ ./crash/ # source files. MAIN = simulation.cpp OBJS = $(wildcard $(SRCPATH)*.o) SRCS = $(wildcard $(SRCPATH)*.cpp) INCLUDES = $(wildcard $(SRCPATH)*.h) #GLOBAL MACROS PASSED TO PROGRAM! MODEL_MRT = $(TRUE) #if true model used is MRT else SRT PARALLEL = $(TRUE) GRAVITY = $(TRUE) # output file name OUT = simulation # C++ compiler flags (-g -O2 -Wall) CXXFLAGS = -g -Wall -O -fopenmp CXXDEFINES = -D MODEL=$(MODEL_MRT) -D PARALLEL=$(PARALLEL) -D GRAVITY=$(GRAVITY) # compiler CXX = g++ $(OUT) : $(OBJS) $(CXX) $(CXXFLAGS) $(MAIN) $(OBJS) $(CXXDEFINES) -o $(OUT) $(OBJS) : $(SRCS) $(INCLUDES) $(CXX) $(CXXFLAGS) -c $(SRCS) -o $(OBJS) clean : $(OUT) rm $(OBJS) rm $(CLEANPATH)/*.* run : $(OUT) clean ./$(OUT) .PHONY: clean run A: This line: SHELL := #!/bin/bash is incorrect. Your makefile should work perfectly well if you leave that line out altogether. If you do need something there, try SHELL := /bin/bash A: You're tricking make with your SHELL variable, it sees is at empty as it is just a comment. Change SHELL := #!/bin/bash to SHELL := /bin/bash
{ "language": "en", "url": "https://stackoverflow.com/questions/7534572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Open Graph Beta, Display another string in Custom Action Caption using Text Templates if Object Property is null? How can we display a different string in a custom action caption using text templates or formatters if a Profile property is null? Facebook displays a default caption for an action if a string property is not set or is empty. For example, a caption for an action with a Profile object, Cooked with {SomeProfile}, displays the profile's description or something else if SomeProfile is not defined. Another example I have an Cook action type. Cook is connected to a Profile object type. Cook has another Profile action property SomeoneICookedWith. I set the caption for Cook to I cooked this with {SomeoneICookedWith}. If SomeoneICookedWith is not empty and set to URL to John's profile, the caption on the timeline displays I cooked this with John. If SomeoneICookedWith is empty, the caption on the timeline displays John is on Facebook. Join Facebook to connect with John and others you may know. Facebook gives people the power to share and makes the world more open and connected.. A: It displays the og:description of the object if the action is aggregated or if the News Feed attachment isn't configured. If you are trying to link directly to a Facebook profile, you can't control the og:description. I would recommend making proxy pages with your own metatags that just redirect users but then you control the tags instead of us. A: I've found that the og:description tag doesn't seem to be working with the og beta. The linter grabs my the description and my other custom object properties just fine, but when actually posting them, the only thing that shows up is the image, link, and the title. Description and everything else are left off, and the default 'Description' shows up. I'm beating my head against a wall since the Linter says it's working fine but it's not in actuality. Paul's answer sounds ideal, but if you redirect the page, then Facebook follows the redirect and grabs the tags from the redirected page. Has anyone else run into this, and what's a good solution?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: setStreetView() and setTrafficView() is not working im working on map view and i have set four views normal , Satellite ,Traffic and Street normal and satellite is working fine but when i click on street and traffic its not get associated views here is code.can any one kindly tell me how to post code after once as im unable to share my xml in this question it my first question so please help . private MapView mapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapview); mapView = (MapView) findViewById(R.id.mapview); mapView.setBuiltInZoomControls(true); mapView.setClickable(true); Drawable marker=getResources().getDrawable(R.drawable.icon); marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); InterestingLocations funPlaces = new InterestingLocations(marker); mapView.getOverlays().add(funPlaces); GeoPoint pt = funPlaces.getCenter(); // get the first-ranked point mapView.getController().setCenter(pt); mapView.getController().setZoom(15); // cheating. We could iterate // and figure out a proper zoom. } @Override protected boolean isLocationDisplayed() { return false; } @Override protected boolean isRouteDisplayed() { return false; } public void myClickHandler(View target) { switch(target.getId()) { case R.id.sat: mapView.setSatellite(true); break; case R.id.street: mapView.setStreetView(true); break; case R.id.traffic: mapView.setTraffic(true); break; case R.id.normal: mapView.setSatellite(false); mapView.setStreetView(false); mapView.setTraffic(false); break; } } A: Take a look at the solution I posted yesterday on a similar question, which is working. The implementation remembers which mode you're in as well: Is there a method to check whether the current Map is in Map or Satellite mode? Hopefully this will help you in resolving your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ViewBinder setViewValue for ListView item leads to multiple CheckBoxes checked I'm using a ListView which has: * *list item click *CheckBox click I can save the cursorPosition by using view.setTag(cursor.getPosition()) and I can take necessary action on the checked item but when I scroll down, I see several other CheckBoxes checked(visual only). As a work around I tried setting the view description, saving CheckedBox view ids in list and then iterate to see if CheckBox needs to be shown as checked. But views appear to be reused as I scroll down(same view ids). How can I only show the actual checked CheckBoxes? Code: public class MyViewBinder implements ViewBinder { public boolean setViewValue(View view, final Cursor cursor, int columnIndex) { int viewId = view.getId(); switch (viewId) { case R.id.checkbox: view.setTag(cursor.getPosition()); return true; case R.id..... ....... } Used as: mySimpleCursorAdapter.setViewBinder(myViewBinder); A: I don't have too much experience with the ViewBinder Interface but have you considered using setChoiceMode() on the listview (API reference)? You can set it to CHOICE_MODE_MULTIPLE so that android adds the checkboxes for you. You shouldn't need to worry about maintaining the checked items this way. API Demo example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In memory ActiveMQ attempting to respond to temporary queue before it's fully created? We have a scenario where we need to send a synchronous message over our an in memory activemq broker. Our synchronous client side code looks like this: Session responseSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue responseQ = responseSession.createTemporaryQueue(); msg.setJMSReplyTo(responseQ); QueueReceiver qReceiver = ((QueueSession) responseSession).createReceiver(responseQ); sendMessage(msg, false, timeout); Message response = qReceiver.receive(timeout); Most of the time our server response code works fine but occasionally we get a stacktrace like: javax.jms.InvalidDestinationException: Cannot publish to a deleted Destination: temp-queue://ID:<removed> at org.apache.activemq.ActiveMQSession.send(ActiveMQSession.java:1632) at org.apache.activemq.ActiveMQMessageProducer.send(ActiveMQMessageProducer.java:231) at org.apache.activemq.ActiveMQMessageProducerSupport.send(ActiveMQMessageProducerSupport.java:269) I'm suspecting that the root problem is that the temporary queue isn't fully setup or that it hasn't been published or whatever it is that it does by the time the service attempts to publish a message to it. In my server code I've wrapped the send call in a loop catching the InvalidDestinationException, sleeping for a second and trying again until it succeeds. Since I've added this, whenever I see the exception on the second try it works. Am I doing something wrong? Should I be doing something on the client to sync or flush or otherwise ensure that the temporary queue is up before sending the message to the server? Is there something else I should be doing on the server side to ensure the queue is up? Can I otherwise safely attempt to create the temporary queue on the server side if it thinks it isn't already there? Note: We were using ActiveMQ 5.3.0 but today I tried 5.5.0 with the same results. A: That's rather strange and I don't think it should be happening as the temp destination is created locally and should be in the Connections map of temp destinations. If you could create a simple JUnit test case the demonstrates the issue you should open a new Jira and attach it for review.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# problem with flags I have an enum (flag) [Flags] public enum DisplayMode { None, Dim, Inverted, Parse, Italics, Bold } I want to assign two of the flags to a variable, like this: var displayFlags = DisplayMode.Parse | DisplayMode.Inverted; However, when I debug and hover over this variable immediately after it is assigned, it says displayFlags is DisplayMode.Dim | DisplayMode.Inverted. What am I missing/not understanding? A: You've missed assigning the flags sensible values, e.g.: [Flags] public enum DisplayMode { None = 0, Dim = 1, Inverted = 2, Parse = 4, Italics = 8, Bold = 16 } That way each value has a separate bit in the numeric representation. If you don't trust your ability to double values, you can use bit shifting: [Flags] public enum DisplayMode { None = 0, Dim = 1 << 0, Inverted = 1 << 1, Parse = 1 << 2, Italics = 1 << 3, Bold = 1 << 4 } From the documentation from FlagsAttribute: Guidelines for FlagsAttribute and Enum * *Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value. *Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap. ... A: By default, an enum will assign consecutive values to the members. So you've essentially got: [Flags] public enum DisplayMode { None = 0, Dim = 1, Inverted = 2, Parse = 3, Italics = 4, Bold = 5 } That doesn't work for binary/flags. So you need to be explicit: [Flags] public enum DisplayMode { None = 0, Dim = 1, Inverted = 2, Parse = 4, Italics = 8, Bold = 16 } A: You're not providing appropriate values to your enum upon declaration: [Flags] public enum DisplayMode { None = 0, Dim = 1, Inverted = 2, Parse = 4, Italics = 8, Bold = 16 } A: You need to specify the values of the flags explicitly. As declared, Parse is 3, which is Dim | Inverted. Try [Flags] public enum DisplayMode { None = 0, Dim = 1 << 0, Inverted = 1 << 1, Parse = 1 << 2, Italics = 1 << 3, Bold = 1 << 4 } A: You need to define the enumertion values as powers of two: [Flags] public enum DisplayMode { None = 1, Dim = 2, Inverted = 4, Parse = 8, Italics = 16, Bold = 32 } More information here: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx A: Since you are using flags, you need to think in binary terms so you should increase your values by a multitude of 2 each time. For example, think: 0001 = 0x01, 0010 = 0x02, 0100 = 0x04, 1000 = 0x08 and so on...
{ "language": "en", "url": "https://stackoverflow.com/questions/7534580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jira update ticket using script Is there any way update Jira ticket using scripts? Basically I will have a build from hudson/jenkins and if I get the Jira ID in all changes then corresponding ID should be updated to release version in Jira? Can any one help me? I am bit new to Jira admin. A: It's a bit difficult to understand the question but there is a Jira plugin for jenkins that does what I think you're asking: Here is a link to the Jenkins JIRA plugin, you'll need to make sure the web service API for JIRA is enabled in the JIRA admin interface. A: JIRA has a SOAP (and in some version REST) web service that would allow you to make an HTTP request to JIRA to make changes to a ticket. If the Jenkins plugin that Mike K suggested does not work for you, then you can look at writing a script that would make the request that you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CR vs LF perl parsing I have a perl script which parses a text file and breaks it up per line into an array. It works fine when each line are terminated by LF but when they terminate by CR my script is not handling properly. How can I modify this line to fix this my @allLines = split(/^/, $entireFile); edit: My file has a mixture of lines with either ending LF or ending CR it just collapses all lines when its ending in CR A: If you have mixed line endings, you can normalize them by matching a generalized line ending: use v5.10; $entireFile =~ s/\R/\n/g; You can also open a filehandle on a string and read lines just like you would from a file: open my $fh, '<', \ $entireFile; my @lines = <$fh>; close $fh; You can even open the string with the layers that cjm shows. A: Perl can handle both CRLF and LF line-endings with the built-in :crlf PerlIO layer: open(my $in, '<:crlf', $filename); will automatically convert CRLF line endings to LF, and leave LF line endings unchanged. But CR-only files are the odd-man out. If you know that the file uses CR-only, then you can set $/ to "\r" and it will read line-by-line (but it won't change the CR to a LF). If you have to deal with files of unknown line endings (or even mixed line endings in a single file), you might want to install the PerlIO::eol module. Then you can say: open(my $in, '<:raw:eol(LF)', $filename); and it will automatically convert CR, CRLF, or LF line endings into LF as you read the file. Another option is to set $/ to undef, which will read the entire file in one slurp. Then split it on /\r\n?|\n/. But that assumes that the file is small enough to fit in memory. A: You can probably just handle the different line endings when doing the split, e.g.: my @allLines = split(/\r\n|\r|\n/, $entireFile); A: It will automatically split the input into lines if you read with <>, but you need to you need to change $/ to \r. $/ is the "input record separator". see perldoc perlvar for details. There is not any way to change what a regular expression considers to be the end-of-line - it's always newline.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Creating a hash in Perl How do I create a hash in Perl which uses the directory name as the key, and then stores both the count of files in the directory as well as the names each of the files? Is it possible using hash of hashes or hash of arrays? I would appreciate any pointers. A: Hash values must be scalars, so the real question is how to get two values into one scalar. References are scalars, so a reference to a hash would work. $data{$dir} = { file_count => 0+@files, files => \@files, }; Note that the file count is redundant. 0+@{ $data{$dir}{files} } could be used for the file count. If you choose to get rid of this redundancy, you could use $files{$dir} = \@files; The file count is available as 0+@{ $files{$dir} } and the files are available as @{ $files{$dir} } (The 0+ can be omitted in scalar context.) A: If I understand you correctly, this seems to do the trick (the printing of the hash using Dumper() at the end is just to show you what the hashref contains): #!/usr/bin/perl -w use strict; use Data::Dumper; my $dir = $ENV{PWD}; opendir( DIR, $dir ) or die $!; my @files = grep { -f "$dir/$_" } readdir( DIR ); my $hash = { $dir => { count => scalar( @files ), files => \@files, } }; print Dumper( $hash ), "\n"; A: Personally almost always I use hash references instead perl hashes (and arrayrefs instead perl arrays, too). Example: my $dirs = { '/home/user' => [ '.profile', '.bashrc', 'My_pic.png' ], '/root' => [ '.profile', '.zshrc' ] }; my $var = { (...) } makes hash reference, => is just a synonym of comma , but allows distinguishing between hash keys and values. [ (...) ] makes annonymous array reference which is assigned as hash value. You don't have to store redundant information like number of files, you can just evaluate array in scalar context: my $root_files = $dirs->{'/root'}; $size = scalar @{$root_files}; You can read more about hashes here and here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: QT project won't link to functions that have std::wstring as parameter. I have a VS2010 dll I'm trying to link into a QT project. I'm using QT version 4.7.4 that I built using MSVC2010. QT Creator is also using MSVC2010 to compile. I'm implicitly linking by including the header files, referencing the .lib in the pro file, and placing the .dll in the execution folder. Right now I'm only using functions from one class from the dll. Some of the functions link, some of them don't. Dependency walker confirms that they're all being exported just fine. The functions that don't link take a std::wstring or a std::wstring* as a parameter. Is something redefining wstring somewhere? Any ideas would be helpful. A: So for anyone else getting this problem, I just figured it out. The linker was breaking because Visual Studio by default maps wchar_t to __wchar_t, and QT does not. To fix: Go to Project Settings -> Configuration Properties -> C/C++ -> Language and uncheck the "Treat WChar_t As Built in Type" property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: django and database connection pools when connecting to many databases If I want my application to connect to potentially hundreds of different databases, what effect will this have on database pools? I'm assuming django has database connection pooling, and if I am connection to 1000 different databases, that will result in allot of memory used up in connection pools no? A: Django does not have database connection pooling, it leaves this up to other tools for that purpose (for example pg-bouncer or pg-pool for PostgreSQL). So there is no worry with the number of database you're connecting to in terms of keeping those connections open and using up a bunch of RAM.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Save multiple graphs one after another in one pdf file Possible Duplicate: How to print R graphics to multiple pages of a PDF and multiple PDFs? I am new to R and have a quick question. The following code writes one .pdf file for each graph. I would like to add figures one after another in ONE pdf file. Thank you so much. Greatly appreciate any help. i=5 while (i<=10) { name1="C:\\temp\\" num=i ext = ".pdf" path3 = paste(name1,num,ext) par(mfrow = c(2,1)) pdf(file=path3) VAR1=rnorm(i) VAR2=rnorm(i) plot(VAR1,VAR2) dev.off() i=i+1 } A: Just move your pdf() function call and your dev.off() call outside the loop: somePDFPath = "C:\\temp\\some.pdf" pdf(file=somePDFPath) for (i in seq(5,10)) { par(mfrow = c(2,1)) VAR1=rnorm(i) VAR2=rnorm(i) plot(VAR1,VAR2) } dev.off() Note my use the the seq() function to loop instead of while() with a counter variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Have I used STL? Or not? I'm confused about some of the documentation at cplusplus.com. Have I used the standard template library with either of these two lines of code? for (std::string::const_iterator it = str.begin(); l < data.size; ++it, ++l) and tile_tag(): distance(std::numeric_limits<int>::max()), dir(unknown_direction), used(false) See: http://www.cplusplus.com/reference/string/string/begin/ and http://www.cplusplus.com/reference/std/limits/numeric_limits/ If I have used STL, how can I modify them to do what they do without STL? Thanks! EDIT: I guess this is OUR definition of STL: http://www.sgi.com/tech/stl/stl_index_cat.html I don't see const_iterator...but I do see max. But is that the max I used? A: Yes, you used it, since std::string alone is "part of the STL", but, more importantly, you are using the iterators, which are a distinctive trait of the STL. Now, for the mandatory purists part: the STL was a library published by SGI and developed mainly by Alexander Stepanov. What I think you are referring to is "the part of the SGI STL which was later included into the standard with some minor modifications", i.e. all the generic containers/algorithms/iterators stuff. The usage of the term "STL" for this stuff is tolerated, what is plain wrong, instead, is calling "STL" the whole C++ standard library (which includes a lot of other stuff, e.g. iostreams, locale, the library inherited from C, ...). If I have used STL, how can I modify them to do what they do without STL? Why would you want to do that? Anyhow, you have several options, that span from rewriting such classes and algorithms from scratch to using simpler data structures (e.g. C strings) reimplementing only the algorithms you need. Anyway, they both imply reinventing the wheel (and probably reinventing a square wheel), so I'd advise you against doing this unless you have a compelling reason. EDIT: I guess this is OUR definition of STL: http://www.sgi.com/tech/stl/stl_index_cat.html Are you sure? Almost no one today uses the SGI STL, generally you use the (more or less) equivalent portion of your C++ standard library (that, by the way, is what you are doing in your code, since you are getting everything from the std namespace). I don't see const_iterator... const_iterator is a typedef member of basic_string<char>, you find it in its page. but I do see max. But is that the max I used? No, it's not it, your max is not a global function, but a member of the std::numeric_limits template class. Such class do not come from the STL. A: Does your code include the namespace std? Then yes, you have used the Standard library. How you can you modify your code to not use the Standard library? Why on earth would you want to? Implementations must provide it- that's why it's called Standard. But if you're truly insane and feel the need to not use it, then ... look up the documentation on what those functions and classes do and write your own replacement. A: You have used the STL std::string and std::numeric_limits. I don't know why you would want to avoid using STL (perhaps homework?). You could use old style C strings with a char* and the macro definition MAX_INT from C limits. A: What is this "STL" you speak of? There was this thing that SGI developed in the mid 90s. Yeah, that's 15+ years ago. Older than the previous C++ standard. Back in the days when compilers like Turbo C++ and Borland C++ were best-of-breed; when people used the phrase "C with classes" unironically and without derision; when the idea of compiling C++ primarily by first cross-compiling to C was finally being abandoned; when exceptions were (at least in this context!) a new idea. They called it "STL" for "standard template library", and they were doing a bunch of neat things with templates and developing new idioms. For its time, it was pretty revolutionary. So much so, in fact, that almost all of its stuff got officially accepted into the standard library with the 1999 standardization of the language. (Similarly, lots of Boost stuff - although nowhere near all; Boost is huge - has been added to the std namespace in the new standard.) And that's where it died. Unless you are specifically referring to a few oddball things like std::iota or lexicographical_compare_3way, it is not appropriate to speak of "the STL", and it hasn't been appropriate to speak of "the STL" for twelve years. That's an eternity in computer science terms. (But, hell, I still seem to keep hearing about new installations of Visual C++ 6.0, and some people using even older compilers...) You're using the standard library of the C++ language. I guess you could write "SC++L" if you like, but that's a bit awkward, isn't it? I mean, no sane Java programmer would ever refer to the SJL, nor any Pythonista to the SPL. Why would you need jargon to talk about using the standard library of the language you are using? This is what you're supposed to do by default, after all. Could you imagine writing code in C without malloc, strlen et. al.? Avoiding std::string in C++ would be just as silly. Sure, maybe you want to use C++ as a systems programming language. But really, the kinds of applications where you absolutely have to squeeze out every cycle (keep in mind that using std::string is often more efficient than naive string algorithms, and difficult to beat with hard work, because of the simple algorithmic benefits of caching the string length count and possibly over-allocating memory or keeping a cache for short strings) are generally not ones that involve string processing. (Take it from me - I have several years' experience as a professional mobile game developer, dating to when phones were much, much less powerful: the standard approach to string processing is to redesign everything to need as little of it as possible. And even when you do have to assemble - and line-wrap - text, it was usually not worth optimizing anyway because the time the code spends on that is dwarfed by the time it takes to actually blit the characters to screen.) A: "STL" can mean a number of things. Formally, the name "STL" was only ever used for the library developed by Stepanov, and which is now hosted by SGI. The library consisted, roughly speaking, of containers (vector, list, deque, map, set and all those), iterators and algorithms (and a few other bits and pieces, such as allocators) This library was adopted and adapted into the C++ standard library when the language was standardized in 1998. In this process, a number of changes were made: corners were cut, components were left out, in order to keep the library small, and to make it easy to swallow for the committee members. A number of changes in order for it to better interoperate with the rest of the standard library, or with the language itself, and certain parts of the existing standard library were modified to become a bit more STL-like. Today, it's really not very useful to discuss the original STL. So when most C++ developers say "STL", they mean "the part of the C++ standard library that was created when the STL was adopted into the standard". In other words, all the container classes, the iterators and the algorithms in the standard library, are commonly called "STL", simply because they look a lot like the "original" STL, and they're a lot more relevant today than the original library. But this also means that the term has become rather fluffy and vague. The std::string class was not a part of the original STL. But it was modifed to behave "STL-like". For example, it was given iterators, so that it can be used with the STL algorithms. Should it be considered a part of the STL? Maybe, maybe not. And to forther confuse matters, the STL became fashionable after it was adopted into the language. Suddenly, people started talking about "STL-style". The Boost libraries, for example, are generally written in a very STL-like way, and some Boost libs have been adopted into the standard library in C++11. So should they now be considered part of the STL? Probably not, but you could make a pretty good case that they should: that they follow the spirit of the STL, and if Stepanov had thought of them when he write the original STL library, maybe he'd have included them. Except for a few purists, who think that everyone is better off if the term "STL" is used exclusively to refer to something that no one ever actually needs to refer to (the SGI library), and if we have no way to refer to the standard library subset that it spawned, pretty much any C++ developer can agree that if you've used the standard library containers OR the standard library iterators OR the standard library algorithms, then you have used the STL. In your code I see an iterator. So yes, you've used at least a small corner of the STL. But why does it matter?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I send a cfm file as the body of an e-mail using ColdFusion? I have a legacy application where an email.cfm file is used with a cfmail tag to send e-mail: <cfmail from="abc@123.com" to="def@456.com" subject="New e-mail!"> // lots of HTML </cfmail> Now I'd like to update it for ColdFusion Model Glue 3. I want to send it using a mail object in the controller, and include in the body a CFM page: var mail = new mail(); mail.setFrom("abc@123.com"); mail.setTo("def@456.com"); mail.setSubject("New e-mail!"); mail.setBody( ** SOME CFM FILE ** ); mail.send(); Does anybody have any idea how I can do this? A: You can render the content you want to email in a cfsavecontent block and then use that in the email, like: <cfsavecontent variable="myemail"> ...add some HTML, include another file, whatever... </cfsavecontent> <cfscript> mail.setBody( myemail ); </cfscript> See http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7d57.html A: Call the CFC assigning it to a variable, like cfset request.emaiBody = cfc.function(). Then just put it in your setBody tag. A: OP was convinced to use CFML, but to answer the question as it was initially asked: var mail = new Mail(); mail.setFrom("abc@123.com"); mail.setTo("def@456.com"); mail.setSubject("New e-mail!"); mail.setType("html"); savecontent variable="mailBody" { include "email.cfm"; } mail.setBody(mailBody); mail.send(); A: I ended up following Henry's advice in the comments and created a CFML-based CFC: <cfcomponent> <cffunction name="SendMail"> <cfargument name="from"/> <cfargument name="to"/> <cfargument name="subject"/> <cfmail from="#from#" to="#to#" subject="#subject#"> <!--- HTML for e-mail body here ---> </cfmail> </cffunction> </cfcomponent> Dave Long's suggestion is also good, which is to create components using <cfcomponent>, then wrapping the code in <cfscript> tags. This gives you the ability to fall back to CFML in case the there is no cfscript equivalent or it's easier to do with CFML: <cfcomponent> <cfscript> void function GetData() { RunDbQuery(); } </cfscript> <cffunction name="RunDbQuery"> <cfquery name="data"> SELECT * FROM ABC; </cfquery> <cfreturn data> </cffunction> </cfcomponent>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select iframe using Python + Selenium So, I was absolutely baffled as to how to do this in Selenium, and couldn't find the answer anywhere, so I'm sharing my experience. I was trying to select an iframe and having no luck (or not repeatably anyway). The HTML is: <iframe id="upload_file_frame" width="100%" height="465px" frameborder="0" framemargin="0" name="upload_file_frame" src="/blah/import/"> <html> <body> <div class="import_devices"> <div class="import_type"> <a class="secondary_button" href="/blah/blah/?source=blah"> <div class="import_choice_image"> <img alt="blah" src="/public/images/blah/import/blah.png"> </div> <div class="import_choice_text">Blah Blah</div> </a> </div> </div> </body> </html> The Python code (using the selenium library) was trying to find this iframe using this: @timed(650) def test_pedometer(self): sel = self.selenium ... time.sleep(10) for i in range(5): try: if sel.select_frame("css=#upload_file_frame"): break except: pass time.sleep(10) else: self.fail("Cannot find upload_file_frame, the iframe for the device upload image buttons") Repeated fails with every combination of Selenium commands I could find. The occasional success would not be reproducible, so perhaps it was some sort of race condition or something? Never did find the right way to get it in selenium proper. A: This worked for me with Python (v. 2.7), webdriver & Selenium when testing with iframes and trying to insert data within an iframe: self.driver = webdriver.Firefox() ## Give time for iframe to load ## time.sleep(3) ## You have to switch to the iframe like so: ## driver.switch_to.frame(driver.find_element_by_tag_name("iframe")) ## Insert text via xpath ## elem = driver.find_element_by_xpath("/html/body/p") elem.send_keys("Lorem Ipsum") ## Switch back to the "default content" (that is, out of the iframes) ## driver.switch_to.default_content() A: You don't need to use JavascriptExecutor. All you needed to do was switch into the frame and then switch back out, like so: // do stuff on main window driver.switch_to.frame(frame_reference) // then do stuff in the frame driver.switch_to.default_content() // then do stuff on main window again As long as you are careful with this, you will never have a problem. The only time I always use a JavascriptExecutor is to get window focus since I think using Javascript is more reliable in that case. A: To shift Selenium's focus within the <iframe> you can use either of the following Locator Strategies: * *Using ID: driver.switch_to.frame("upload_file_frame") *Using CSS_SELECTOR: driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, "iframe#upload_file_frame")) *Using XPATH: driver.switch_to.frame(driver.find_element(By.XPATH, "//iframe[@id='upload_file_frame']")) Ideally, you have to induce WebDriverWait for the desired frame to be available and switch to it and you can use either of the following Locator Strategies: * *Using ID: WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"upload_file_frame"))) *Using CSS_SELECTOR: WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#upload_file_frame"))) *Using XPATH: WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='upload_file_frame']"))) *Note : You have to add the following imports : from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC Reference You can find a couple of relevant discussions in: * *Ways to deal with #document under iframe *Switch to an iframe through Selenium and python A: If iframe is dynamic node, it's also possible to wait for iframe appearence explicitly and then switch to it using ExpectedConditions: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait as wait driver = webdriver.Chrome() driver.get(URL) wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it("iframe_name_or_id")) If iframe doesn't have @id or @name it can be found as common WebElement using driver.find_element_by_xpath(), driver.find_element_by_tag_name(), etc..: wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath("//iframe[@class='iframe_class']"))) To switch back from iframe: driver.switch_to.default_content() A: Selenium's selectFrame command accepts all the standard locators like css=, but it also has a an extra set of locators that work specifically with FRAME and IFRAME elements. As the doc says: selectFrame ( locator ) Selects a frame within the current window. (You may invoke this command multiple times to select nested frames.) To select the parent frame, use "relative=parent" as a locator; to select the top frame, use "relative=top". You can also select a frame by its 0-based index number; select the first frame with "index=0", or the third frame with "index=2". You may also use a DOM expression to identify the frame you want directly, like this: dom=frames["main"].frames["subframe"] Arguments: locator - an element locator identifying a frame or iframe In general, you'll have better luck using the specialized locators, especially if you establish the right context first (e.g., select_frame("relative=top"); select_frame("id=upload_file_frame");). A: What finally worked for me was: sel.run_script("$('#upload_file_frame').contents().find('img[alt=\"Humana\"]').click();") Basically, don't use selenium to find the link in the iframe and click on it; use jQuery. Selenium has the capability to run an arbitrary piece of javascript apparently (this is python-selenium, I am guessing the original selenium command is runScript or something), and once I can use jQuery I can do something like this: Selecting a form which is in an iframe using jQuery A: you can use this simple code to look for the iframe using xpath sample use set_iframe("/html/body/div[2]/table/") def set_iframe(xpath): print('set_iframe') driver.switch_to.default_content() seq = driver.find_elements_by_tag_name('iframe') for x in range(0, len(seq)): driver.switch_to.default_content() print ("iframe-"+str(x)) try: driver.switch_to.frame(int(x)) driver.find_element_by_xpath(xpath) return str(x) except: continue
{ "language": "en", "url": "https://stackoverflow.com/questions/7534622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: imeOptions actionDone with Android 2.3 I have a few EditTexts where I've set the imeOptions to actionDone. When I run my application in the emulator using either Android 2.1 or Android 2.2, the enter key on the virtual keyboard becomes "done." However, (and I've not tested this in the emulator), when I run my application on my phone, which is running Android 2.3 (straight 2.3, Nexus S), the enter key on the virtual keyboard is still a return button and pressing it enters a newline into the EditText. How can I make the return key on the virtual keyboard say and behave as "done" in Android 2.3? A: I have implemented as below and it works great for me. Try out it might help you out. EditText m_etDone = (EditText) findViewById(R.id.am_etDone); EditText m_etSearch = (EditText) findViewById(R.id.am_etSearch); m_etDone.setOnEditorActionListener(new DoneOnEditorActionListener()); m_etSearch.setOnEditorActionListener(new DoneOnEditorActionListener()); class DoneOnEditorActionListener implements OnEditorActionListener { @Override public boolean onEditorAction(TextView p_v, int p_actionId, KeyEvent p_event) { if (p_actionId == EditorInfo.IME_ACTION_DONE) { InputMethodManager m_imm = (InputMethodManager)p_v.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); m_imm.hideSoftInputFromWindow(p_v.getWindowToken(), 0); return true; } else if(p_actionId == EditorInfo.IME_ACTION_SEARCH) { Toast.makeText(getApplicationContext(),"Search Text",Toast.LENGTH_SHORT).show(); return true; } return false; } } Layout file: <EditText android:id="@+id/am_etDone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Enter some text" android:imeOptions="actionNext" android:singleLine="true" android:imeActionLabel="Done"/> <EditText android:id="@+id/am_etSearch" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="Enter search text" android:imeOptions="actionSearch" android:singleLine="true" android:layout_below="@+id/am_etDone" android:imeActionLabel="Search"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ignore minimum size when resizing QWidget Is there a way to make a QWidget (and any subclass of it) completely ignore its minimum size? What I want is for a QPushButton to cut off when it is sized too small, rather than prevent the window from resizing (the default behavior). A: You can use: button.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) but you'll have to set the initial size yourself. Or you can just set the minimum size to a small non-zero value: button.setMinimumSize(1,1) To apply that to all buttons within a widget, you could try to use a style sheet, but the borders don't disappear when the button is at its minimum content size (at least with QGtkStyle on Linux): dialog.setStyleSheet("QPushButton { min-height: 0px; min-width: 0px }");
{ "language": "en", "url": "https://stackoverflow.com/questions/7534644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot run "HelloWorld" monodroid application on my device Helo.apk and Hello-signed.apk (by vs2010 monodroid)(default monodroid app from template I have lg android2.2 phone and i load by usb to my phone those files. When i run it i see "Unexpected error process Hello.apk") In emulator device application works fine Mycompilation config-debug all cpu * *Should i install mono to my device? *Should i use another build configuration(linking sd and user assemblies) *What is use shared libraries? p.s i am using trial version of monodroid A: The trial version of monodroid does not support pushing to phones, you will have to try your sample app on an emulator. Edit: Yes the emulator is pretty bad, I feel your pain - it's too the point where the trial version is almost useless. This is not monodroid's problem to solve though, even if it paints their product in a very bad picture. Developing and debugging on the phone with monodroid works actually much better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scipy's fmin sticks only on inf only sometimes I'm using Scipy's fmin search to compute the log of the likelihood of a distribution's fit to some data. I'm using fmin to search for the parameters that maximize the log likelihood, like so: j = fmin(lambda p:-sum(log(likelihood_calculator(data, p))), array([1.5]), full_output=True) (likelihood_calculator takes data and a parameter and spits out an array of likelihood values for each data point.) If we start that search with a parameter that yields a likelihood of 0, the loglikelihood is -inf, so the -sum is inf. fmin should run away from the initial parameter, but instead it sticks on that value for the maximum number of calls, then returns it: In [268]: print j (array([ 1.5]), inf, 67, 200, 1) I thought this was perhaps a problem with fmin's handling of infs, but if we remove the likelihood calculator and just hand a 0 directly, we get better behavior: In [269]: i = fmin(lambda p: -sum(log(p)), array([0]), full_output=1) Warning: Maximum number of function evaluations has been exceeded. In [270]: i Out[270]: (array([ 3.16912650e+26]), -61.020668415892501, 100, 200, 1) This same correct behavior happens if we use an array of zeros, if those zeros are floats, or if we use fmin_bfgs. The same incorrect behavior with the function call continues if we use fmin_bfgs, but fmin works CORRECTLY if we start with a parameter that doesn't yield a 0 likelihood (and thus any infs). Thoughts? Thanks! Update: If there's a broad area of parameters that result in zeros, we can push the parameter value up to the edge. If the parameter is near enough the edge, fmin will get out of zeroland and start searching. Ex. p<1 = Inf, then at p=.99 fmin will work, but not at p=.95 A: Maybe your update answers the question. Since fmin uses a downhill gradient algorithm, it searches in a neighborhood of the initial guess for the direction of steepest descent. If you are deep enough into a parameter-region where the function always returns inf then the algorithm can not see which direction to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server Login role for remote database manipulation My scenarion is MVC Blog (funnelweb) installed on a server named WEB. The SQL Server 2005 runs on DB. FunnelWeb site requires access to its own database. I have create a new database using SQL Server Management Studio and had named it FunnelWeb. I want to use SQL authentication, so I went ahead and created a SQL login FunnelWebAdmin. In the login mappings I have mapped FunnelWebAdmin to FunnelWeb database, and have granted him a dbowner permission on a db. I have not granted a login any server roles. SQL Authentication is enabled for the server. My question is: Do I need to grant this login any server roles, so that the web site can connect to a database using SQL authentication? If yes, which are the minimum one's in order for site to be able to manipulate database. A: Unless I'm missing something setting that user in the role DBAdmin will give it the right to login. It will give it full rights and control over the database. Be sure you lock down that web application. Giving admin rights to a DB from a web app is dangerous at best. It leaves you open to SQL injection, which can open the door to all sorts of issues. A good attacker (or a mediocre one with access to google) can exploit an SQL Injection attack and gain full control over the operating system if the server isn't locked down properly. http://sqlmap.sourceforge.net/doc/BlackHat-Europe-09-Damele-A-G-Advanced-SQL-injection-whitepaper.pdf Even if they can't get control over the OS, you still need to worry about data theft, insertion of XSS or XSRF scripts, or any number of attacks. I'm not saying not to do it, just to be careful and be sure you know what you're doing. Getting access to a database via a web app is childs play if there are any vulnerabilities. There are toolkits that you can buy that do it for you, so attackers don't even need to know what they're doing. I really have no idea what your experience level is, so forgive me if I'm telling you something you already know. Your question indicates that you're more on the "beginner" end of the spectrum, but I may be wrong. Assuming I'm right, however, I would really caution you to spend a lot of time on these sites,learning everything you can. They don't teach this stuff adequately in school, or in the "Learning programming" resources (books, web, videos, etc). OWASP Top 10 Writing Secure Code (Microsoft) Even if the website itself is not Internet accessible (say it's running on a corporate Intranet and only logged in users have access) you still need to be cautious. Statistics show that disgruntled co-workers with access are just as much of a threat as outside attackers. Just something to bear in mind.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to increase div's height with Zoom level/Screen resolution? Could anyone of you help me resolve this issue. I have to implement the following layout: Root div -Header -Content Footer div There should not be any gap between the Root Div and the Footer. And the Footer should always stick to the bottom of the web page. So basically, if I zoom out or increase the resolution, the Content Div should increase in height. Can any of you please tell me how to achieve this? The divs look like this: <header> <container> <content> ---> Has a gradient background <text> <image> ---> The bottom end of this image should be behind the footer, and when the screen resolution changes, the complete image should display with the Gradient background extended until the footer. <footer> A: It is pretty much always an illusion - being that when you expand your page you're not getting more content. http://www.cssstickyfooter.com/ Putting a background image / color on your wrapper div would give you the likely result you're looking for. A: Like so?: <div id="root" style="height:100%;"> Le root </div> <div id="footer" style="position:absolute;bottom:0px;">Le Footer</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP MYSQL displaying picture link from dB Hey all I have a table caleld Box1, with a simple structure of: id(increment,primary) imageurl, link. What I am looking to do, is on my site in the HTML file, display the imageurl into a imgsrc, so that the Image URL loads the image when going to the site I cannot find specifically what I am looking for online and know I must be close somewhere, this is what I have so far in my coding for my .php file.... thanks. <?php $con = mysql_connect("localhost","data","data"); if (!$con) { die('Could not connect: ' . mysql_error()); }else { mysql_select_db("database1", $con); $result = mysql_query("SELECT * FROM Box1 ORDER BY id DESC LIMIT 1"); while($row = mysql_fetch_array($result)) { echo $row['image']; // NEXT STEP IS TO DISPLAY THE the IMAGE EXAMPLE: '<img src code<?php echo 'image'; ?>' > } } mysql_close($con) ?> if you could guide me to an exmaple of how to do this, that would be amazing, im so confused how one would implement HTML with PHP, thanks!! A: <?php ... connect to DB ... $sql = "SELECT imgurl FROM Box1 WHERE id=XXX"; $result = mysql_query($sql) or die(mysql_error()); $row = mysql_fetch_assoc($result); ?> <img src="<?php echo $row['imgurl'] ?>" /> A: Also, it is helpful to become familiar with this operator for large chunks of html echo <<<YOUR_TOKEN_NAME <img src="$row['imgurl']" /> ...misc html and php vars intermixed YOUR_TOKEN_NAME;
{ "language": "en", "url": "https://stackoverflow.com/questions/7534660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server Script Error: Database is Already in Use I have a SQL Server deployment script running from visual studio that gives me the error: Error SQL01268: .Net SqlClient Data Provider: Msg 1828, Level 16, State 5, Line 1 The logical file name "myDB" is already in use. Choose a different name. However, when I go into SSMS and try and drop this database, I get the error: Cannot drop the database 'myDB', because it does not exist or you do not have permission. Can anyone help me understand where this phantom filename is already stored so that I can delete it? Thanks. A: The second error message states that the database cannot be dropped because other sessions are currently connected to it. In order to kick all the users out, you can add this to your deployment script or run it manually before deploying. The USE command is to make sure there isn't a race condition when you are the one who's connected. USE [master]; GO ALTER DATABASE myDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO DROP DATABASE myDB; GO A: This error can also occur when trying to generate a database from a script. I was trying to do downgrade a SQL Server 2012 database to 2008 as per this article https://superuser.com/questions/468578/move-database-from-sql-server-2012-to-2008. However, when I ran the script initially, I got this error The logical file name "emmagarland" is already in use. Choose a different name. Turns out (after reading this article https://ask.sqlservercentral.com/questions/106577/the-logical-file-name-database-is-already-in-use.html) in my restore script, I hadn't checked and changed the logical file names. I had to ensure the path is correct, and the change the generated name for the log file, else it tries to overwrite the .mdf file with the log and then throws this error. I fixed it by changing the name from xxxxx to xxxxxldf CREATE DATABASE [xxxxx] ON PRIMARY ( NAME = xxxxx', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\xxxxx.mdf' , SIZE = 14400KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) LOG ON ( NAME = N'xxxxxldf', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\xxxxx_log.ldf' , SIZE = 18560KB , MAXSIZE = 2048GB , FILEGROWTH = 10%) GO Sounds simple but I couldn't work out why this error was occuring when I was creating a brand new database!
{ "language": "en", "url": "https://stackoverflow.com/questions/7534664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The best regex to parse Twitter #hashtags and @users Here is what I quickly came up with. It works with regexKitLite on the iPhone: #define kUserRegex @"((?:@){1}[0-9a-zA-Z_]{1,15})"; Twitter only allows letters/numbers, underscores _, and a max of 15 chars (without @). My regex seems fine but reports false positives on e-mail addresses. #define kHashtagRegex @"((?:#){1}[0-9a-zA-Z_àáâãäåçèéêëìíîïðòóôõöùúûüýÿ]{1,140})"; kHashtagRegex works with accentuated words but it is not enough for UTF-8 words. What is the 'tech spec' of a hashtag? Is there a reference somewhere on what to use for parsing these? Or do you have advice on how to enhance this regex? A: I'm not sure if this is complete, bu this is what I would do: For the username, Add a check for whitespace/start of string before the @ to eliminate emails (?:^|\s): #define kUserRegex @"((?:^|\s)(?:@){1}[0-9a-zA-Z_]{1,15})"; for the hash tags, I would just say \w or \d #define kHashtagRegex @"((?:#){1}[\w\d]{1,140})"; A: REGEX_HASHTAG = '/(^|[^0-9A-Z&\/\?]+)([##]+)([0-9A-Z_]*[A-Z_]+[a-z0-9_üÀ-ÖØ-öø-ÿ]*)/iu';`
{ "language": "en", "url": "https://stackoverflow.com/questions/7534665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating bash aliases via .bashrc As a sysadmin I routinely rdp and ssh into remote machines for administration. I've created a file, ${SERVER_FILE}, containing one entry per line noting the hostname and protocol to use when connecting to a given server. Example: ... server1,ssh winsrv,rdp ... Given the above entries I want the following to be created+evaluated (rdp is itself a script on my system): alias server1='ssh server1' winsrv='rdp winsrv' The following code, when I cut and paste the resultant output to an alias command, works flawlessly: $ echo $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n') server1='ssh server1' winsrv='rdp winsrv' $ alias server1='ssh server1' winsrv='rdp winsrv' $ alias alias server1='ssh server1' alias winsrv='rdp winsrv' SO I change it to this to actually cause the aliases to be created and I get errors: $ alias $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n') bash: alias: server1': not found bash: alias: winsrv': not found $ alias alias server1=''\''ssh' alias winsrv=''\''rdp' Advice? A: Try: $ eval alias $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n') Works for me. A: Might I suggest awk instead of sed for a much more easily readable command? awk 'BEGIN { FS="," format = "%s=\"%s %s\" " } $2 ~ /(rdp|ssh)/ { printf format, $1, $2, $1 }' ${SERVER_FILE} A: Well, it looks like alias and echo are interpreting some backslashes differently. This is admittedly a hack, but I would try this: alias $(echo $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n')) :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Exporting GridView to Excel results in blank columns being inserted into the middle of the GridView i am trying to export the elements in gridview to excel spreadsheet. that grid hides several columns depending on the condition, here is some of the code in the def of the button, this is the part where i have prob with exporting worksheet = workbook.Worksheets["Sheet1"]; //string wname = tab.Text.Replace(" ", "_"); //worksheet.Name = wname; range = worksheet.Cells["A1"]; for (int i = 0; i < fr_chart_grid.Columns.Count; i++)//count = 7 { if (fr_chart_grid.Columns[i].Visible == true) dtData.Columns.Add(fr_chart_grid.HeaderRow.Cells[i].Text); } // add each of the data rows to the table foreach (GridViewRow row in fr_chart_grid.Rows) { DataRow drData; drData = dtData.NewRow(); for (int i = 0; i < row.Cells.Count; i++) { if (fr_chart_grid.Columns[i].Visible == true) drData[i] = row.Cells[i].Text; } dtData.Rows.Add(drData); } range.CopyFromDataTable(dtData, SpreadsheetGear.Data.SetDataFlags.None); and here is how my grid is defined <asp:GridView ID="fr_chart_grid" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Dateval" HeaderText="Date" DataFormatString="{0:d}" HtmlEncode="false" /> <asp:BoundField DataField="Col1" HeaderText="Data" DataFormatString="{0:f3}" /> <asp:BoundField DataField="Col2" HeaderText="" DataFormatString="{0:f3}"/> <asp:BoundField DataField="Col3" HeaderText="" DataFormatString="{0:f3}"/> <asp:BoundField DataField="Col4" HeaderText="" DataFormatString="{0:f3}"/> <asp:BoundField DataField="Col5" HeaderText="" DataFormatString="{0:f3}"/> <asp:BoundField DataField="Col6" HeaderText="" DataFormatString="{0:f3}"/> </Columns> </asp:GridView> my problem is that i have blank columns when i export the datafield, and sometimes wuts suppose to be in col 3 goes into col 4, with col 3 being blank. othertimes i have 5 rows and it tells me it cannot find the 5th row...it is frustrating....is there a way i could get rid of the blank columns? it's random and it doesn't show when i run the website, but it causes prob when i export to excel A: It looks like you have at least one issue... where you set the data for a cell in your new row, you are indexing i in both row.Cells and drData -- They are out of sync when some columns are not visible. This line is trouble: drData[i] = row.Cells[i].Text; drData may have fewer items than i due to non-visible columns. You'll be overwritting data that is intended for other columns, or getting exceptions. You need to make sure you index drData with the index of the visible columns. Something like this should work: int j = 0; for (int i = 0; i < row.Cells.Count; i++) { if (fr_chart_grid.Columns[i].Visible == true) { drData[j] = row.Cells[i].Text; j++; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Variable and if input What is wrong with this code? I declare a variable, then i say if it is 0 hide, if it is 1 animate. Then, when you click on it, the variable become 1 and so it animate. The code hides #slickbox11, but, when i click on it, it doesn't "animate" itself and the scroll. var slickbox11 = 0 //slickbox11// $(document).ready(function() { if (slickbox11 == 0){ $('#slickbox11').hide(); } }) $(document).ready(function() { if (slickbox11 == 1){ $('html,body').animate({scrollTop: 135}, 300); $('#slickbox11').animate({ opacity: '1', height: '1' }, 300 ); } }) $(document).ready(function() { $('#slick-toggle11').click(function() { slickbox11 = 1; }) }) A: Animate is not rerunning every time you click. it's not part of your click handler. You could check the state of the variable in the click handler and toggle the state of slickbox11 appropriately. A: $(document).ready only gets executed once when all the DOMs are loaded so you'll have to bind the animation to the click event itself. You should probably use toggleClass like: $('#slick-toggle11').click(function() { $(this).toggleClass('animate'); if ($(this).hasClass('animate')) //animate else //animate some other way }) A: First off, you only should have 1 $(document).ready.... To make it work: $(document).ready(function() { $('#slick-toggle11').click(function() { $('html,body').animate({scrollTop: 135}, 300); $('#slickbox11').animate({ opacity: '1', height: '1' }, 300 ); }); }); Javascript is event driven, all those $(document).ready... only get fired once. So setting the variable to 1 is doing just that, setting a variable. You need to have the action you want to happen (animate, scroll), tied to an event (click). A: because the if statements are evaluated in the ready method and then forgotten. the $(document).ready function is not run every time a variable changes but when the document is ready. Therefore, when you click the element, $(document).ready has already run a long time ago and if you want to call another method you have to do it in the click event. var slickbox11 = 0 $(document).ready(function() { run(); $('#slick-toggle11').click(function() { slickbox11 = 1; run(); }) }) function run() { if (slickbox11 == 1){ $('html,body').animate({scrollTop: 135}, 300); $('#slickbox11').animate({ opacity: '1', height: '1' }, 300 ); } else if (slickbox11 == 0){ $('#slickbox11').hide(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Trouble inserting variable as my URL in PHP fopen() I'm trying to make my xml file URL dynamic so multiple people can be using my site and querying data at once. I order to do so I'm inserting a random number php variable in front of my xmlfile. For some reason I'm having issues creating and writing xml files when trying to use this variable. When I use a static URL like 'wine.xml' it works fine. $fp = fopen($randnumb.'wine.xml', 'w'); fwrite($fp, $string); fclose($fp); A: I might be wrong (so any one let's correct me) if you have an xml and want to allow many people to read it why do you have to make multiple copies of it?! Isn't the server supposed to do this job serving a file to many peple? If I am wrong and there is something else you try to then this php only works okay. This way you don't have to look for errors in php. <?php $fileName = rand().'file.xml'; $fp = fopen($fileName, 'w'); fwrite($fp, 'Hello!'); fclose($fp); ?> <?php $handle = fopen($fileName, "rb"); $contents = fread($handle, filesize($fileName)); print_r($contents); fclose($handle); ?> var winexml=loadXMLDoc("<?=$randnumb?>wine.xml"); Does <? work for you? cause wamp asks <?PHP (must be the php.ini) Why do you have a second = in the loadxmldoc parameters?! Does this work: <?PHP $dbq="\""; echo 'var winexml=loadXMLDoc(',$dbq,$randnumb,'wine.xml',$dbq,');'; ?> A: Okay I see. I don't know what is you preference of final xml file display, however this scripts has stuff that might let you have your job done, just adjust it to your needs. index.html and getXml.php <html> <head> <script type="text/javascript"> var request = false; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } } } if (!request) alert("Error initializing XMLHttpRequest!"); </script> <script type="text/javascript"> var fileOption; var fileName; function runPhp(makeFile) { var url = "getXml.php"; fileOption = makeFile; var params = "makeFile=" +makeFile+""; request.open("POST", url, true); //Some http headers must be set along with any POST request. request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); request.setRequestHeader("Content-length", params.length); request.setRequestHeader("Connection", "close"); request.onreadystatechange = updatePage; request.send(params); }//////////////////// function getXml( ) { if(fileName==null){alert('please click create file first');return;} var url = fileName; var params = null; request.open("POST", url, true); request.setRequestHeader("Connection", "close"); request.onreadystatechange = displayFile; request.send(params); }//////////////////// //You're looking for a status code of 200 which simply means okay. function updatePage() { if (request.readyState == 4) { if (request.status == 200) { if(fileOption==1) {fileName=request.responseText; return;} document.getElementById('divResults').innerHTML=request.responseText; document.getElementById('textareaResults').innerHTML=request.responseText; } else{ //alert("status is " + request.status); } } } function displayFile() { if (request.readyState == 4) { if (request.status == 200) { document.getElementById('textareaResults').innerHTML=request.responseText; document.getElementById('divResults').innerHTML='File loaded in text area above.'; } else{ //alert("status is " + request.status); } } } </script> </head> <body > <span style="background-color:blue;color:yellow;" onClick="runPhp(0)"/> Click for Xml Results.<br> (<font color=pink>I prefer this one!!!</font>) </span><br><br> <span style="background-color:blue;color:yellow;" onClick="runPhp(1)"/> Click to create an xml file.<br> </span> <span style="background-color:blue;color:yellow;" onClick="getXml(1)"/> Click to read the xml file.<br> </span> <textarea rows="10" cols="88" id="textareaResults"> </textarea> <br><br> <pre><div id="divResults"></div></pre> <br><br> </body> </html> <?PHP mysql_connect('localhost', 'root',''); mysql_select_db("mysql"); $query="select * from help_category;"; $resultID = mysql_query($query ) or die("Data not found."); $xml_output = "<?xml version=\"1.0\"?>\n"; $xml_output .= "<records>\n"; for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){ $row = mysql_fetch_assoc($resultID); $xml_output .= "\t<record>\n"; $xml_output .= "\t\t<help_category_id>" . $row['help_category_id'] . "</help_category_id>\n"; $xml_output .= "\t\t<name>" . $row['name'] . "</name>\n"; $xml_output .= "\t\t<parent_category_id>" . $row['parent_category_id'] . "</parent_category_id>\n"; $xml_output .= "\t</record>\n"; } $xml_output .= "</records>"; if($_POST['makeFile']==0) echo $xml_output; else { $fileName = rand().'file.xml'; $fp = fopen($fileName, 'w'); fwrite($fp, $xml_output); fclose($fp); $dbq="\""; echo $fileName; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to import data from excel sheet in iOS programmatically I am working for a iOS project whose data source is an excel sheet. How can I convert the excel sheet to csv or plist? A: I just had a similar issue recently. I saved my excel files to csv format, and then I downloaded the code described in this link: http://blog.danilocampos.com/2009/12/04/convert-a-csv-into-a-plist-file/ which is for a mac app that converts csv files to plist files. I had to edit the - (IBAction)executeConversion:(id)sender method in AppController.m to get the plist in the format I wanted, but it was straightforward. It may not be the best solution, but it was the best I could find.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bar Graph Effect: Aligning Multiple DIVs to Bottom when Side by Side Here is an image of my problem: http://www.rhexi.com/images/uploads/example.jpg I am trying to align multiple side-by-side divs to the bottom within a parent div. The end result I am trying to achieve is a bar graph, where you have a parent container, and multiple bar divs a the bottom within the parent. I have successfully embedded the child bar divs within the container div, but they are all aligned top. How do i get it to align bottom? I do not want to use position: absolute and bottom: 0 since these bars need to be floating. Here is my code: <div style="width: 100px; height: 50px; padding-bottom: 1px; border: 1px solid #000;"> <div style="width: 20px; height: 20px; background: #000; margin-left: 1px; float: left;"></div> <div style="width: 20px; height: 10px; background: #00f; margin-left: 1px; float: left;"></div> <div style="width: 20px; height: 5px; background: #f00; margin-left: 1px; float: left;"></div> </div> Thanks for the help! A: If you want to continue using this technique, but need skybondsor's answer to be aligned with the bottom of the "screen" without using absolute positioning on each bar, just make use of your margin style. Your margin-top should be equal to: margin-top = height_of_graph - height_of_bar So, in the example set by skybondsor, this worked for me: <div style="width: 100px; height: 50px; padding-bottom: 1px; border: 1px solid #000;position:relative;"> <div style="width: 199px; height: 50px; position: absolute; bottom: 0;"> <div style="width: 20px; height: 20px; background: #000; margin-left: 1px; float: left; margin-top: 30px;"></div> <div style="width: 20px; height: 10px; background: #00f; margin-left: 1px; float: left; margin-top: 40px;"></div> <div style="width: 20px; margin-top: 45px; height: 5px; background: #f00; margin-left: 1px; float: left;"></div> </div> </div> Hope this helps. A: How about creating 3 divs instead of 1? Something like this: <div style="width: 20px; height: 100%; margin-left: 1px; float: left;"> <div style="height: 80px;"></div> <div style="height: 100%; background: #000;"></div> </div> .. A: I'm not sure if this is what rfausak is also getting at, but position: absolute, bottom: 0 is the only way to do this. Fortunately, nesting one level deeper will allow you to achieve the effect without losing your floats. <div style="width: 100px; height: 50px; padding-bottom: 1px; border: 1px solid #000;position:relative;"> <div style="width: 199px; height: 50px; position: absolute; bottom: 0;"> <div style="width: 20px; height: 20px; background: #000; margin-left: 1px; float: left;"></div> <div style="width: 20px; height: 10px; background: #00f; margin-left: 1px; float: left;"></div> <div style="width: 20px; height: 5px; background: #f00; margin-left: 1px; float: left;"></div> </div> </div> A: Maybe make each bar a div nested inside another div and then make the background of the container div the color you want your bar to be, with the nested div the color of the background of the chart. Then, rather than giving the nested div the height you desire, you can give it the inverse. E.g. something like: <div style="width: 100px; height: 50px; padding-bottom: 1px; border: 1px solid #fff;"> <div style="width: 20px; height: 50px; background: #000; margin-left: 1px; float: left;"> <div style="width: 20px; height: 30px; background: #fff;"></div> </div> <div style="width: 20px; height: 50px; background: #000; margin-left: 1px; float: left;"> <div style="width: 20px; height: 20px; background: #fff;"></div> </div> <div style="width: 20px; height: 50px; background: #000; margin-left: 1px; float: left;"> <div style="width: 20px; height: 10px; background: #fff;"></div> </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Method in SSRS Custom Assembly Fails After Pushing to Server Background - I have developed a custom assembly for my SSRS server that I use to dynamically generate default values for particular report parameters. Some of these functions require a call to my database, mostly funneled through a generic function named ExecuteScalar(). I am using cascading parameters to pass particular criteria to these methods. Issue - Calling these methods returns the correct result when ran on my local machine. However, it stops working once I deploy it to my server. The DLL is in the right place and IS being found. I know this because I can set my method to pass back a hard-coded value just fine. The issue comes when I try to open my connection. Once this happens SSRS spits out the oh-so-specific error Error during processing of ‘Start’ report parameter. (rsReportParameterProcessingError) (Start is the name of the parameter for which I am querying the default value). I have tried implementing the suggestions at this site to no avail http://stevenharman.net/blog/archive/2007/01/22/Reporting_Services__Your_Custom_Assembly__Error._WTF.aspx. (Setting the Permission State did not fix it and setting the assembly to AllowPartiallyTrustedCallers wouldn't even compile) I am using SSRS 2005 and a C# assembly. Any help you can provide would be awesome & appreciated! public T ExecuteScalar<T>(String query) { SqlCommand cmd = null; try { this.GenerateConnectionString("Test"); //Creates global var conn string cmd = GetSqlCommand(query); //Creates cmd object using global conn string //If I return a hard-coded date here, I have no problems. cmd.Connection.Open(); //If I return a hard-coded date here, I get the error msg stated above. return (T)Convert.ChangeType(cmd.ExecuteScalar(), typeof(T)); } catch (Exception ex) { throw new ApplicationException("Error in " + (new System.Diagnostics.StackFrame()).GetMethod().Name + "()", ex); } finally { if (cmd != null) { cmd.Connection.Close(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails console is not outputting SQL Statements to my Development Log When I access my Webrick server via the localhost, or when I run rails migrations, my development.log is correctly written to. However, when I bootup my rails console with "rails c" and then try and create a new database object and save it via a command like "user.save", I see SQL statements in the console, but nothing is written to in the development log. Most people when answering a question similar to this say "check to make sure that the config is set to the correct environment". I've done this, and can say on my system this happens for a completely new rails app. Any help would be appreciated. Thanks! A: the rails console never writes to the log file, but you can achieve it quite easily, for example, if you execute following after starting the rails console ActiveRecord::Base.logger = Logger.new STDOUT rails will log all SQL statements to stdout, thus display them in your terminal. and since Logger.new accepts any stream as first argument, you could just let it write to the rails development.log: ActiveRecord::Base.logger = Logger.new File.open('log/development.log', 'a') A: I am in Rails 2.3.8, the above answer doesn't really work for me. ActiveRecord::Base.logger = Logger.new STDOUT The following actually works: ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT) Reference http://www.shanison.com/2012/03/05/show-sql-statements-in-rails-console/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Check if siblings in an unordered list of inputs are checked using jquery I have an unordered list of checkbox inputs: <ul> <li><input type="checkbox">parent <ul> <li><input type="checkbox">child <ul> <li><input type="checkbox">grandchild <ul> <li><input type="checkbox" checked="checked">great grandchild</li> <li><input type="checkbox">great grandchild</li> <li><input type="checkbox">great grandchild</li> <li><input type="checkbox" checked="checked">great grandchild</li> </ul> </li> </ul> </li> </ul> </li> </ul> If I uncheck one of the checkboxes, how can I check if any siblings are also checked only from that <ul>? I've tried a number of things such as siblings(), find() and index(). A: $(this).parent().siblings().children(":checkbox:checked").length This should get you the number of "sibling" checkboxes which are checked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to print comma-separated list with hamlet? With the hamlet templating language that comes with yesod, what is the best way of printing a comma-separated list? E.g. assume this code which just prints one entry after another, how do I insert commas in between the elements? Or maybe even add an “and” before the last entry: The values in the list are $ forall entry <- list #{entry} and that is it. Some templating languages such as Template Toolkit provide directives to detect the first or last iteration. A: I don't think there's anything built-in like that. Fortunately, it's easy to use helper functions in Hamlet. For example, if your items are plain strings, you can just use Data.List.intercalate to add commas between them. The values in the list are #{intercalate ", " list} and that is it. If you want to do fancier things, you can write functions to work with Hamlet values. For example, here's a function which adds commas and "and" between the Hamlet values in a list. commaify [x] = x commaify [x, y] = [hamlet|^{x} and ^{y}|] commaify (x:xs) = [hamlet|^{x}, ^{commaify xs}|] This uses ^{...} syntax to insert one Hamlet value into another. Now, we can use this to write a comma-separated list of underlined words. The values in the list are ^{commaify (map underline list)} and that is it. Here, underline is just a small helper function to produce something more interesting than plain text. underline word = [hamlet|<u>#{word}|] When rendered, this gives the following result. The values in the list are <u>foo</u>, <u>bar</u> and <u>baz</u> and that is it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Google shopping API country code not working except for US Hi I'm trying to call this url https://www.googleapis.com/shopping/search/v1/public/products?key="my key"&country=US&q=9780198062257&alt=json on the browser. It works fine and gave the appropriate data but when I change the country form US to IN (India) or any other country code, it gives zero results even though it works fine through Google shopping search. Can any one tell how to search for every country? I know ISO 3166 code are the country code but they are not working. Please help on how to call this url country wise. A: That's because Google Product Search API does not work for India. Here is a list of countries for which this API will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect google bots, but show a 'Moved' page to visitors? When moving a site to a new domain name, how can I show a 'This page has moved.' message to visitors and not automatically redirect, but at the same time tell Google and other bots that the sites have moved, to maintain SEO? Or what is the best alternative? User agent cloaking isn't what I'm looking for. What about the canonical meta tag? Seems like each page would need it's own, and the content on those pages would need to be nearly the same, but I guess you could have a box pop up saying "we have moved" to the user or something. Is this a viable alternative, or are there any complications? Thanks. A: you can provide different content, depend ending on the user agent specified in the http request header. you can find an overview of googlebot user agents here: http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=1061943. what language / framework are you using?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'objType' is not defined... Actually, it is, so why is this happening? As you seen in this picture below, for some reason my DirectCast wont except ANYTHING for the second argument. It says it requires a type, but, it won't take any object at all! Thanks for any help! I'm using VB.net so all .net answers are acceptable :) EDIT Ok, so apparently I'm not giving it the right kind of type. Could somebody please clarify this? Assuming the type it needs to cast to is gridElement, what should I replace objType with? A: DirectCast requires an object prototype (i.e. just giving it the intended class name) rather than a System.Type descriptor object. To cast an object using a System.Type, you will want to utilize CTypeDynamic(): Return CTypeDynamic(createElementByIdAndLayer.MemberwiseClone(), objType) The error is essentially telling you a class with the type name "objType" does not exist. A: Its expecting a "Type", not a "Type Object". What is the return value of the function?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use a Go package built from a different version? I'm using Go for Google App Engine, which uses an older version of Go. I want to use a third party package that requires a newer version of Go (goauth). It is possible to use that package in my Google App Engine program? Goauth uses strings.SplitN, which does not seem to be present in the GAE version of Go. A: Not without hacking the source of oauth to make it compatible, I'm afraid. Either that, or you can try and contact the author to see if they are willing to publish a version compatible with AppEngine's Go version. A third option would be to find an older revision of oauth which is compatible with your Go version and just use that one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make calls to a server in WPF I'm a noob in WPF so please bear with me. I wanted to do a client - server application. The client has a UI and the server is a console application. Is there any way that the client can communicate with the server? I know there were "sockets" in Windows Forms, which could send/receive data. Are they available in WPF also? And if yes, could anyone provide me with a simple example on how to use them? Thank you. A: As stated in the comments Microsoft has a whole technology dedicated just to that. Link to beginners guide to Windows Communication Foundation: http://msdn.microsoft.com/en-us/netframework/dd939784 A: we use WCF for client-server communication and wpf for the client. works like a charme.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: From Flash to Asp.net I have a flash file, but I haven't got the source codes. How can I get values from it? For example if it was a html form, I can get the posted values like below: Request.Form("myValue") But it doesn't work. How can I get the posted values? Thanks. A: In HTML, this code: Request.Form("myValue") Is not accessing the HTML source code; it's accessing the data sent in an HTTP form post. In HTML, the input names happen to dictate which form variables are sent. ActionScript (the Flash programming language) can do a post just like HTML. Here's some sample code: var loader:URLLoader = new URLLoader(); var request:URLRequest = new URLRequest("yourpage.aspx"); request.method = URLRequestMethod.POST; var variables:URLVariables = new URLVariables(); variables.myValue = "foo"; loader.addEventListener(Event.COMPLETE, handleCompletion); loader.load(request); private function handleCompletion(e : Event):void { // Do things after the post completes } If you post to an ASP.NET page or handler using this code, Request.Form("myValue") would work the same way as if an HTML form had been posted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to scroll down to particular child of a div using jquery How to scroll down to a nth child of a div. Consider this code <span id="click_me">Click me to scroll down to nth child</span> Messages div has 6 childs. I want to scroll down to 3rd or 4th child which somebody click on "click_me" Note: Childs are added dynamically. Using some ajax functions calls/juggernaut push notifications. <div class="messages" id="messages_212"> <div class="message_container"> <p><b>Sahil grover: </b>5</p> <div> <div class="message_container"> <p><b>Sahil grover: </b>4</p> <div> <div class="message_container"> <p><b>Sahil grover: </b>3</p> <div> <div class="message_container"> <p><b>Sahil grover: </b>2</p> <div> <div class="message_container"> <p><b>Sahil grover: </b>1</p> <div> <div class="message_container"> <p><b>Sahil grover: </b>0</p> <div> </div> A: I don't use jQuery (or any framework), but it's easy to do in plain JavaScript: d = document.getElementById('messages_212'); d.scrollTop = d.children[2].offsetTop; // children[2] for the third div, [3] for the fourth, etc. A: use http://plugins.jquery.com/project/ScrollTo plugin homepage and docs at: http://flesler.blogspot.com/2007/10/jqueryscrollto.html //scroll to nth child var child = 3; $.scrollTo($(".message_container")[child]); or //scroll to nth child var child = 3; $.scrollTo("#messages_212:nth-child("+child+")"); A: There is jQuery plugin for that: http://demos.flesler.com/jquery/scrollTo/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: drawing a line from gesture between 2 buttons I am beginner for interactions on iphone. I have 3 buttons, one on the left, and the 2 other ones on the right. I would like to push the left button with finger and display a line real time stretching with my finger moving on screen that goes to the other button I am going to go to on the right - and then I reach the button on the right and release my finger the line stays on screen. Where should I start in the manual to understand how to do something like this? - please don't say page 1 ;-) thanks for all the pointers so I can learn and write the code myself Cheers, geebee A: Wow, uh, you're jumping right into the deep end. First, the answer to your question is ... check out the Sample Code at developer.apple.com. By playing with those sample projects, and running them in the debugger, and reading that code, you can learn a whole lot about what you're trying to do. Using those samples as your tutorial, refer to specific information in the reference docs also available at developer.apple.com. There are specific docs on the classes you'll be using (e.g. UIButton Class Reference), and there are high level guides that talk about different areas, like the Event Handling Guide for iOS, and Drawing and Printing Guide for iOS. Here are some of the issues you're going to face, and some of the areas that you should read up on: * *UIButtons are going to respond to your touch and won't allow any other view to receive that touch without some special handling in your code. *Check out samples that deal with UITouch events, Quartz 2D drawing, creating custom controls *Try doing this without any buttons first, that's fairly simple. Just figure out how to detect a TouchDownInside event, track the finger movement across the screen, and detect a TouchUpInside event, all in a normal UIView. (There may be a sample for this.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: environment.rb contents when migrating from Rails 2 to Rails 3 I'm updating an application from rails 2.3 to rails 3.1, and I'm new to rails. I followed the RailsCast and got some idea. Somebody please help me for where to place my old environment variables. These are the four pieces of code in my old environment.rb 1: ENV['RAILS_ENV'] ||= 'development' 2: if RUBY_PLATFORM =~ /java/ require 'rubygems' RAILS_CONNECTION_ADAPTERS = %w(jdbc) end 3: CalendarDateSelect.format = :hyphen_ampm 4: Mime::Type.register "text/csv", :csv Where do I place this, the new environment.rb or application.rb? A: 3 and 4 in an initializer (config/initializers), i don't think you need 1, and i am not sure about 2, but i think you just need to add gem 'activerecord-jdbc-adapter' to your Gemfile. ( i haven't used jruby with rails yet, so i honestly don't know, it's just a guess, because i saw it somewhere ) A: Don't upgrade. People may not like that answer, but it's not worth the effort to go from 2.3 to 3. Starting from scratch? Maybe use 3, up to you. A: This tutorial helped me do what you are trying to do: http://gregmoreno.ca/rails-3-upgrade-part-1-booting-the-application/ A: I figure out the answer, all the configurations must go to the application.rb
{ "language": "en", "url": "https://stackoverflow.com/questions/7534746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ideal database schema for similar structures In our business application, we have a need to store user or system generated "comments" about a particular entity. For example, comments can be created about a customer, an order, or a purchase order. These comments all share many of the same characteristics, with the exception of the referenced entity. All comments require the date, time, user, and comment text. They also require a foreign key to the referenced table so that you can look up comments for that particular entity. Currently the application has a separate table for each type of comment (e.g. customer_comments, order_comments, purchaseOrder_comments). The schemas of these tables are all identical with respect to the date, time, user and comment text, but each has a FK to the respective table that the comment is for. Is this the best design or is there a better design? A: Personally, I'd create a single comment table and then use one intersection table per entity (customer, order, etc.) to link the comment with the entity. A: If it had been me, I think I would have had a single Comments table with an extra comment_type_id field that maps to whether the comment should be available for customer entities, order entities, etc... Somewhere else you'd need to have a comment_type table that comment_type_id refers to. This way, if you decide to add an extra piece of meta-data to comments, you only have to do it in a single Comments table rather than in customer_comments, order_comments, etc... A: you could put all these comments into one table comments and add another column commented_table, which would make it a polymorphic ManyToOne. some frameworks / orms (like Rails' ActiveRecord) do have built in support for that, if whatever you're using doesn't, it's basically as simple as adding another where clause
{ "language": "en", "url": "https://stackoverflow.com/questions/7534748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to stop a browser from opening a dialogue box when a user clicks the right mouse button? I'm making a game, it uses the canvas element, and I need both of the mouse buttons. How can I stop the browser (I'd like it to run in most major ones, so, it's preferred that the solution is universal) from opening that dialogue box when the user presses the right mouse button. How can I do that in JavaScript? I tried this, but it does not work: self.onClick = function(ev) { if(ev.button == 2) { ev.preventDefault(); } var x = ev.clientX - self.canvas.offsetLeft; var y = ev.clientY - self.canvas.offsetTop; input.mouse = {"button": ev.button, "click": true, "x": x, "y": y}; } The global variable input is then sent to the server to be processed. EDIT: it works now. I had to edit the canvas element (canvas oncontextmenu="return false") A: You can try this: self.oncontextmenu = function() { return false; }; A: Use self.oncontextmenu and call preventDefault on the event. self.oncontextmenu = function(e) { e.preventDefault(); } Note that some users may not like you disabling their context menu. A: It is onclick and not onClick In this case use self.oncontextmenu=function() { return false } or self.oncontextmenu=function(e) { e.preventDefault(); } in plain JS
{ "language": "en", "url": "https://stackoverflow.com/questions/7534753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery add a class only if it does not have another class I have a navigation animation that is being applied to elements with the "js" class - via a css background. I don't want this animation to occur on the link for the current page (a class "current" is being echo'd out by PHP to the current page). So basically the page your on (current page) link in the main nav will have a class of current, the others a class of js - and get the animation. How do apply that logic in a funciton? I can do it via css background but want to do it in js. Here is working js used in combination with css for desired look: $(function() { $("ul#mainNav li a").addClass("js"); $("ul#mainNav li a").hover( function () { $(this).stop(true,true).animate({backgroundPosition:"(0 0)"}, 200); $(this).animate({backgroundPosition:"(0 -5px)"}, 150); }, function () { $(this).animate({backgroundPosition:"(0 -130px)"}, 200); } ); }); What I'm trying to no avail: $(function() { if($("ul#mainNav li a").hasClass("current")) { //do nothing } else { $(this).addClass("js") } //rest of animation function }); }); A: $("ul#mainNav li a").not(".current").addClass("js"); Your if should work too, but you mix up this and $("ul#mainNav li a"). A: There are several ways to approach this. If you need the selector you have for other things, you can do it like this: $(function() { $("#mainNav li a").each(function() { if (!$(this).hasClass("current")) { $(this).addClass("js") } }); //rest of animation function }); If you don't need that whole selector for other things, then you can do it more simply like this: $("#mainNav li a").not(".current").addClass("js"); Note, I've removed the ul from the start of your main selector as it is not required since ids are unique. A: if(! $("ul#mainNav li a").hasClass("current")) { $("ul#mainNav li a").addClass("js") } The other answer is better, but this is how your if statement would work if you insisted to do it that way. $(this) only works in the correct scope. You're confusing its usage for when you are using a closure like: $('a').each(function(){ $(this).stuff(); }); A: You could use the :not selector provided by jQuery to do it more succinctly: $("ul#mainNav li a:not(.current)").addClass("js") A: For anyone looking at this to us on a live event (such as .live('click', ) $("ul#mainNav li a").not(".current").addClass("js"); GolezTrol's '.not' answer (above) although effective usually can fall down on live events. So I would suggest using the answer supplied by Chris G. (below) if(! $("ul#mainNav li a").hasClass("current")) { $("ul#mainNav li a").addClass("js") } I hope this is useful to someone as it may save them some time trying to figure out what they have done wrong (as it was in my case)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ doesn't convert string from data I want to write a little program which should be used in supermarkets. everything is fictitious and it's only for learning purposes. However, The tool generate a new data for every new article. in the data there are 2 lines, the name and the prise. The data is named as the article number of the product. So the user enter a articlenumber and the tool looks for a data with this number, if it found it, it reads the 2 lines and initiates the variables. But for some reasons it does not convert and copy the strings correctly. here is the part which loads the data. int ware::load() { string inhalt; cout << "please insert article number" << endl; cin >> articlenumber; productname.open(articlenumber, ios::in); if (!productname.is_open()) { cout << "can't find the product." << endl; return 1; } if (productname.is_open()) { while (!productname.eof()) { getline(productname, inhalt); strcpy(name,inhalt.c_str()); getline(productname, inhalt); price = atoi (inhalt.c_str()); cout << inhalt << endl; } warenname.close(); } cout << endl << endl << "number: " << inhalt << " preis: " << price << " name: " << name << endl << endl; //this is a test and will be deleted in the final } hope you can help me! Here is the class: class ware{ private: char articlenumber[9]; char name[20]; int price; fstream warennamefstream; ifstream warenname; public: void newarticle(); //this to make a new product. void scan(); //this to 'scan' a product (entering the article number ;D) void output(); //later to output a bill int load(); //load the datas. }; hope everything is fine now. A: First, you have a using namespace std; somewhere in your code. This occasionally leads to subtle bugs. Delete it. ( Using std Namespace ) int ware::load() { string inhalt; cout << "please insert article number" << endl; cin >> articlenumber; The type of articlenumber is incorrect. Declare it std::string, not char[]. ( What is a buffer overflow and how do I cause one? ) productname.open(articlenumber, ios::in); There is no reason to have an ifstream lying around waiting to be used. Also, there is no point in providing ios::in -- it is the default. Just use the one-argument form of the ifstream constructor. if (!productname.is_open()) { cout << "can't find the product." << endl; return 1; } Don't bother checking to see if the file opened. Your users don't care if the file was present or not, they care whether the file was present AND you retrieved the essential data. if (productname.is_open()) { while (!productname.eof()) { getline(productname, inhalt); strcpy(name,inhalt.c_str()); getline(productname, inhalt); price = atoi (inhalt.c_str()); cout << inhalt << endl; } warenname.close(); } This loop is just wrong. * *Never invoke eof(). It doesn't do what you think it does, and will cause bugs. *Why is this a loop? Aren't there only two lines in the file? *There is no point in calling close. Just let the file close when the istream goes out of scope. *Why is warename different than productname? *Don't store your data in char[]. This is the 21st century. Use std::string. . cout << endl << endl << "number: " << inhalt << " preis: " << price << " name: " << name << endl << endl; //this is a test and will be deleted in the final * *Never use endl when you mean to say '\n'. Each of those endl manipulators invokes flush, which can be very expensive. ( What is the C++ iostream endl fiasco? ) *You forgot to return a value. Try this instead: int ware::load() { // This declaration should be local std::string articlenumber; cout << "please insert article number" << endl; cin >> articlenumber; // This declaration should be local std::ifstream productname(articlenumber.c_str()); // These declarations can be class members: std::string name; int price; std::string number; if(getline(productname, name) && productname>>price && productname>>number) { cout << "\n\n" << "number: " number << " preis: " << price << " name: " << name << "\n\n"; //this is a test and will be deleted in the final return 0; } else { cout << "can't find the product." << endl; return 1; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select from table1 where similar rows do NOT appear in table2? I've been struggling with this for a while, and haven't been able to find any examples to point me in the right direction. I have 2 MySQL tables that are virtually identical in structure. I'm trying to perform a query that returns results from Table 1 where the same data isn't present in table 2. For example, imagine both tables have 3 fields - fieldA, fieldB and fieldC. I need to exclude results where the data is identical in all 3 fields. Is it even possible? A: There are several ways to do it (assuming the fields don't allow NULLs): SELECT a, b, c FROM Table1 T1 WHERE NOT EXISTS (SELECT * FROM Table2 T2 WHERE T2.a = T1.a AND T2.b = T1.b AND T2.c = T1.c) or SELECT T1.a, T1.b, T1.c FROM Table1 T1 LEFT OUTER JOIN Table2 T2 ON T2.a = T1.a AND T2.b = T1.b AND T2.c = T1.c WHERE T2.a IS NULL A: select t1.* from table1 t1 left join table2 t2 on t1.fieldA = t2.fieldA and t1.fieldB = t2.fieldB and t1.fieldC = t2.fieldC where t2.fieldA is null Note that this will not work if any of the fields is NULL in both tables. The expression NULL = NULL returns false, so these records are excluded as well. A: This is a perfect use of EXCEPT (the key word/phase is "set difference"). However, MySQL lacks it. But no fear, a work-around is here: Intersection and Set-Difference in MySQL (A workaround for EXCEPT) Please not that approaches using NOT EXISTS in MySQL (as per above link) are actually less than ideal although they are semantically correct. For an explanation of the performance differences with the above (and alternative) approaches as handled my MySQL, complete with examples, see NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: MySQL: That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS. Happy coding. A: The 'left join' is very slow in MYSQL. The gifford algorithm shown below speeds it many orders of magnitude. select * from t1 inner join (select fieldA from (select distinct fieldA, 1 as flag from t1 union all select distinct fieldA, 2 as flag from t2) a group by fieldA having sum(flag) = 1) b on b.fieldA = t1.fieldA;
{ "language": "en", "url": "https://stackoverflow.com/questions/7534774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to attach a list box to a button onclick I am creating a monthly calendar of events. Each day that has one or more events is represented by a button labelled with the day of the month. If the user clicks on a day with one event, that event is chosen. However if the user clicks on a button with more than one event, I would like to display a ListBox containing the event times. The user then chooses a time by clicking on a ListBox item. Is this the way to go? Is there a "better" way to approach the problem? The target is a mobile device. Language C#; OS Windows CE. A: The solution was not to use a ListBox at all. Rather, a number of Buttons, each labelled with one of the times, was collected into a Panel that was then positioned under the triggering day button. The BringToFront ( ) method was invoked against each Button as well as against the Panel. The Panel was Hidden, its controls were Cleared, and it was Disposed when one of the Buttons it contained was Clicked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory leaks in pushViewController and (I think) coming back from a GCD queue I'm having some trouble with memory leaks on one of my view controllers. From my main view controller, I'm pushing my settings view controller like so: -(IBAction)launchSettings { SettingsViewController *svc = [[SettingsViewController alloc] init]; svc.title = @"title of app"; //this actually adds a back button for the next vc pushed self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil] autorelease]; [[self navigationController] pushViewController:svc animated:YES]; // <--Instruments says leak is here [svc release]; if (AdsAreEnabled) { ADBannerView *adBanner = SharedAdBannerView; adBanner.delegate = nil; } } So, when I initially push the view controller, I have no leaks. The view controller uses a GCD queue to load up my In-App Purchase store, and when I hit the "back" button I've created above to pop it off the stack, that's when a crapload of leaks show up in Instruments. A bunch are showing up in the line of code where I push the view controller, which makes no sense to me since I immediately release it. A couple other leaks are only leaking in main, either NSCFstrings, SKProduct and SKProductInternal, all of which I think are only brought up in the GCD queue. Here's where instruments is telling me the problem is: int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); // <-- Instruments says leak is here [pool release]; return retVal; } Here's my code where I call GCD, in its own method that gets called during viewDidLoad of the SettingsViewController: if ([iapManager canMakePurchases]) { // Display a store to the user. iapTableView.sectionFooterHeight = 0; iapTableView.rowHeight = 50; iapTableView.scrollEnabled = NO; //init sectionNames here to avoid leakage. sectionNames = [[NSArray alloc] initWithObjects:@"Get Rid of Ads!", nil]; [spinner startAnimating]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadStore) name:kInAppPurchaseManagerProductsFetchedNotification object:iapManager]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadStore) name:kTransactionCompleted object:iapManager]; //Run this in seperate thread to avoid UI lockup dispatch_queue_t store_check = dispatch_queue_create("see if store is available", NULL); dispatch_async(store_check, ^ { [iapManager loadStore]; }); dispatch_release(store_check); } I'm a little stumped as to what I've done wrong here - I use exactly the same technique to load up a different view controller and it doesn't leak, and I can't figure out how to tell if/where my GCD stuff is leaking - everything's been analyzed repeatedly and comes out clean. I remove my observer from the Notification Center in SVC's dealloc so it's not that. I made sure to remove the transaction observer in my IAP manager's dealloc, so it's not that. Any suggestions? Anything else you'd need to know to help me figure out where I've gone so terribly terribly wrong here? Edited to add: I release sectionNames in SVC's dealloc method, so that's not it either. Edit 2: I tried auto-releasing svc when I alloc it (and getting rid of the corresponding release) but I'm still getting the same leaks. A: Well, I finally figured it out with some troubleshooting help from a friend - for some reason I forgot you still have to release an IBOutlet ivar even if you haven't set it up as a property (for some reason I thought an IBOutlet autoreleased if it wasn't a property, which is not true), and once I had the proper releases in dealloc, all my leaks magically went away. Duh. Another thing to add to my Idiot Checklist, I suppose. :) Thanks for the suggestions, guys! A: First of all, in "launchSettings". You have initialized the UIBarButtonItem by "alloc and init" which makes its retain count = 1 but you haven't released it. You should realize that those properties are retaining the values passed to them. So you could have autoreleased it. I should say that this action isn't needed as the back button is already put for you. Second, in the last code snippet, you did the same sectionsName.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Java make a image move down How can i make a image just scroll down a straight line by it self? Like The Image starts up here and then it will just smoothly scroll down till it hits the bottom and stop Please look at this: http://tinypic.com/r/1z17iv9/7 A: i think you should take a look about TranslateAnimation on the doc , refer this , And this is some examples of it : Tutorials A: You should save this TopDownAnim.xml in the anim folder inside resources. <translate android:interpolator="@android:anim/accelerate_interpolator" android:fromXDelta="0" android:toXDelta="0" android:zAdjustment="top" android:fromYDelta="0%" android:toYDelta="100%" android:duration="1000"/> And in the code you can use something like TranslateAnimation tdAnim = AnimationUtils.loadAnimation(this, R.anim.TopDownAnim); view.startAnimation(tdAnim); A: Your question is a bit vague, but I think what you're looking for is a ScrollView. Try referring to this documentation. What you want to do is to put the ImageView inside this ScrollView. EDIT Ah, I see. I apologize for misunderstanding what you were asking about. Perhaps you should consider animating the ImageView with some basic view animations. Try looking at this question. A: These tasks are there in game development where the objects are moved around the screen. You can take a look at this and see how objects are moved on the screen. On the same lines you can solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dynamic div height attribute I'm looking to extend the height of my div dynamically with my menu on the left. Here is the url: http://www.whiterootmedia.com I would like to add grass and the bass of the tree to the bottom of this web page. Any help or ideas? currently the div has this inline css: <div id="tree_trunk_div"style="position:relative;top:-100px; width:270px; text-align:right; margin-left:auto; background-image:url('../images/treetrunk7.png');background-repeat:repeat-y;"> A: Use jQuery to do it ^^ http://api.jquery.com/show/ A: Almost... just a few tweaks. <div id="tree_trunk_div" style="position:absolute;bottom:0px; width:270px; height:100%; text-align:right; margin-left:auto; background-image:url('../images/treetrunk7.png');background-repeat:repeat-y;">
{ "language": "en", "url": "https://stackoverflow.com/questions/7534796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to restrict which nodes produce output in stylesheet I am working on a transform. The goal is to transform nodes into key/value pairs. Found a great stylesheet recommendation on this forum but I could use some help to tweak it a bit. For any node that has no children, the node name should become the value of <name> and the value should become the value of <value>. The source document may have some hierarchical structure to it, but I want to ignore that and only return the bottom nodes, transformed of course. Here is my source data: <?xml version="1.0" encoding="UTF-8"?> <objects> <Technical_Spec__c> <Id>a0e30000000vFmbAAE</Id> <F247__c>4.0</F247__c> <F248__c xsi:nil="true"/> <F273__c>Bronx</F273__c> ... </Technical_Spec__c> </objects> Here is the stylesheet: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="*[count(*) = 0]"> <item> <name> <xsl:value-of select="name(.)" /> </name> <value> <xsl:value-of select="." /> </value> </item> </xsl:template> <xsl:template match="*[count(*) > 0]"> <items> <xsl:apply-templates/> </items> </xsl:template> </xsl:stylesheet> DESIRED OUTPUT - The stylesheet should transform these nodes to key value pairs like this: <items> <item> <name>F247__c</name> <value>4.0</value> </item> <item> <name>F248__c</name> <value></value> </item> <item> <name>F273__c</name> <value>Bronx</value> </item> ... </items> CURRENT OUTPUT - But it creates nested 'items' elements like this: <items> <items> <item><name></name><value></value></item> ... </items> </items> I understand (I think) that it is matching all the parent nodes including the top node 'objects' and nesting the 'matches count 0' template. So I tried altering the matches attribute to exclude 'objects' and start at 'Technical_Spec__c' like this (just the template lines): <xsl:template match="objects/Technical_Spec__c/*"> <xsl:template match="*[count(*) = 0]"> <xsl:template match="objects/*[count(*) > 0]"> In my mind this says "First (master) template only matches nodes with parents 'objects/Tech_Spec'. Second (inner) template matches any node with no children. Third (outer) template matches nodes with parent 'objects' " - which should limit me to one . OUTPUT AFTER ALTERING MATCH - Here is what I get: <?xml version="1.0" encoding="UTF-8"?> - <items xmlns=""><?xml version="1.0"?> <item><name>Id</name><value>a0e30000000vFmbAAE</value></item> <item><name>F247__c</name><value>4.0</value></item> ... </items> The extra <items> block is gone but there is an extra <?xml> block stuck in the middle so it's not recognized as valid xml anymore. Any ideas? Why the extra <?xml>; How to restrict template to particular parts of the tree? A: Through a great deal of trial and error, I stumbled on the following solution: I added a root anchor to the third template match criteria. Instead of match="*[count(*) > 0]", I now have /*[count(*) > 0]. This appears to eliminate the outer <items> element. If anyone can tell me why, I'd appreciate it. Why would this be different than /objects/*[count(*) > 0] ? I do think Dimitre is right about the processor (which is IBM Cast Iron) so I did open a ticket. I tested the same stylesheet from above on an online XSLT tester and did not get the extra <?xml ?> tag. <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="*[count(*) = 0]"> <item> <name> <xsl:value-of select="name(.)" /> </name> <value> <xsl:value-of select="." /> </value> </item> </xsl:template> <xsl:template match="/*[count(*) > 0]"> <items> <xsl:apply-templates/> </items>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: General question about curl in php It's simple question, can curl make posts on vBulletin forum? In PHP script so of course. I didn't try that so just if anyone now or ever tried, to spare me some time I would appreciate a lot :D If there is too much job, I'm not really sure if I should try to write that code A: can curl make posts on vBulletin forum? Sure it can. The worst part would be to catch tokens, login and other forms which requires to parse HTML A: While cURL can, you should more look at the vBulletin API. It contains a webservice to communicate with the vBulletin Board, which should be more suitable than the raw cURL method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Contact Form Problem http://www.raymondselda.com/php-contact-form-with-jquery-validation/ I'm trying a few different contact forms including the one above. I have it running on this page: http://themeforward.com/demo2/features/contact-form/ The problem is this form does not successfully send e-mails to the address in the code (finished code can be found here: http://www.raymondselda.com/php-contact-form-with-jquery-validation/ ) Does anybody know what the problem may be? //If there is no error, send the email if(!isset($hasError)) { $emailTo = 'youremail@email.com'; //Put your own email address here $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nComments:\n $comments"; $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email; mail($emailTo, $subject, $body, $headers); $emailSent = true; A: Many reasons: * *Mail isn't configured properly on your server. mail() will return a boolean FALSE if it can't hand off the email to an SMTP server. You're not checking for that condition *The SMTP server isn't configured properly to allow you to send through it *The receiver server has your sending server blacklisted *The email is treated as spam and is getting trashed First place to start looking is mail()'s return value. Then go look at your SMTP server's log to see what happens to the email (if) once PHP handed it over. The SMTP server's log will also say if the receiving server bounced/refused it. If it's getting silently thrown in a spam folder on the receiver server, there'll be NO evidence of this on your end, and you'll have to investigate further on the receiving end. Email is a complicated business with many many invididual steps where each one has to work right. Any glitches anywhere along the line and the email is probably gone. You have to investigate what happens at EACH of these stages to figure out why something isn't being delivered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight binding with filtering I am currently trying to figure out a binding solution in Silverlight 4. I have an observable collection of items. I want to bind this to a ComboBox but only display the items that match a certain condition. For example group == "Test Group." I have tried quite a few ways to make this work but haven't had any success. A: In the past I have used LINQ in an exposed property on the VM e.g: /// <summary> /// Get filtered results(by location) /// </summary> public ObservableCollection<SearchResultData> FilteredResults { get { return new ObservableCollection<SearchResultData>(Results.Where(p => p.LocationId == CurrentLocation.Id)); } } Using this approach you will need to provide a notification when the underlying collection in the LINQ changes e.g: public ObservableCollection<SearchResultData> Results { get { return _results; } set { _results = value; NotifyOfPropertyChange(() => Results); NotifyOfPropertyChange(() => FilteredResults); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make a secure file that PHP can read? I have a file sort of like this, it's a user database (udb.htm): user1:pwd1 user2:pwd2 user3:pwd3 something along the lines of that. I would like to secure this file and make it available for PHP via the file_get_contents("udb.htm"); method, but not a browser window. Thanks! A: you can: * *upload the file in a directory outside the public html directory, but that php has access *block the access to the file using apache .htaccess <Files> or similar *use HTTP Basic Authentication *save your data in an actual database (mysql, mssql, oracle, sqlite) A: Put the file outside of the web root. For instance, in the directory that contains public_html. PHP can access it (and any other file on the system), but you can't get to it from the web. A: Move the file into a folder still accesible to PHP but not web clients. A: What you want to do is put the database below the web path. So for example, if your website is at www.example.com and it points to: /var/www/html Then you can put your password file into /var/www/password/udb.htm Then access it from your php script as file_get_contents("../../password/udb.htm") Your script can access the file, but your web service will not. A: This changes the permissions of your file before open, and remove grants when you close the file, be sure about webserver permissions over the file. <?php $file = 'udb.htm'; chmod($file, 0600); $contents = file_get_contents($file); chmod($file, 0000); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove alias details in Nhibernate logging When NHibernate logs its SQL, it uses aliases for all the columns it retrieves e.g. SELECT menuitems0_.menuSectionId as menuSect6_1_ I was just wondering if it's possible to omit the alias information to make the SQL a bit clearer e.g. SELECT menuitems.menuSectionId This would help a lot when I am doing a demonstration to other people, as it will be easier to show them what NHibernate is doing under the hood. Thanks A: I don't think it is possible to remove aliases but you can make output look a lot nicer if you use 'FormatSql' option. Set it to true when configuring session factory config.SetProperty(Environment.ConnectionString, "...") config.SetProperty(Environment.ShowSql, "true") config.SetProperty(Environment.FormatSql, "true") So the output would look like this: SELECT this_.ID as ID58_0_, this_.Name as Name58_0_, ... FROM MyTable this_ WHERE this_.Name = @p0; Or use NHibernate Profiler for demo purposes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display Rows side by side, Kind of pivot I have a table like this Column1 | Column2 ------------------- A | 1 A | 2 A | 3 B | 4 B | 5 B | 3 C | 2 C | 2 C | 2 D | 7 D | 8 D | 9 I want to output it as A | B | C | D -------------------- 1 | 4 | 2 | 7 2 | 5 | 2 | 8 3 | 3 | 2 | 9 It will have fixed Rows/Columns like A,B,C,D. Could you suggest a query in SQL Server 2005/2008? A: it's better to know your clustered key in the table, since the order might be different after the result. Martin is right, try this out, it will get you started: SELECT pvt.A, pvt.B, pvt.C, pvt.D FROM (SELECT *, row=ROW_NUMBER() OVER(PARTITION BY Column1 ORDER BY (SELECT 1)) FROM yourtable) AS A PIVOT (MIN(Column2) FOR Column1 IN ([A], [B], [C], [D])) AS pvt
{ "language": "en", "url": "https://stackoverflow.com/questions/7534839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to force https I have a grails project. Right now, the user can access it either with HTTP or HTTPS. I would like to require that they can only access it through HTTPS. any ideas? I do have spring security core installed, if that can be of help thanks jason A: Spring's core supports that: grails.plugins.springsecurity.secureChannel.definition = [ '/path/**': 'REQUIRES_SECURE_CHANNEL' ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7534844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Reset Static fields on change in INI file I have a C# class library which reads an INI file to obtain the value for a parameter for e.g. (debug=on) Now on every call and some times multiple times in one call I have to check this INI and this leads to I/O overhead. To overcome this I made the parameter in code to be static so at the load time it will check the INI and will store the result. But now I have to add this condition that reset your IIS or kill your windows form in case you change the INI value. Note: I dont want to use configuration files (app.config/web.config) as this library is used in various projects (forms/web/services). So in your opinion what is the best way to Reset Static fields on change in INI file without doing an IIS Reset etc. A: Look into using a FileSystemWatcher A: Any reason it has to actually be static fields? I would suggest having some sort of configuration interface which you can pass around as a dependency to the bits that need it. You can then have three implementations: * *A "fake" with writable properties used for testing *A "file reading" implementation which reads a file on construction, and is then immutable *A "file watching" implementation which has the idea of its current configuration (and instance of the previous one) and replaces its "current" one when the file changes, via FileSystemWatcher. Calls to read the configuration properties simply delegate to the "current" configuration. This approach will lead to a much better testing experience - both for within your class library and potentially for code which uses your class library. If you really, really need a single place that you can always get at a configuration, you could always use the above but have a single static field which refers to the "file watching" implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preparing SQLite SQL statements in PHP I'm trying how best to prepare my SQLite SQL strings in PHP. The SQLite3 class comes with an escapeString() function, but here are my issues: Try 1) $sql = "INSERT INTO items ('id','content','title','created') VALUES ('4e7ce7c18aac8', 'Does this work', NULL, '2011-09-23T16:10:41-04:00');"; $sql = SQLite3::escapeString( $sql ); echo ($sql); This results in a string that's all jacked up: INSERT INTO items (''id'',''content'',''title'',''created'') VALUES (''4e7ce7c18aac8'', ''Does this work'', NULL, ''2011-09-23T16:10:41-04:00''); Those aren't double quotes, rather doubled-up single quotes. Obviously won't work. Try 2) $sql = 'INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Does this work", NULL, "2011-09-23T16:10:41-04:00");'; $sql = SQLite3::escapeString( $sql ); echo ($sql); This results in: INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Does this work", NULL, "2011-09-23T16:10:41-04:00"); This query works fine, but the escapeString function hasn't modified anything as there's nothing to escape... Try 3) $sql = 'INSERT INTO items ("id","content","title","created") VALUES ("4e7ce7c18aac8", "Doesn't this work", NULL, "2011-09-23T16:10:41-04:00");'; $sql = SQLite3::escapeString( $sql ); echo ($sql); Here's the big problem- Now I have an apostrophe in one of my values. It won't even make it to escapeString() because PHP will throw an error on the invalid string: PHP Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' How am I supposed to be approaching this? Keep in mind that in the actual code my parameter values will be variables, so am I supposed to escape each variable before I pass it into the string? If so, what function do I use? Finally, what's the point of escapeString()?? I can't figure out how it's supposed to be used correctly. A: You don't escape the entire query. You escape unsafe data you're inserting into the query, e.g. $unsafe = $_GET['nastyvar']; $safe = SQLite3::escapeString($unsafe); $sql = "INSERT INTO table (field) VALUES ($safe);"; echo ($sql);
{ "language": "en", "url": "https://stackoverflow.com/questions/7534848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to apply OR rules in find of MongoDB db.media.find( {Released : {$gte: 1990, $lt : 2010}}) Looks for movies released between 1990<= to <2010 and this is an AND condition. How to apply an OR condition in the query statement? For example, Looks for movies released before 2000 or type is of action. A: You can use the $or command in your queries. http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or Your query would look something like this: db.media.find( { $or : [ { Released : { $lt: 2000 } }, { Type : "Action" } ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7534849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: We are getting a permission denied error in IE8. facebook-graph-api We are getting a permission denied error in IE8. It happens after the FB.init. We have tried the channelUrl fix. We have put the as the first tag after the body. We have tried the document.domain in both the script and in the channel.html. We have tried the FB.UIServer.setActiveNode workaround. It works fine in IE9, FF, Chrome and Safari. <div id="fb-root"></div> <script src="//connect.facebook.net/en_US/all.js"></script> <script type="text/javascript"> var myUserId; document.domain = 'XXXX.XXXX.com'; window.fbAsyncInit = function() { FB.init({ appId: 'XXXXXXXXX', status: true,`enter code here` cookie: true, xfbml: true, channelUrl: 'http://XXX.XXXX.com/channel.html' }); FB.UIServer.setActiveNode = function(a, b) { FB.UIServer._active[a.id] = b; } // IE hack to correct FB bug I am getting an permission denied error in IE8 in a facebook-iframe for a tab app on a facebook-fanpage. Any ideas how to fix this? A: This worked for me: FB.init({ appId: 'xxxxx', appSecret: 'xxxxxxxxx', status: true cookie: true }); // this code solves the issue FB.UIServer.setLoadedNode = function (a, b) { FB.UIServer._loadedNodes[a.id] = b; }; As seen here http://ikorolchuk.blogspot.com/2011/09/facebook-javascript-sdk-security-error.html?showComment=1323866805727#c7681567069563597438 A: I'd suggest attaching the debugger and posting exactly where the error occurs. If its related the Facebook Proxy it might be a temporary issue with Facebook. A couple of suggestions ( not mentioned above ): 1/ Try adding FBML to your html tag: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en"> 2/ Try disabling compatibility mode options if your are accessing a test server that might be considered an intranet site ( generally same subnet ). A: It is possibly because you redirect to a HTTP page while your current iframe is https. The protocol of the iframe can be https, maybe because of an internal redirect, even if the Facebook page is http.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery: how to let showed div which display:none, keep showing when load to another page? I have a div in masterpage that I set a toggle effect on it. It's like expand folders; when you click the "folders", it will expand folders so all the sub-level folders show up. Each sub-level folder is a hyperlink. I set the folders' div's to style="display:none" so when you first load the page it won't show all the sub-level folders. The problem is whenever I click a sub-level folder the page reloads and the folder div is hidden. How to keep it shown when it is already in shown status when directed to another page. The folder div is in masterpage. The div has id=AppendedFolder. I used following code but it does not work: $(document).ready(function() { if ($('#AppendedFolder').is(":visible")) { $('#AppendedFolder').show(); } }); A: If you want to save state from one page that you can use in another page, you need to save it it somewhere and then in the other pages, check that state and show the object that you wanted visible. The classic place to save this state is in a cookie. You would then have initialization code in your other pages that examine the value of the cookie and decide, based on the cookie value, whether to show #AppendedFolder or not. Some of the other ways that you can pass state to the next page are: HTML5 local storage (only available in newer browsers) or passing a query parameter to all subsequent pages that indicates the state of this visibility. A: If I understand you correctly, you basically need the page, after being reloaded, to know which folders should still be expanded, correct? In that case, it seems that you have 3 possible options: * *If a certain URL should always have certain folders expanded, add in some JS code (or some PHP code if you can) that will expand the correct folders based on the URL. *Use cookies. This would allow you to maintain the same expanded folders from the previous page. *Any time some folders are expanded, append a parameter like "?expandedFolders=xxx" to all of the links on the page. Then, upon page load, either PHP or JS would be used to get the value of that parameter and expand the correct folders. This really wouldn't achieve anything that #2 wouldn't do, and it would definitely be more work for your script to do, and maybe more work for you to code as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android kernel configuration menu for ARM DS-5 Streamline I am trying to use ARM DS-5 streamline for Android and I am having a hard time to figure out the basic settings. You must enable certain kernel configuration options to run Streamline. In the kernel configuration menu, use the arrow keys to navigate to the desired submenu and press Enter. Each submenu is listed with the action you need to take within it. The official document says this. And I was trying to see the kernel configuration menu on Android. So I typed something like this adb shell cd sys cd kernel and I could see this -r--r--r-- root root 4096 1970-01-14 16:54 uevent_seqnum -rw-r--r-- root root 4096 1970-01-14 16:54 uevent_helper -rw-r--r-- root root 4096 1970-01-14 16:54 profiling drwxr-xr-x root root 1970-01-14 16:54 uids drwxr-xr-x root root 1970-01-14 16:54 debug drwxr-xr-x root root 1970-01-01 00:00 ipv4 drwxr-xr-x root root 1970-01-14 16:54 mm drwxr-xr-x root root 1970-01-14 16:54 slab drwxr-xr-x root root 1970-01-14 16:54 config I typed make menuconfig and I got his make: not found How do I see the menuconfig menu on Android devices ? Thanks in advance.. A: Like you, i wanted to use ARM DS-5. Notice something important about this - your kernel might be already be built properly with the required menuconfig options (It was for me on a production device). However, you still need access to the kernel code to build binary that will run your target device. The way to check if the kernel was already built properly is "adb shell" into a running device and then: adb pull /proc/config.gz ./config.gz and then from your linux env. (you can simply extract and look inside if you're on windows) zcat ./config.gz | grep <option> //for example zcat ./config.gz | grep CONFIG_TRACING. I learned this from: {DS-5 install root}/arm/gator/README_Streamline.txt On my Samsung Galaxy S4, for example, CONFIG_PROFILING=y is found (amongst other needed flags). A: This is not something you do on your Android device but on your Android build machine. If you have installed the Android build environment and then checked out a suitable kernel source you would use make gconfig or make menuconfig to configure a kernel. However, often devices have a default configuration already. For instance to build the kernel for the Nexus S you use the following: export PATH=$PATH:$ANDROID_ROOT/prebuild/linux-x86/toolchain/arm-eabi-4.4.3/bin make ARCH=arm clean make ARCH=arm herring_defconfig make -j4 ARCH=arm CROSS_COMPILE=arm-eabi- For another device, something similar will likely be available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using an NSFormatter to alter string as user types I'm writing a Mac OS X desktop Cocoa app. I've got an NSTableView with some values and I'm trying to control those values using a custom NSNumberFormatter. My desired behavior: As a user is typing a value, if they type -, I want it to behavior similar to a +/- button on a calculator. So if the user types "500-" then I want to automatically replace that string with "-500". Now, I've got a working subclass of NSNumberFormatter which handles this situation and returns my desired replacement string. But when I'm typing into my NSTableView, my logs are showing me that "500-" is getting replaced with "-500" but the NSTableView only shows "500" and doesn't show the - either before OR after. Is there something I need to do in my xib or in my NSNumberFormatter subclass so that the NSTableView will actually show the negative number? - (BOOL) isPartialStringValid:(NSString **)partialStringPtr proposedSelectedRange:(NSRangePointer)proposedSelRangePtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSelRange errorDescription:(NSString **)error is logging this to the console: proposed string: 500- replacement string: -500 But the cell in the NSTableView still shows just "500" afterward. A: It turns out that my old school C skills are just rusty and I wasn't passing the new string back correctly. I was incorrectly writing: partialStringPtr = &validString; But the correct code is: *partialStringPtr = validString;
{ "language": "en", "url": "https://stackoverflow.com/questions/7534867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comparing generic types I am writing a Generic Binary Search Tree. I need to compare two generic types. How to do it, assuming the the user has implemented IComparable in T class. private void Insert(T newData, ref Node<T> currentRoot) { if (currentRoot == null) { currentRoot = new Node<T>(newData); return; } if (newData <= currentRoot.data) //doesn't work, need equivalent functionality Insert(newData, ref currentRoot.lChild); else Insert(newData, ref currentRoot.rChild); } A: You have to add a generic constraint where T: IComparable<T> to your method to make the CompareTo() method available to instances of your type T. private void Insert(T newData, ref Node<T> currentRoot) where T: IComparable<T> { //... } Then you can use: if (newData.CompareTo(currentRoot.data) <= 0) { //... } A: use the where clause, i.e. class Node<T> where T : IComparable http://msdn.microsoft.com/en-us/library/bb384067.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7534869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Checking all checkboxes in jQuery I have a table setup like this: <table> <thead> <th> <input type="checkbox" class="check-all" /> </th> <th> Title </th> </thead> <tbody> <tr> <td><input type="checkbox" /></td> <td>Name</td> </tr> <tr> <td><input type="checkbox" /></td> <td>Name 2</td> </tr> </tbody> </table> I'm trying to have it so when the checkbox in the header with class 'check-all' is checked, it checks all the checkboxes below. This is what I have, but it doesn't seem to work $('.check-all').click( function(){ $(this).parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked')); } ) Any ideas? Thank you! A: First you should use jQuery.closest() to find the closest table tag. $('.check-all').click(function() { $(this).closest('table').find("input:checkbox").attr('checked', this.checked); }); Second. If you are using jQuery 1.6 or higher you should use jQuery.prop() $('.check-all').click(function() { $(this).closest('table').find("input:checkbox").prop('checked', this.checked); }); Finally, for a boolean value from the check-all box you do not need the jQuery object you can simply use HTML DOM this.checked A: I lost track of parents. :) Try this: $(this).closest("table").find("input[type='checkbox']").attr('checked', $(this).is(':checked')); Edit: P.S. @John Hartsock changed your syntax slightly. I left your syntax as is, but his syntax is better (or you you can just use .find(":checkbox"). I'm guessing that jquery is able to find checkboxes in a much more efficient way than getting all inputs and then checking the attribute "type" to see if it's a checkbox. A: I wrote an article about this a while back. It will be easier if you give all related check boxes the same class. UPDATE Here's a jsFiddle with the code copied here now that I've got more time. HTML <table> <thead> <tr> <th> <input type="checkbox" class="check-all" /> </th> <th>Check All Below</th> </tr> <tr><th><hr /></th></tr> </thead> <tbody> <tr> <td><input type="checkbox" class="groupOne" /></td> <td>Name</td> </tr> <tr> <td><input type="checkbox" class="groupOne" /></td> <td>Name 2</td> </tr> </tbody> </table> JavaScript var $_checkAll = $('.check-all'); var $_groupOne = $('.groupOne'); $_checkAll.click(function(){ $_groupOne.prop('checked', $_checkAll.prop('checked')); }); /* If I uncheck a groupOne checkbox, uncheck the related "check all" */ $_groupOne.click(function(){ if ( !$(this).prop('checked') ) { $_checkAll.prop('checked', false ); } }); /* Checking the "check all" checkbox when all groupOne checkboxes have been checked is left as homework. */
{ "language": "en", "url": "https://stackoverflow.com/questions/7534874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Pass data/variables/objects to Zend_Controller_Plugin I am converting an old ZF app (its using an early ZF version where we used to do manual app loading/config in the index.php) to latest version, and in one of the plugin we are sending data directly to the plugin constructor $front->registerPlugin(new My_Plugin_ABC($obj1, $obj2)) Now in the current version we can register a plugin by directly providing the details in the application.ini and I want to stay with this approach(registering using config file). So while testing, I noticed the the plugin constructor is called fairly early in the bootstrapping, so the only option I am left with is using Zend_Registry to store the data, and retrieve it in the hooks. So is it the right way? or are there any other better ways EDIT The plugin was actually managing ACL and Auth, and its receiving custom ACL and AUTH objects. Its using the preDispatch hook. A: Okay so you could consider you ACL and Auth handlers as a some application resources, and be able to add configuration options for them in you application.ini //Create a Zend Application resource plugin for each of them class My_Application_Resource_Acl extends Zend_Application_Resource_Abstract { //notice the fact that a resource last's classname part is uppercase ONLY on the first letter (nobody nor ZF is perfect) public function init(){ // initialize your ACL here // you can get configs set in application.ini with $this->getOptions() // make sure to return the resource, even if you store it in Zend_registry for a more convenient access return $acl; } } class My_Application_Resource_Auth extends Zend_Application_Resource_Abstract { public function init(){ // same rules as for acl resource return $auth; } } // in your application.ini, register you custom resources path pluginpaths.My_Application_Resource = "/path/to/My/Application/Resource/" //and initialize them resources.acl = //this is without options, but still needed to initialze ;resources.acl.myoption = myvalue // this is how you define resource options resources.auth = // same as before // remove you plugin's constructor and get the objects in it's logic instead class My_Plugin_ABC extends Zend_Controller_Plugin_Abstract { public function preDispatch (Zend_Controller_Request_Abstract $request){ //get the objects $bootstrap = Zend_Controller_Front::getInstance()->getParam("bootstrap"); $acl = $bootstrap->getResource('acl'); $auth = $bootstrap->getResource('auth'); // or get them in Zend_Registry if you registered them in it // do your stuff with these objects } } A: Acl is needed so many other places hence storing it in Zend_Registry is cool thing to do and since Zend_Auth is singleton so you can access it $auth = Zend_Auth::getInstance() ; anywhere you like so no need for auth to be stored in registry . Lastly if you have extended Zend_Acl class for your custom acl its better to make it also singleton . Then you can access acl My_Acl::getInstance(); where My_Acl is subclass of Zend_Acl .
{ "language": "en", "url": "https://stackoverflow.com/questions/7534876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Usb Host Problem with Samsung Galaxy 10.1 Tablet I am attempting to leverage the USB host capability on the Samsung Galaxy Tablet. I purchased the attachment dongle from samsung (http://www.samsung.com/us/mobile/galaxy-tab-accessories/EPL-1PL0BEGSTA). When I first connected a usb device via this dongle, I had a high power error from the Galaxy Tablet -- FYI use an externally powered USB hub and you can bipass this. Now that the device itself is acknowledging the existance of a USB peripheral when I attach it, I attempted to use Android's android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; library. I saw that there are two methods for recognizing a USB device, registering a broadcast receiver to listen for the intents via IntentFilter usbIntentFilter = new IntentFilter(); usbIntentFilter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED"); usbIntentFilter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED"); registerReceiver(mUsbReceiver,usbIntentFilter); This is not firing any intents when I attach any devices, strange...ok. So I went on to try the next method: explicitly querying for a device list via the UsbManager -- this was accomplished as follows: HashMap<String, UsbDevice> deviceList = manager.getDeviceList(); int count = deviceList.size(); Iterator<UsbDevice> iterator = deviceList.values().iterator(); if(iterator.hasNext()){ UsbDevice deviceVal = iterator.next(); testTxtView1.setText("set device " + deviceVal); } This would presumably grab the one (only one USB device currently supported per Google Documentation) USB device that is currently connected. To test this I would call the above code upon a button click and display the device results. For some reason, I am getting a device from the device list every time, whether a USB dongle is connected or not. Furthermore, the device is the same every time regardless of the USB dongle (or lack thereof). The output is as follows: device usbDevice[mName=/dev/bus/usb/001/002,mVendorId=1256,mProductId=27033,mClass=0,mSubClass=0,mProtocol=0,mInterfaces=[Landroid.os.Parcelable;@406ff4d8] ^^ the @406ff4d8 value changes every time I query this code (I just put a single instance of it up) I have searched everywhere and have not been able to find any similar problems or solutions that may apply to my situation. I have tried implementing google's USB examples (which is exactly what I have essentially, I ripped theirs) and am running into these problems. I should also mention the makeup of my manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="edu.mit.ll.drm4000" android:versionCode="1" android:versionName="1.0"> <uses-feature android:name="android.hardware.usb.host" /> <uses-sdk android:minSdkVersion="12" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".DRM4000Activity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" /> </intent-filter> <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" /> </activity> </application> and device filter: (I removed criteria on the device filter but have also tried inserting specific information about the device I am looking for...both to no avail.) Any help regarding this problem would be much appreciated! Another update: The device I complained about always being enumerated on the device list device usbDevice[mName=/dev/bus/usb/001/002,mVendorId=1256,mProductId=27033,mClass=0,mSubClass=0,mProtocol=0,mInterfaces=[Landroid.os.Parcelable;@406ff4d8] must be the android side usb port or something...because I started attaching a bunch of different devices to my code and found that (similar to this link: USB_DEVICE_ATTACHED Intent not firing) HID devices, arduino devices..and sadly... my USB device do not appear to fire an intent or get enumerated by the USB hub. I tried with a USB flash drive and it DID enumerate it and worked...however it shows up as the SECOND device on the list, the first being the ever-present usbDevice listed above. Intents do fire with it though. Does anyone know a workaround to making intents fire with HID devices and other USB devices except the select few android seems to do now? A: SOO unfortunately it looks like the Samsung Galaxy Tablet just does not play nicely with the UsbManager and about half of the USB devices in the world. The kernel in Samsung seems to fire intents for storage devices and the like, but not for HID and other random devices (such as arduino, and my usb sensor, and HID devices as well.) It seems to be a bug in samsung kernel. Interestingly, the HID devices WORK on the tablet, but are not enumerated on the UsbManager. I have found several links of the same problem, and it seems like a kernel patch (or the acer tablet) are the only ways around this atm. hopefully samsung will fix in the future. Here is a link to a guy who did a kernel patch if rebuilding the kernel is your thing and you really need to get UsbManager working. I have not tested but plan to eventually, and will leave a comment on my thoughts. http://forum.xda-developers.com/showthread.php?t=1233072 A: I am facing same problem but you can use one method deviceName(), after enumerating device you can store device name in a string using device.getdeviceName() method. you will get exact device name appart from full information of device. A: Samsung has removed the USB API from the Android Kernal A: i think you should define the device you want to recognize in resource/xml/device_filter.xml. you can referring the android api. A: There may be another (nasty) reason why you can't see your HID device. UsbHostManager.beginUsbDeviceAdded() "Called from JNI in monitorUsbHostBus() to report new USB devices". This method calls a private method isBlackListed() which will unconditionally filter out all HUB's, and HID's with subclass BOOT. This may be the reason why you don't see HID devices when you do a getDeviceList() If anyone has a workaround to this, I think that there are a fair amount of users out there who would appreciate see this. A: I have had succesfully attached my Arduino Uno to my samsung galaxy tab 10 P7500. If you have a problem connecting it, It is because the tablet deny permission for the usb devices that doesn't have external power. Try to power your device externally using 5 or 3.3 Volt AC/DC Adaptor, for the first time, if you find your device attached and fire the intent, unplug the power adaptor, and your device would operate without external power, the tablet itself would give the power through USB OTG
{ "language": "en", "url": "https://stackoverflow.com/questions/7534878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: GCC C compile error, void value not ignored as it ought to be I'm having trouble compiling some C code. When I compile, I'l get this error: player.c: In function ‘login’: player.c:54:17: error: void value not ignored as it ought to be This is the code for the error: static bool login(const char *username, const char *password) { sp_error err = sp_session_login(g_sess, username, password, remember_me); printf("Signing in...\n"); if (SP_ERROR_OK != err) { printf("Could not signin\n"); return 0; } return 1; } Any way to bypass this kind of error? Thanks Edit: All sp_ functions are from libspotify A: It usually means you assign the return of a void function to something, which is of course an error. In your case, I guess the sp_session_login function is a void one, hence the error. A: Where is the error line exactly? Without further information, I'm guessing it's here: sp_error err = sp_session_login(g_sess, username, password, remember_me); I guess sp_session_login is returning the void. Try: static bool login(const char *username, const char *password) { sp_session_login(g_sess, username, password, remember_me); printf("Signing in...\n"); return 1; } A: I'm going to guess that sp_session_login is declared as returning void and not sp_error and there is some alternative way of determining whether it succeeded. A: It doesn't look like sp_session_login actually returns anything. In particular, it doesn't return an sp_error, so there's no way this could work. You can't really bypass it. A: You must declare void functions before use them. Try to put them before the main function or before their calls. There's one more action you can do: You can tell the compiler that you will use void functions. For exemplo, there are two ways to make the same thing: #include <stdio.h> void showMsg(msg){ printf("%s", msg); } int main(){ showMsg("Learn c is easy!!!"); return 0; } ...and the other way: #include <stdio.h> void showMsg(msg); //Here, you told the compiller that you will use the void function showMsg. int main(){ showMsg("Learn c is easy!!!"); return 0; } void showMsg(msg){ printf("%s", msg); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: onUpgrade database Android version number not increasing I am trying to update my database in my Android application. When I update the version number, onUpgrade gets called, but the version number doesn't increase, so every time I access the database, onUpgrade gets called. Here is my code: private final static int DB_VERSION = 8; public DataBaseHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); this.myContext = context; } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "in onCreate"); try { copyDataBase(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "in onUpgrade. Old is: " + oldVersion + " New is: " + newVersion); myContext.deleteDatabase(DB_NAME); Log.d(TAG, "the version is " + db.getVersion()); db.setVersion(newVersion); Log.d(TAG, "the version is " + db.getVersion()); onCreate(db); } Anyone know why this is happening? A: Don't try to manually set the version. (This is all taken care of.) Don't try to delete the database. You're in the middle of upgrading it, and it shouldn't really surprise you that manually setting the version of a database you've just deleted doesn't work very well. All you should do in onUpgrade is make the changes needed to the structure of the tables. If you want to do this by deleting the current tables (NOT the database) and then re-creating them, then that's fine. If you need to preserve the data in your tables, have a look at this question for suggestions on how to do it: Upgrade SQLite database from one version to another? A: I ended up adding another database to the assets folder. I know its not the best solution, but it works. When the app is upgraded this time, it just writes the new database - it has a new name - instead of the old one. I check if the old one exists and if it does, I delete it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: @Singleton cache implementation I wonder if my cache implementation is correct and would appreciate any feedback. A resource has some String (Client-Adresses) values assigned. Do i have to synchronize the addEntityRegistration() method? Or is there a better approach for this use-case? thanks in advance, m @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class Cache{ private Map<Object, Set<String>> registeredClients = new ConcurrentHashMap<Object,Set<String>>(); ..... protected void addEntityRegistration(Object key, String fullJid){ Set<String> registered = registeredClients.get(key); if(registered == null){ registered = Collections.newSetFromMap(new ConcurrentHashMap<String,Boolean>()); registeredClients.put(key, registered); } registered.add(fullJid); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is a SqlConnection automatically closed when an application is closed? I am querying the db in a separate thread. If I close the application while the query is being executed, will the SqlConnection automatically close or will it remain open? A: If the process is terminated, all the OS resources, including network connections, will be released. In other words - that's fine. A: If the application ends, the connection gets closed, along with everything else that was opened. A: A SqlConnection is a disposable object. In general it is always good practice to Dispose() of objects that implement IDisposable. I also noticed SqlConnection objects have a Close() method. Should you call that too? Well, I found this article with more info on this: SqlConnection: To Close or To Dispose?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Embed Google Maps on page without overriding iPhone scroll behavior I'm working on optimizing a site for mobile. We have a Location page that includes info about a location and a map of the location via the Google Maps API. (v2 - I know it's deprecated but I haven't justified the time to upgrade, "if it ain't broke..") I want to use a single column layout with basic information followed by the map followed by more information. Now when I use my finger to scroll down the mobile page on an iPhone, once I get to the map, the page scrolling is overridden and the map starts panning. The only way for me to scroll farther down the page is to put my finger above or below the map, assuming such space is available. If I disable map dragging, then when I start scrolling down and get to the map it doesn't pan but the page doesn't scroll either. I would like to treat the map as a static image that I can scroll past, but still allow the zoom buttons and allow the map to be redrawn with directions through a select field I have coded, so a literal static image is not a solution. I found this post that required similar functionality, but it's using v3. I think all I need to do is "add touch events to the map container," but I'm not familiar with that part of javascript, and what I have below does not allow normal scrolling. Do I need to bite the bullet on v3, or do I have a bug on adding touch events that has a simple javascript correction to do what I want? function initialize() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map_canvas")); geocoder = new GClientGeocoder(); } } function showAddress(address, zoom) { //clipped... this part works fine } //These three lines create a map that my finger pans initialize(); showAddress("[clipped.. street, zip code]"); map.addControl(new GSmallZoomControl3D()); //This stops the map pan but still prevents normal page finger scrolling map.disableDragging(); //If done right could this allow normal page finger scrolling?? var dragFlag = false; map.addEventListener("touchstart", function(e){ dragFlag = true; start = (events == "touch") ? e.touches[0].pageY : e.clientY; },true); map.addEventListener("touchend", function(){ dragFlag = false; }, true); map.addEventListener("touchmove",function( if ( !dragFlag ) return; end = (events == "touch") ? e.touches[0].pageY : e.clientY; window.scrollBy( 0,( start - end ) ); }, true); I have also tried replacing map.addEventListener with document.getElementById("map_canvas").addEventListener or document.addEventListener to no avail. A: I solved it by upgrading to v3 and then detecting a basic javascript error in my use of the code from the solution linked above. The key was start = (events == "touch") ? e.touches[0].pageY : e.clientY; The user must have been setting the events variable somewhere outside the presented code, since it looks like the matching assignment is for touch events and the else assignment is for key events. But since I didn't have an events variable it was defaulting to the wrong assignment. I simply changed mine to start = e.touches[0].pageY (and did the same for the touchend event) and now everything works. However, I switched back to v2 to see if it would work with that javascript error corrected, and it did not. So it looks like I did not waste any time upgrading to v3, neither in figuring out this specific solution nor in setting myself up for future compatibility. In conclusion, if you want to embed Google Maps on a mobile page and be able to scroll past it, you need to use API v3, disable dragging, and add touch events. I made a few minor tweaks to my code as well, presented here for any who may benefit in the future: function initialize() { geocoder = new google.maps.Geocoder(); var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } function showAddress(address, zoom) { if (geocoder) { geocoder.geocode( { 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.setOptions( { zoom: zoom }); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } }); } } initialize(); showAddress("'.$geocode_address.'"); map.setOptions( { draggable: false }); var dragFlag = false; var start = 0, end = 0; function thisTouchStart(e) { dragFlag = true; start = e.touches[0].pageY; } function thisTouchEnd() { dragFlag = false; } function thisTouchMove(e) { if ( !dragFlag ) return; end = e.touches[0].pageY; window.scrollBy( 0,( start - end ) ); } document.getElementById("map_canvas").addEventListener("touchstart", thisTouchStart, true); document.getElementById("map_canvas").addEventListener("touchend", thisTouchEnd, true); document.getElementById("map_canvas").addEventListener("touchmove", thisTouchMove, true);
{ "language": "en", "url": "https://stackoverflow.com/questions/7534888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Raise an alert in rails controller without redirect I just want to flash an notice/error if the message is/isn't saved, without any redirect, how can I have no redirect: respond_to do |format| if @message.save format.html { redirect_to request.referer, :notice => 'Message sent!' } #dont want redirect else # error message here end A: Use flash.now: if @message.save flash.now[:notice] = 'Message sent!' else flash.now[:alert] = 'Error while sending message!' end respond_to do |format| format.html { # blahblah render } end A: In rails 5, you can do: format.html { redirect_to request.referer, alert: 'Message sent!' }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Can jQuery check whether input content has changed? Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow? I know about .change() method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup() method but it reacts also on arrow keys and so on. I need just trigger an action every time the text in the input changes, even if it's only one letter change. A: There is a simple solution, which is the HTML5 input event. It's supported in current versions of all major browsers for <input type="text"> elements and there's a simple workaround for IE < 9. See the following answers for more details: * *jQuery keyboard events *Catch only keypresses that change input? Example (except IE < 9: see links above for workaround): $("#your_id").on("input", function() { alert("Change to " + this.value); }); A: function checkChange($this){ var value = $this.val(); var sv=$this.data("stored"); if(value!=sv) $this.trigger("simpleChange"); } $(document).ready(function(){ $(this).data("stored",$(this).val()); $("input").bind("keyup",function(e){ checkChange($(this)); }); $("input").bind("simpleChange",function(e){ alert("the value is chaneged"); }); }); here is the fiddle http://jsfiddle.net/Q9PqT/1/ A: You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested): $(document).ready(function() { $("#fieldId").bind("keyup keydown keypress change blur", function() { if ($(this).val() != jQuery.data(this, "lastvalue") { alert("changed"); } jQuery.data(this, "lastvalue", $(this).val()); }); }); This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields. UPDATE: Added blur to the bind list. A: Yes, compare it to the value it was before it changed. var previousValue = $("#elm").val(); $("#elm").keyup(function(e) { var currentValue = $(this).val(); if(currentValue != previousValue) { previousValue = currentValue; alert("Value changed!"); } }); Another option is to only trigger your changed function on certain keys. Use e.KeyCode to figure out what key was pressed. A: You can also store the initial value in a data attribute and check it against the current value. <input type="text" name="somename" id="id_someid" value="" data-initial="your initial value" /> $("#id_someid").keyup(function() { return $(this).val() == $(this).data().initial; }); Would return true if the initial value has not changed. A: You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed. To do this in a more or less clean way: You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess. An example is in this fiddle: http://jsfiddle.net/zeEwX/ A: I had to use this kind of code for a scanner that pasted stuff into the field $(document).ready(function() { var tId,oldVal; $("#fieldId").focus(function() { oldVal = $("#fieldId").val(); tId=setInterval(function() { var newVal = $("#fieldId").val(); if (oldVal!=newVal) oldVal=newVal; someaction() },100); }); $("#fieldId").blur(function(){ clearInterval(tId)}); }); Not tested... A: I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier. A: Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed: var inp = $('#input'), val = saved = inp.val(), tid = setInterval(function() { val = inp.val(); if ( saved != val ) { console.log('#input has changed'); saved = val; },50); You can also set this up using a jQuery special event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Using strings as incomplete bits of code in Python (please help me clarify the title) This is what I'd like to do: s = "'arg1', 'arg2', foo='bar', baz='qux'" def m(*args, **kwargs): return args, kwargs args, kwargs = m(magic(s)) # args = ['arg1', 'arg2'] # kwargs = {'foo': 'bar', 'baz'='qux'} What is the definition of magic()? Parsing the string myself is a last resort since it's fraught with pitfalls (what if arg1 has a comma in it? what if arg2 has quotes in it? etc). A: With s and m defined as you have them: >>> args, kwargs = eval('m(%s)' % s) >>> args ('arg1', 'arg2') >>> kwargs {'foo': 'bar', 'baz': 'qux'} A: Take a look at eval, but be aware that bad things can happen if you're not careful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cuda context creation and resource association in runtime API applications I want to understand how a cuda context is created and associated with a kernel in cuda runtime API applications? I know it is done under the hood by driver APIs. But I would like to understand the timeline of the creation. For a start I know cudaRegisterFatBinary is the first cuda api call made and it registers a fatbin file with the runtime. It is followed by a handful of cuda function registration APIs which call cuModuleLoad in the driver layer. But then if my Cuda runtime API application invokes cudaMalloc how is the pointer provided to this function associated with the context, which I believe should have been created beforehand. How does one get a handle to this already created context and associate the future runtime API calls with it? Please demystify the internal workings. To quote NVIDIA's documentation on this CUDA Runtime API calls operate on the CUDA Driver API CUcontext which is bound to the current host thread. If there exists no CUDA Driver API CUcontext bound to the current thread at the time of a CUDA Runtime API call which requires a CUcontext then the CUDA Runtime will implicitly create a new CUcontext before executing the call. If the CUDA Runtime creates a CUcontext then the CUcontext will be created using the parameters specified by the CUDA Runtime API functions cudaSetDevice, cudaSetValidDevices, cudaSetDeviceFlags, cudaGLSetGLDevice, cudaD3D9SetDirect3DDevice, cudaD3D10SetDirect3DDevice, and cudaD3D11SetDirect3DDevice. Note that these functions will fail with cudaErrorSetOnActiveProcess if they are called when a CUcontext is bound to the current host thread. The lifetime of a CUcontext is managed by a reference counting mechanism. The reference count of a CUcontext is initially set to 0, and is incremented by cuCtxAttach and decremented by cuCtxDetach. If a CUcontext is created by the CUDA Runtime, then the CUDA runtime will decrement the reference count of that CUcontext in the function cudaThreadExit. If a CUcontext is created by the CUDA Driver API (or is created by a separate instance of the CUDA Runtime API library), then the CUDA Runtime will not increment or decrement the reference count of that CUcontext. All CUDA Runtime API state (e.g, global variables' addresses and values) travels with its underlying CUcontext. In particular, if a CUcontext is moved from one thread to another (using cuCtxPopCurrent and cuCtxPushCurrent) then all CUDA Runtime API state will move to that thread as well. But what I don't understand is how does cuda runtime create the context? what API calls are used for this? Does the nvcc compiler insert some API calls to do this at compile time or is this done entirely at runtime? If the former is true what run time APIs are used for this context management? It the later is true how exactly is it done ? If a context is associated with a host thread, how do we get access to this context? Is it automatically associated with all the variables and pointer references dealt with by the thread? how ultimately is a module loading done in the context? A: The CUDA runtime maintains a global list of modules to load, and adds to that list every time a DLL or .so that uses the CUDA runtime is loaded into the process. But the modules are not actually loaded until a device is created. Context creation and initialization is done "lazily" by the CUDA runtime -- every time you call a function like cudaMemcpy(), it checks to see whether CUDA has been initialized, and if it hasn't, it creates a context (on the device previously specified by cudaSetDevice(), or the default device if cudaSetDevice() was never called) and loads all the modules. The context is associated with that CPU thread from then on, until it's changed by cudaSetDevice(). You can use context/thread management functions from the driver API, such as cuCtxPopCurrent()/cuCtxPushCurrent(), to use the context from a different thread. You can call cudaFree(0); to force this lazy initialization to occur. I'd strongly advise doing so at application initialization time, to avoid race conditions and undefined behavior. Go ahead and enumerate and initialize the devices as early as possible in your app; once that is done, in CUDA 4.0 you can call cudaSetDevice() from any CPU thread and it will select the corresponding context that was created by your initialization code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why is my Facebook app not getting the allow access box? $app_id = "someid"; $canvas_page = "http://mydomain/index.php/fbresponse"; $auth_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page); $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); if (empty($data["user_id"])) { //echo("<script> top.location.href='" . $auth_url . "'</script>"); echo "NO USERID"; } else { echo ("Welcome User: " . $data["user_id"]); } I always get NO USERID. I am at apps.facebook.com/myapp and it is set up for an app iframe. I just never get the allow access box to popup for the user. It just goes straight to no userid. At least one time this worked. Now it always goes to no userid. Thanks. A: I believe that it is probably working, but you have agreed to the permission box before. The access box only pops up once per app. There are some exceptions, for example if you try to request extra permissions or you request permissions that the user decided to skip in the past. That would explain why you said that at least one time this worked. I suggest setting up a test user and seeing if the permissions dialog pops up for that user. You can do this through your app dashboard - by going to "Roles", "Test Users"
{ "language": "en", "url": "https://stackoverflow.com/questions/7534897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting Skype status images from an HTTPS site I have a Rails 3 app where I'm trying to display a page with users and their respective Skype status. This is easy to do if the page is HTTP: just set a background url of an element to the image returned from http://mystatus.skype.com/mediumicon/USERNAME. However, my site is HTTPS, and loading resources via HTTP from an HTTPS causes IE to choke. And Skype evidently doesn't provide an HTTPS version of the status icon. So I'm taking the approach of getting the Skype status server-side (i.e. in the controller) by calling the above URL with Net::HTTP. Then I can write JUST the image bytes back to the page without a problem using send_data(). But I can't figure out how to stream the image bytes back to the view along with all the other page data. Any ideas? A: Here is a code snippet that works. I have done it in sinatra purely to make it work stand alone, but the contents of the get block are the important lines. require 'sinatra' require 'net/http' require 'base64' get '/' do base_image = Net::HTTP.get(URI.parse('http://mystatus.skype.com/mediumicon/Gazler')) "<img src=\"data:image/png;base64,#{Base64.encode64(base_image)}\">" end This takes advantage of base64 encoding the source. You can read more here. Please note that this may not work on older versions of IE. One solution for this would be to base64 encode the image returned as above and to store all the images possible as a status and then do a comparison from the result. Obviously this would be quite slow doing it each time, so you would want to store the base64 of the images locally and then do a lookup on the base64 string. Hope this makes sense. EDIT As a helper method: def skype_status(username) base_image = Net::HTTP.get(URI.parse("http://mystatus.skype.com/mediumicon/#{username}")) content_tag("img", :src =>"data:image/png;base64,#{Base64.encode64(base_image)}") end
{ "language": "en", "url": "https://stackoverflow.com/questions/7534901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make PDF reports in Perl? All the PDF libraries for Perl seem a bit barbaric -- stuck in the 1980's. You have to specify PostScript points to do layout. Java has JasperReports, Ruby has Prawn, and Python has ReportLab. Is there a non-extinct library/module that will let me make a nice looking PDF in less than a week of coding? (I'm a little frustrated by PDF::API2, PDF::Table, etc.) I don't want to generate HTML and convert it. Perl is ideal for reporting, but the main report file format is not available in a usable way. What libraries do people use? I need: * *tables *charts (Images) *color *formatting (ideally automatic, not pixel by pixel) *headers / footers I'm slightly open to wrapping external (non-Perl) open source tools, if absolutely needed. But not really interested in a major Java server approach. For the bounty, I want a pure Perl approach, since I want to run this on a server that I can't add more than modules to. If you have a public example that works well, please point me to it. A: If LaTeX is too big, perhaps one could use Inline::Python to wrap ReportLab, that everyone seems to like so much (I haven't used it and am not too proficient at Python). Edit 3: Here is Edit 2, except split into a modular style, if people like it (and if it is an kind of robust) perhaps I can publish to CPAN. For now place the .pm file in a file structure like Inline/Python/ReportLab.pm somewhere in your @INC (the script's own base directory is usually in @INC). # Inline/Python/ReportLab.pm package Inline::Python::ReportLab; use strict; use warnings; use Carp; use Inline::Python qw/py_eval/; our @ISA = 'Inline::Python::Object'; sub import { py_eval('from reportlab.pdfgen.canvas import Canvas'); } sub new { my $class = shift; my $filename = shift || croak "Must specify file name to contructor"; return bless(Inline::Python::Object->new('__main__', 'Canvas', $filename), $class); } 1; Then a script could be something like: #!/usr/bin/env perl use strict; use warnings; use Inline::Python::ReportLab; my $c = Inline::Python::ReportLab->new('hello.pdf'); $c->drawString(100,100,"Hello World"); $c->showPage(); $c->save(); Edit 2: While Edit 1 is still of interest, it seems (tell me if I am incorrect!) that I have figured out how to create an instance of 'Canvas' and expose its methods directly: #!/usr/bin/env perl use strict; use warnings; use Inline::Python qw/py_eval/; py_eval('from reportlab.pdfgen.canvas import Canvas'); my $c = Inline::Python::Object->new('__main__', 'Canvas', 'hello.pdf'); $c->drawString(100,100,"Hello World"); $c->showPage(); $c->save(); Edit 2/3: This portion is left as an example of a more manual interface. I think Edits 2/3 give a better interface which leaves the heavy lifting to the original Python class without (too much) wrapping. Edit 1: I have now exposed some of the functionality by manually hacking in the methods. This means that for every method one wants to use, a wrapper method must be added. While this is already a feasible solution, I wonder if there isn't some easier way to expose the entire python 'canvas' class, but for now this is where I am: #!/usr/bin/env perl use strict; use warnings; use Inline Python => <<END_PYTHON; from reportlab.pdfgen import canvas class Canvas: def __init__(self,filename): self.canvas = canvas.Canvas(filename) def drawString(self,x,y,text): self.canvas.drawString(x,y,text) def save(self): self.canvas.showPage() self.canvas.save() END_PYTHON my $c = Canvas->new('hello.pdf'); $c->drawString(100,100,"Hello World"); $c->save(); A: Using Perl, generate LaTeX, perhaps using Template::Toolkit, then call the compiler, either TeXLive or MikTeX or whatever distribution you need for your OS. There is an extension called Template::LaTeX, though you probably don't need it, which manages the build process. LaTeX has support for all the things you need. Tables get a little interesting but there are some modern table packages which ease things (I think that its called ltxtable). For charts (do you mean diagrams) there is a sub language called TikZ which is spectacularly powerful. This really is a very easy workflow, especially if you want the results to be similar every time (i.e. can use a template). In fact it really is not unlike creating HTML from a template and serving it to a browser. Another benefit of this is that the template (and prepared source) will be portable should you need to build a report in another language. A: After much thought and experimentation, I ended up writing a lot of code to wrap PDF::API2. Unfortunately this was an internal project within a company so not going to be released open source, but frankly I'd recommend using a different language (Python / Ruby), perhaps passing the data through with JSON or something. My end result is efficient, but it required a lot of coding. There is a refactoring of PDF::API2 underway on CPAN but it seems to be stalled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I fix this Ruby Yes/No-Style Loop? I've got this method I wrote to ask n-times for user input using a while loop inside. The idea is really simple and common, repeat the while loop if the condition is true, The problem is that it doesn't work... def play_again? flag = true while flag print "Would you like to play again? [y/n]: " response = gets.chomp case response when 'y' Game.play when 'n' flag = false end end flag end play_again? As it stands it will only successfully repeat once and then exit, instead of keep on looping, Could you guys please tell me what is wrong? (Sorry if it's such a n00b question, I'm a ruby n00b after all) Thank you. A: Possible problems: * *check Game.play *Capital/no-capital in the answer? -> String#upcase or String#downcase *hidden spaces (before/after the answer) -> String#strip instead String#chomp You may also use regular expressions (example N) or with a list of answers (yes) to check the answer: def play_again? while true print "Would you like to play again? [y/n]: " case gets.strip when 'Y', 'y', 'j', 'J', 'yes' #j for Germans (Ja) puts 'I play' # Game.play when /\A[nN]o?\Z/ #n or no break end end end play_again?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Aligning content within a table with CSS I have a table in my HTML that is defined like the following <table> <tr> <td><img src='corner1.png' /></td> <td>First Name <a href='#'>edit</a></td> <td><img src='corner2.png' /></td> </tr> </table> I want the edit link to be right-aligned within the cell. But I want "First Name" to be left-aligned. Currently, everything is left-aligned. How can I make the link right-aligned? A: <td><a href='#' class="floatRight">edit</a> First Name</td> Entry in CSS file .floatRight {float:right;} Moved edit before First Name else some browsers will show it in new line and not in-line with First Name. A: Set a float on the <a> element: table tr td a { float: right } This will push the <a> to the right of the cell. The selector is a bit too specific - at minimum it could be table a. A: You can try the following CSS: td a { float: right; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple increment of a local variable in views in ASP.NET MVC3 (Razor) Well, this is just embarrassing. I can't even figure out a simple increment in one of my views in ASP.NET MVC3 (Razor). I have done searches and it appears that the documentation for Razor is pretty sparse. Here is what I have tried and failed miserably: @{ var counter = 1; foreach (var item in Model.Stuff) { ... some code ... @{counter = counter + 1;} } } I have also tried @{counter++;} just for kicks and to no avail =) I would appreciate it if someone could enlighten me. Thanks! A: @{ int counter = 1; foreach (var item in Model.Stuff) { ... some code ... counter = counter + 1; } } Explanation: @{ // csharp code block // everything in here is code, don't have to use @ int counter = 1; } @foreach(var item in collection){ <div> - **EDIT** - html tag is necessary for razor to stop parsing c# razor automaticaly recognize this as html <br/> this is rendered for each element in collection <br/> value of property: @item.Property <br/> value of counter: @counter++ </div> } this is outside foreach A: See Following code for increment of a local variable in views in ASP.NET its work fine for me try it. var i = 0; @foreach (var data in Model) { i++; <th scope="row"> @i </th>.... }... A: I didn't find the answer here was very useful in c# - so here's a working example for anyone coming to this page looking for the c# example: @{ int counter = 0; } @foreach(Object obj in OtherObject) { // do stuff <p>hello world</p> counter++; } Simply, as we are already in the @foreach, we don't need to put the increment inside any @{ } values. A: Another clean approach would be: <div> @{int counter = 1; foreach (var item in Model) { <label>@counter</label> &nbsp; @Html.ActionLink(item.title, "View", new { id = item.id }) counter++; } } </div> A: If all you need to do is display the numbering, an even cleaner solution is increment-and-return in one go: @{ var counter = 0; } <section> @foreach(var hat in Ring){ <p> Hat no. @(++counter) </p> } </section>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: Google+ API get people "me" After struggling to authenticate on the Google+ API, I finally succeed to retrieve my info with https://www.googleapis.com/plus/v1/people/{MyUserId}?key={ApiKey} However, despite I did obtain an access token with the scope https://www.googleapis.com/auth/plus.me I cannot request "me" : https://www.googleapis.com/plus/v1/people/me?key={ApiKey} I end up with an 401 unauthorised request... It's late and I don't get what I'm missing. Here is my code: string apiUrl = "https://www.googleapis.com/plus/v1/people/me?key={my api key"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl); request.Method = HttpMethod.GET.ToString(); try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { => 401 error Thank you for your help! A: This doesn't directly answer your question, but have you tried the Google APIs Client Library for .NET? See: http://code.google.com/p/google-api-dotnet-client/ http://code.google.com/p/google-api-dotnet-client/wiki/OAuth2 http://code.google.com/p/google-api-dotnet-client/wiki/APIs#Google+_API The 401 error most likely means your access token has expired, and needs to be refreshed with the refresh token. A: I'm 3 years late, but I found this post while looking for a solution to a nearly identical problem. I'm trying to avoid using Google's API, however, so I thought I'd post my own solution in case anyone ever wants to see a way to do this without the Google API. I'm using RestSharp to handle HTTP requests, but that isn't necessary. //craft the request string requestUrl = "https://www.googleapis.com/plus/v1/people/me?access_token=" + AccessToken; RestClient rc = new RestClient(); RestRequest request = new RestRequest(requestUrl, Method.GET); request.AddHeader("Content-Type", "application/json"); request.AddHeader("x-li-format", "json"); request.RequestFormat = DataFormat.Json; //send the request, and check the response. RestResponse restResponse = (RestResponse)rc.Execute(request); if (!restResponse.ResponseStatus.Equals(ResponseStatus.Completed)) { return null; } The primary difference from the original implementation in the question is not that I'm using RestSharp - that's insignificant. The primary difference is that I passed an access_token in the query string instead of a key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I express this query in sqlalchemy? I'm using this as an example to help me learn sqlalchemy. Here is the mySQL: select f.type, f.variety, f.price from ( select type, min(price) as minprice from fruits group by type ) as x inner join fruits as f on f.type = x.type and f.price = x.minprice; Here is what I have so far: s = Session() sq = s.query(func.min(fruit.price)).group_by(fruit.type).subquery() ans = s.query(fruit).join(sq, fruit.price==sq.c.price).all() but it clearly does not work. Am I even close? I've been pouring over these docs. price is a PK if that helps.. maybe i need an alias or something. Any help or direction is appreciated. A: I can't be sure of this because I don't know what exception you're getting. Since you're trying to get SQLAlchemy to execute a similar query to the one you posted, in which you have a select statement in your from clause, you'll need to call mapper on the result of a sqlalchemy.select similar to the linked example. This mapped class will be your x in the query you're trying to imitate. Then you can do session.query(fruits).join((x, ...)).filter(... to get the final result. The subquery method of a query object, by contrast, is for situations where you desire a select statement in the where clause, as in where column in (select ...). Use subquery to obtain what will become the inner select in the final generated query. You can then create a separate (outer) query and join against the result of the subquery call. To get SQLAlchemy to use a query similar to your example, it does not appear you will need to use this technique. A: SOLUTION: Following should do it: Version when fruit is a Table instance: q = (select([fruit.c.type, func.min(fruit.c.price).label("min_price")]). group_by(fruit.c.type)).alias("subq") s = select([fruit], and_(fruit.c.type == q.c.type, fruit.c.price == q.c.min_price) ) res = session.execute(s) Version when fruit is a Model type: q = (select([fruit.type, func.min(fruit.price).label("min_price")]). group_by(fruit.type)).alias("subq") s = (session.query(fruit). join(q, and_(fruit.type==q.c.type, fruit.price == q.c.min_price)) ) res = s.all() Side note: Float column as a PK does not sound like a great idea... and really, cannot two different fruits have the same price (which will violate uniqueness)? A: This also works and is the syntax I am most familiar with. s = Session() sq = s.query(func.min(fruit.price).label('min_price').\ group_by(fruit.type).subquery() ans = s.query(fruit).join(sq, fruit.price==sq.c.min_price).all()
{ "language": "en", "url": "https://stackoverflow.com/questions/7534937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why can't I see my HTML content in my App? I'm new to developing for Facebook. I'm trying to create a "Welcome" tab, and I'm unable to see content after adding the App to my Page. I'm a little confused on Canvas Page URL and Page Tab URL. Should they be the same URL minus the HTML filename? A: The canvas page url is the folder where the page is stored: ex. http://www.myurl.com/facebooktabs/ the Page tab url is the exact url of the content: ex. http://www.myurl.com/facebooktabs/index.php make sure you give the secure page tab url an address as well: ex. https://www.myurl.com/facebooktabs/index.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7534941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: detect carriage return in UITextField in iOS How would I detect a carriage return for a UITextView in iOS? I am currently just watching this field for a period of time but want to improve on this a bit: - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSLog(@"text editing started: %i", scanning); if (!scanning) { timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkText:) userInfo:nil repeats:NO]; scanning = YES; [self.scannedItems scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES]; } return YES; } So I would want to call a function after the return is found, currently I call checkText after 1 second. A: Start with this: - (BOOL) textFieldShouldReturn:(UITextField *)textField I presume its also possible to look at the character value in the code you posted. Return was int value of 13 the last time I needed to look at it directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are public properties in an ASP.NET code behind supposed to persist between page loads? I am trying to capture the HTTP_REFERER upon page_load event of an ASP.NET page, and persist it between postbacks until I need it later. The way I trying to do this isn't working: public partial class About : System.Web.UI.Page { public string ReferringPage { get; set; } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ReferringPage = Request.ServerVariables["HTTP_REFERER"]; } } protected void ImageButton1_Click( object sender, ImageClickEventArgs e) { Response.Redirect(ReferringPage); } } I've verified that the referring page's url goes into the property, but when I click the image button, ReferringPage is null! I had thought that the property's value was being stored in the ViewState, so that it would be available upon postback, but this turns out not to be the case. Or am I simply doing it wrong? A: Every request creates a new instance of the page class, so no, nothing is meant to persist. A: No, only [most] control properties are persisted on postbacks, so you could save the referring page on a hidden field, or in the ViewState property of your page I use this snippet a lot: private string ReferringPage { get { return (string)ViewState["ReferringPage "]; } set { ViewState["ReferringPage"] = value; } } This will make your ReferringPage work as expected. But be careful, like any hard drug, abuse of ViewState is considered harmful. http://anthonychu.ca/post/aspnet-viewstate-abuse If you need the ReferringPage variable to persist not only on postbacks, but even when the user navigates to other pages, you just change ViewState to Session, which lets you persist values across navigation from the same (user) session And last, you may want to take a look at server transfer mechanism in webfoms (with added bonus of links to data persistence methods) http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7534946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Groovy Script to insert database entries with unique key I am writing a groovy script to read data from an CSV file and then pull inserts into database. I have gotten everything to work EXCEPT for generating a unique primary key or autoincrement for each insert. The unique key is campusID. Here is the script. def sql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb", "xxxx", "xxxx", "com.mysql.jdbc.Driver") def campus = sql.dataSet("CAMPUS") new File("C:\\test.csv").splitEachLine(",") {fields -> campus.add( campusId: // Need to generate a unique key here campusShortName: fields[1], campusUrl: fields[2]) Thanks. A: The unique key is usually handled by the database, not by the code. Some databases (like MySQL) accept setting the autogenerated field to null, others require that the column isn't provided at all. So, either remove the campusId from your query, or set it to null, and make sure the column is set to be an AUTO_INCREMENT column. If you need the ID that was inserted (for example, to use as a foreign key), you may be better off using the normal SQL methods, and check the return value of the executeInsert method
{ "language": "en", "url": "https://stackoverflow.com/questions/7534949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery Plugin - Passing options as object I built a custom Message Dialog Box JQuery plugin that works great. However, I am trying to allow users to set the options from input text fields (i.e. background color, font size, etc). I then create a object with all the options that are not empty, and pass to my plugin to $.extend with the default options. Cant get it to work! Any ideas? messageBox_settings is the class for the input fields to be used as options. The field 'id' = option name. I am looping through each field and checking for any that are not empty. The plugin works fine when manually defining individual options in the plugin function call. $('button#show_messagebox').click(function(){ var optionLabel = ''; var optionValue = ''; var optionsArr = {}; $('.messageBox_settings').each(function(){ if($(this).val()!=""){ optionLabel = $(this).attr('id'); optionValue = $(this).val(); $.extend(optionsArr,{optionLabel:optionValue}); } }); //optionsArr = {optionLabel:optionValue}; Just a test when passing one option $('.messageBox_test').messageBox(optionsArr); A: optionsArr is a javascript object, which can be used like an associative array indexed by the object's property name. var options = {}; $('.messageBox_settings').each(function(){ if($(this).val()!=""){ optionLabel = $(this).attr('id'); optionValue = $(this).val(); options[optionLabel] = optionValue; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7534950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - XML - Treat inner xml from a certain element as string I have the following XML: <Plan> <Error>0</Error> <Description>1</Description> <Document> <ObjectID>06098INF1761320</ObjectID> <ced>109340336</ced> <abstract>DAVID STEVENSON</abstract> <ced_a /> <NAM_REC /> <ced_ap2 /> </Document> </Plan> I deserialize it with this: [XmlRoot("Plan")] public class EPlan { [XmlElement("Error")] public string Error { get; set; } [XmlElement("Description")] public string Description { get; set; } [XmlElement("Document")] public List<EDocument> Documents { get; set; } } public class EDocument { [XmlText] public string Document { get; set; } } The issue is that I want the element "Document" to contain its inner XML as a single string, I mean, the object should have these values: obj.Error = "0"; obj.Description = "1"; obj.Documents[0].Document = "<ObjectID>06098INF1761320</ObjectID><ced>109340336</ced><abstract>DAVID STEVENSON</abstract><ced_a /><NAM_REC /><ced_ap2 />"; But the way I mentioned before keeps retrieving a NULL "Document" property. Is it possible to achieve the behaviour I want? Any help would be appreciated. A: XmlText expects a text node, but what you have are actually element nodes. I don't know if there's a direct way to do that, but you can have a XmlAnyElement node to collect the result of the deserialization, and afterwards you merge them in a single string if that's what you need, as shown in the example below. [XmlRoot("Plan")] public class EPlan { [XmlElement("Error")] public string Error { get; set; } [XmlElement("Description")] public string Description { get; set; } [XmlElement("Document")] public List<EDocument> Documents { get; set; } } [XmlType] public class EDocument { private string document; [XmlAnyElement] [EditorBrowsable(EditorBrowsableState.Never)] public XmlElement[] DocumentNodes { get; set; } [XmlIgnore] public string Document { get { if (this.document == null) { StringBuilder sb = new StringBuilder(); foreach (var node in this.DocumentNodes) { sb.Append(node.OuterXml); } this.document = sb.ToString(); } return this.document; } } } static void Test() { string xml = @"<Plan> <Error>0</Error> <Description>1</Description> <Document> <ObjectID>06098INF1761320</ObjectID> <ced>109340336</ced> <abstract>DAVID STEVENSON</abstract> <ced_a /> <NAM_REC /> <ced_ap2 /> </Document> <Document> <ObjectID>id2</ObjectID> <ced>ced2</ced> <abstract>abstract2</abstract> <ced_a /> <NAM_REC /> <ced_ap2 /> </Document> </Plan>"; XmlSerializer xs = new XmlSerializer(typeof(EPlan)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)); EPlan obj = xs.Deserialize(ms) as EPlan; Console.WriteLine(obj.Documents[0].Document); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }