text
stringlengths
8
267k
meta
dict
Q: Why is os.path.expanduser misbehaving when the home directory has special characters? Currently, my user directory is located in "C:\Users\João", and I'm running the Python 2.7's 64-bit build under Windows 7. Normally, the Python interpreter runs with 'ascii' as the default encoding. However, for some reason, when Eclipse runs it, the default encoding is 'utf-8'. Now, in the regular Python console, the following happens: >>> sys.getdefaultencoding() 'ascii' >>> os.path.expanduser('~/filename') 'C:\\Users\\Jo\xe3o/filename' >>> x = open(_, 'w') >>> x.close() >>> I'll note that '\xe3' is the code for 'ã' in both Latin-1 and Windows-1252, and that everything goes fine. However, in Eclipse, >>> sys.getdefaultencoding() 'utf-8' >>> os.path.expanduser('~/filename') 'C:\\Users\\Jo\xc6o/filename' >>> x = open(_, 'w') Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 13] Permission denied: 'C:\\Users\\Jo\xc6o/filename' Which is confusing, since '\xc6' is the character code for 'Æ', and on top of that, isn't valid UTF-8. If you're wondering about "Permission denied", instead of "No such file or directory", a couple of programs have also written stuff to 'C:\Users\JoÆo', and I also have no idea why. So what is the cause of, and the solution for this? Is it even programatic or do you think it's some system setting that might be wrong? TL; DR: Home directory is correctly reported as 'C:\Users\João' in the standard Python interpreter, and as 'C:\Users\JoÆo' when the interpreter is running in Eclipse. Why? A: Try changing Eclipse's default encoding. File Menu: Windows --> Preferences; Tree Bar: General -> Workspace; Change "Text file encoding" from Cp1252 to ISO-8859-1. You can also change it for a specific debug configuration if you open up "Debug Configurations", go to the "Common" tab, change "Encoding". Edit: Very weird. Performing a glob on "./J*" in a directory with a "João" directory works fine for me in Eclipse with UTF-8 and Cp1252 (the default) in 64-bit Python 2.7.2, Windows 7. UTF-8: ['.\Jo\xe3o'] Cp1252: ['.\Jo\xe3o']
{ "language": "en", "url": "https://stackoverflow.com/questions/7601300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to design a web application that developers can use to retrieve the crashdump/Logs from customer environment Hi I am c++ developer and my knowledge to web technologies is minimum. Right now i am trying to design a web application which the development team can use to connect to specific customer and collect any crash dumps or log files. With my research i realized it could be the following way. 1) develop an agent with build it http server and listing for request in specific port and install it in a machine with internet access and public ip address in all customer sites environment. 2) The agent is capable of collecting the required information from the customer environment based on the request it receives. 3) Develop an application with browser interface, and installed it centrally on the development data center. This application must have capability to connect to a specific customer environment and send http request over the internet to listening agent in that customer site and collect crash dump or logs or some statistics on the customer environment based on the request. I am not sure this is the right way of doing, but I am sure there is a better way to do it. Any help or pointers on what is the right approach and what kind of infrastructure is require to implement this kind of a service is highly appreciated. Regards, Prakash R A: The approach looks serviceable, except you don't need to develop any applications to do that, as existing applications fit the bill nicely: * *Use a web server of your choice. Apache is well known and open source (free). You might wish to configure security. *Assuming you're running under unix, you could use a link to include the log directory in the file system the apache serves. *Use your browser. (You obviously have one already). If you have many sites, you could use bookmarks, on a link list in your intranet, or ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7601301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TFS Build Error While Invoking custom build file via TFS Build definition I use TFS 2010, VS 2010. I wrote a custom msbuild proj file which I use locally to build my solution. I use MSBUILD.exe TFSBuild.proj and it does everything in my local machine. (I have a taregt called 'DoMyBuild' which kicks off the build and does everything.) I have used this in the DefaultTargets attribute as below: <Project DefaultTargets="DoMyBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> I am trying hard to configure this to use my build server with a build definition. In the build definition, under Process - I configured 'Upgrade Template' and in the build process paramters, have given the path to this TFSBuild.Proj file. Ideally. TFS should start 'DoMyBuild' target as I read. But it gives a error looking for 'EndToEndIteration' not defined. So, I believe it is still doing a DesktopBuild which I dont want. I want to use my custom target to kick start. Is this possible ? Any help is very much appreciated. Thanks, Mani A: You problem is discussed here. Make sure you have at least an EndToEndIteration target defined in your MSBuild project. <Target Name="EndToEndIteration" Condition=" '$(IsDesktopBuild)'!='true' " DependsOnTargets="$(EndToEndIterationDependsOn)" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7601303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to turn off web camera in IE using action script I am using flash professional for take photo from webcam. My requirement is that I want to start camera and after 2 sec it will take photo and turn off the camera. I did that and its working good in all browser except IE. Actually, I am display:none that flash object after photo take, and it will automatically turn off camera in browser except IE. If I display:none camera flash object, it will not turn off my webcam. So, can you please help me in how to turn off web camera in IE. Thank you. A: I figured out. I called action script function from java script. In action script function I just pass null to attachCamera function like this way - "video.attachCamera(null);" null will turn off camera. and its working in all browser. A: I would not expect that to work well in all browsers (as you noticed). It would be better to send a function call to the flash file telling it to do whatever is needed to turn off the camera (deteach the camera from the screen I guess), using ExternalInterface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert CGI REMOTE_ADDR to network byte order for use with MySql INET_NTOA I'm trying to log requests for a script and I want to store the client's IP Address in an int(4) column, using INET_NTOA() to return it in a readable function. However, in my Perl CGI script, $ENV{REMOTE_ADDR} contains an IP in host byte order which, when entered into the database with the INET_ATON() function, is converted incorrectly so when I pull it back out, I have a completely different address. #!usr/bin/perl -wT use strict; use CGI; use DBI; my $dbh = DBI->connect("DBI:mysql:$db:$server", "$user", "$password"); my $addr = $ENV{REMOTE_ADDR}; my $insert = $dbh->prepare(qq[insert into access_log (ipaddress) values (INET_ATON('$addr'))]); $insert->execute or die "sql insert error"; my $retrieve = $dbh->prepare(qq[select INET_NTOA(ipaddress) as IP_Address from access_log]); $retrieve->execute or die "sql select error"; my $newIP = $retrieve->fetchrow_array; Ideally, this script should return the value of $addr but instead I get something completely different. How can I format $addr before putting it into the database? Thanks for your help. A: I've discovered that no change to the $ENV{REMOTE_ADDR} is needed. By using a an int(4) unsigned for my ip_address column, inet_aton() and inet_ntoa() work correctly. With a signed integer, "values corresponding to IP addresses for which the first octet is greater than 127 cannot be stored correctly" so the data gets distorted in the insert stage. http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-ntoa A: Odd. The ENV var should be the normal dotted-quad notation, not a raw integer. Shouldn't it be $ENV{'REMOTE_ADDR'} anyways? Note that your INT column should be unsigned. inet_ntoa() does not like negative numbers, and half the IP address space will show up as negative if you store it in signed int fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you track when an android application has been terminated? Looked at android documentation and it appears that we don't have the ability to know when an app shuts down. Whether it was explicitly by the user or automatically by the operating system. Below is the onTerminate() documentation which is only available in the emulated scenario. public void onTerminate() Since: API Level 1 This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so. Does anyone have any other approaches to report back when the user closes the application? We need to know from a pilot/usability standpoint if we need to incorporate additional functionality into our future production app. A: Not sure whether this is going to help you... In my app, I'm using Activity.onDestroy() to do the cleanup that I need. I have a couple of activities - and have onDestroy() in each of them. This is the closest I got to doing what I needed - and it actually works quite well. A: Looked at android documentation and it appears that we don't have the ability to know when an app shuts down. Whether it was explicitly by the user or automatically by the operating system. Users do not close applications on Android. Does anyone have any other approaches to report back when the user closes the application. Users do not close applications on Android. Android, in this respect, behaves much like a Web browser. Users do not close Web applications in Web browsers. They might close the browser. They might close a tab. They might press the home button and navigate to a different site/app. They might choose a bookmark and navigate to a different site/app. They might drag a document into the browser and view it. They might double-click on a desktop icon and view it. And they might click some "logout" link in the currently-viewed Web site/app. Any of these cause the user to leave whatever Web site/app they are in, but none of them would be construed as "closing" the Web site/app in the same manner that clicking the close button on a desktop OS window might be construed as "closing" the desktop app. As @Aleks G notes, there are various lifecycle methods you can override to find out what the user is doing with respect to an activity. onStop() indicates something else took over foreground input and your current activity is no longer visible. onUserLeaveHint() indicates that the user pressed HOME. And so on. But those are at the activity level, not the application level. A: Make a BaseActivity extending Activity in your Application and extends this BaseActivity instead of Activity. In this BaseActivity override the onDestroy() method. Like @Override protected void onDestroy() { super.onDestroy(); //Write the code that you want to do if the application terminates }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Vim Regex Duplicate Lines Grouping I have a log file like this: 12 adsflljl 12 hgfahld 12 ash;al 13 a;jfda 13 asldfj 15 ;aljdf 16 a;dlfj 19 adads 19 adfasf 20 aaaadsf And I would like to "group" them like one of these two: 12 adsfllj, 12 hgfahld, 12 ash;al 13 a;jfda, 13 asldfj 15 ;aljdf 16 a;dlfj 19 adads, 19 adfasf 20 aaaadsf Or 12 adsfllj, hgfahld, ash;al 13 a;jfda, asldfj 15 ;aljdf 16 a;dlfj 19 adads, adfasf 20 aaaadsf And I am totally stuck. And if vim doesn't do it, I have sed and awk and bash too. I just don't really want to write a bash script, I want to increase my regex-fu A: In Vim you can use: :%s/\(\(\d\+\) .*\)\n\2/\1, \2/g which means: if a group of numbers is matched after a new line, remove the newline and place a comma instead. If you are not familiar with them, \1 and \2 are backreferences. Unfortunately this only merges two occurrences at a time, so you'll have to run it multiple times before achieving your goal. EDIT: one way to do it in a single go would be to cycle and exploit the fact that the as soon as the file doesn't match anymore an error is issued. The error is a bit annoying though, but I couldn't do better with a one-liner: :while 1 | :%s/\(\(\d\+\) .*\)\n\2/\1, \2/g | :endwhile A: I'd just use awk: awk ' { sep = val[$1] ? ", " : "" val[$1] = val[$1] sep $2 } END {for (v in val) print v, val[v]} ' log.file | sort > new.file A: In Vim, I would use the command :g/^\d\+/y|if+@"==getline(line('.')-1)|s//,/|-j! if it is guaranteed that the first column always contains digital ids. Otherwise, I would modify that if-condition as follows. :g/^\S\+/y|if matchstr(@",@/)==matchstr(getline(line('.')-1),@/)|s//,/|-j! A: Another way to do this, with a macro this time (I advise you to use another solution, this one just shows that there are plenty of ways to do it): gg:%s/$/,enterqa0V?ctrl-rctrl-w\>\&^enterJjq100@a:%s/.$//return explanation: * *gg => go to start of file *:%s/$/, => append comma to every line *qa => start recording a macro into register a *0V => go to first column, and start linewise selection *? => lookup backwards (you must have set wrapscan) * *ctrl-r ctrl-w inserts word under cursor. *\> ensures end of word *\&^ ensures pattern matches at start of line. You cannot put ^ at the beginning of the pattern, because if incsearch is set, then as soon as you have typed ^ then ctrl-r ctrl-w will print the word under cursor, which will have moved to the previous line. *J will join all lines from the visual selection with spaces. *j will go to next line *q will stop recording macro *100@a will play macro 100 times. *:%s/.$// will remove trailing commas. A: I do not think that this is a good idea to use regular expressions here. Same idea that you can find in @glenn jackman's solution written in vimscript will be the following: function JoinLog() let d={} g/\v^\S+\s/let [ds, k, t; dl]=matchlist(getline('.'), '\v^(\S+)\s+(.*)') | \let d[k]=get(d, k, [])+[t] %delete _ call setline(1, map(sort(keys(d)), 'v:val." ".join(d[v:val], ", ")')) endfunction You can keep the order instead of sorting: function JoinLog() let d={} let ordered=[] g/\v^\S+\s/let [ds, k, t; dl]=matchlist(getline('.'), '\v^(\S+)\s+(.*)') | \if has_key(d, k) | let d[k]+=[t] | \else | let ordered+=[k] | let d[k]=[t] | \endif %delete _ call setline(1, map(copy(ordered), 'v:val." ".join(d[v:val], ", ")')) endfunction
{ "language": "en", "url": "https://stackoverflow.com/questions/7601324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I change a button from going to the next page to doing some code? I am new to perl/html. This is from a perl file. This button is in there right now: <button id = "button1" name = "submitButton" type="submit"> <span class="right">Submit</span> </button> I don't see any piece of code where submitButton or button1 is given any logic so I don't understand why this jumps to the next page. Can someone explain? EDIT: This seems to be the only javascript in the whole file... <script type="text/javascript"> % $m->comp('../js/share.js'); </script> I looked at the file, and it doesn't seem to do any redirecting or anything. A: Often event handlers are hooked up at run-time using JavaScript. If there is an included script, look in the code for "button1" and see which function is hooking it up. Also since this is a SUBMIT button, if it is wrapped in a form, no code needs to hook this up. It will post to whatever is defined in the form's ACTION property. A: Maybe there is some JS/Jquery or another js-framework included to the page? A: Since this is a submit button, it does the logic defined by the Form that surrounds it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the line width of error bar caps How can the line width of the error bar caps in Matplotlib be changed? I tried the following code: (_, caplines, _) = matplotlib.pyplot.errorbar( data['distance'], data['energy'], yerr=data['energy sigma'], capsize=10, elinewidth=3) for capline in caplines: capline.set_linewidth(10) capline.set_color('red') pp.draw() Unfortunately, this updates the color of the caps, but does not update the line width of the caps! The resulting effect is similar to the "fat error bar lines / thin caps" in the following image: It would be nice to have "fat" bar caps, in the case; how can this be done, in Matplotlib? Drawing the bar caps "manually", one by one with plot() would work, but a simpler alternative would be best. A: EOL, you were very close.., distance = [1,3,7,9] energy = [10,20,30,40] sigma = [1,3,2,5] (_, caps, _) = plt.errorbar(distance, energy, sigma, capsize=20, elinewidth=3) for cap in caps: cap.set_color('red') cap.set_markeredgewidth(10) plt.show set_markeredgewidth sets the width of the cap lines. Matplotlib objects have so many attributes that often it is difficult to remember the right ones for a given object. IPython is a very useful tool for introspecting matplotlib. I used it to analyze the properties of the 2Dlines correponding to the error cap lines and I found that and other marker properties. Cheers A: This is based on @joaquin's answer, but a little more concise (if you just want plain error caps with no special styling): distance = [1,3,7,9] energy = [10,20,30,40] sigma = [1,3,2,5] plt.errorbar(distance, energy, sigma, capsize=5, elinewidth=2, markeredgewidth=2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7601334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Debugging my downloader I have a downloader application in C# using .NET 2.0. For the most people it works well, but I saw that I have big error log from other people. The 99% of the exceptions are: * *Unable to connect to remote server *The remote name could not be resolved *Operation timed out Can this be from a short timeout of my downloader or from a slower internet connection? Or it can be some internal thread error in my downloader (it's multipart/multithread). A: It sounds like some of your users * *are behind a firewall or proxy, which is supported by their web browser but not by your downloader or *simply have a terribly bad Internet connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get photos with graph api I've read a lot of tutorials/articles/questions here about this, as well as trying to find something useful in the fb documentation. So far I've made no progress at all myself so any input would be greatly appreciated, I'm simply trying to access a list of my photos but all I get is an empty array. I know I've added more req_perms than I need probably, I just copied the ones from a "working tutorial" that didnt work for me, and after reading a thread here I also added user_photo_video_tags because that had worked for the thread poster (again, not me). I've gotten the dialog to allow photos sharing my photos with my app, login works without any problems, the access token I get seem to be correct, after logging in I have visited: https://graph.facebook.com/me/photos?access_token= and the token, and gotten an empty array, if I wasnt logged in or the access_token wasnt linked to my app there would be some error, but all I get is an empty array. Thanks in advance for any input. Thanks to Chaney Blu I was able to validate my permissions: { "data": [ { "installed": 1, "status_update": 1, "photo_upload": 1, "video_upload": 1, "create_note": 1, "share_item": 1, "publish_stream": 1 } ] } <?php error_reporting(E_ALL); ini_set("display_errors", 1); require_once 'library/facebook.php'; $app_id = "xxxxxxxxxxxxxxxx"; $app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true )); $loginLink = $facebook->getLoginUrl(array( 'scope' => 'user_status,publish_stream,user_photos,user_photo_video_tags' )); $logOutLink = $facebook->getLogoutUrl(); $user = $facebook->getUser(); if ($user) { try { // User logged in, get token $token = $facebook->getAccessToken(); //var_dump($token); dumped successfully // Get public profile info $user_profile = $facebook->api('/me'); //var_dump($user_profile); dumped successfully $photos = $facebook->api('/me/photos?access_token=' . $token); var_dump($photos); // Empty array, BAH! } catch (FacebookApiException $e) { $user = null; } } ?> <a href="<?php echo $loginLink; ?>">Click here to login if you aren't autoredirected</a><br /><br /><br /> <a href="<?php echo $loginLink; ?>">Click here to logout</a> A: Not sure if this is the problem, but try this. It appears you're using the latest PHP SDK. In your getLoginUrl(); calls, try changing 'req_perms' to 'scope'. Like this: $loginLink = $facebook->getLoginUrl(array( 'scope' => 'user_status,publish_stream,user_photos,user_photo_video_tags' )); You can verify that you've authorized the correct permissions by visiting https://graph.facebook.com/me/permissions/?access_token=XXXX A: After testing some other permissions I noticed facebook weren't updating the permissions to my token, even when logging out of the app, logging in again and accepting new permissions nothing changed when I looked at the Graph permissions link I got from Chaney Blu. I used that link to verify the token from facebooks graph api page http://developers.facebook.com/docs/reference/api/ and noticed that token had access to user_photos but not my token. Going into my facebook settings and removing the app made facebook update my permissions the next time I signed into the app. Thanks to Chaney Blu for putting me on the right track. Would vote you up if I had the reputation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: group_concat only when more than one to group I'd like to perform a group-concat in SQLite only on those records where there is more than one row to concatenate. It seems like you could do this beforehand (count records using a group by then remove those singleton rows before proceeding with the group_concat); after (complete the group_concat then remove rows where nothing was concatenated); or possibly even during? My question: what's the fastest way for SQLite to accomplish this? I've worked out an "after" example using APSW in Python, but am not happy with it: #set up a table with data c.execute("create table foo(x,y)") def getvals(): a = [1, 1, 2, 3, 3] b = ['a','b','c','d','e'] for i in range(5): yield a[i],b[i] c.executemany("insert into foo values(?,?)",getvals()) c.execute('''create table fooc(a,b); insert into fooc(a,b) select x, group_concat(y) from foo group by x''') c.execute('select * from fooc') c.fetchall() ## reports three records c.execute("select * from fooc where b like '%,%'") c.fetchall() ## reports two records .. what I want It seems crazy (and slow?) to use LIKE for this kind of need. A: Add a HAVING clause to your query: INSERT INTO fooc(a,b) SELECT x, group_concat(y) FROM foo GROUP BY x HAVING COUNT(*) > 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7601341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android app to search mp4 videos by metadata I have a set of mp4 files that I need to load onto an SD Card and read in my Android app. The app needs to be able to search the videos by category, so my plan was to add some category info in the mp4 metadata before loading them (probably in the "description" field) and then use a ManagedQuery on the MediaStore.Video.Media.EXTERNAL_CONTENT_URI to find them. I have updated the "description" field using Adobe Bridge, but when I look at the tags returned by a search, the "description" field is always null. Clearly, the data I'm writing to the mp4 files is not being picked up when Android looks at the video file. Is there another way I should be writing/searching video metadata? A: You should probably look at MediaStore.Video.VideoColumns.DESCRIPTION. You can query the MediaStore.Video.Media.EXTERNAL_CONTENT_URI as you would any other content provider: http://developer.android.com/guide/topics/providers/content-providers.html#querying A: You can add/delete/lookup metadata fields in MP4 files using JCodec's MetadataEditor class. If you want to add metadata field to MP4 file you can use: MetadataEditor mediaMeta = MetadataEditor.createFrom(new File("file.mp4")); Map<String, MetaValue> meta = mediaMeta.getKeyedMeta(); meta.put("com.android.capture.fps", MetaValue.createFloat(25.)); mediaMeta.save(false); // fast mode is off Alternatively the same can be done from the command line with the CLI tool (MetadataEditorMain): ./metaedit -sk com.android.capture.fps,float=25.0 file.mp4 In the Java code you can get the list of metadata like so: MetadataEditor mediaMeta = MetadataEditor.createFrom(new File("file.mp4")); Map<String, MetaValue> meta = mediaMeta.getKeyedMeta(); for (String key : meta.keySet()) { System.out.println(key + ": " + meta.get(key)); } OR from the command line: ./metaedit <file.mp4> Read more about it: http://jcodec.org/docs/working_with_mp4_metadata.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7601342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ELF format manipulation I have a requirement where I want to associate an index with a file(in a certain format). I was wondering if I can do any ELF manipulation and still ensure that, consistency is maintained so, the file works fine on linux. The idea here is to create a file format which can be queried by a certain API[self-defined] to get me the index. a)is it possible to modify the ELF header to store the index(mentioned above). b)if yes, what is the process? A: You can add a new ELF section with whatever data you want to an existing executable. e.g. $ echo 42 > /tmp/index $ objcopy --add-section .my_index=/tmp/index /bin/ls myls $ objdump -s myls | tail . . . Contents of section .my_index: 0000 34320a 42. You can then figure out where to read this data from using libelf.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Multiple relationships of the same type but with different properties between the same two nodes Can I create multiple relationships of the same type between the same two nodes? I am trying to discover patterns in nodes connected with the same relationship type. For e.g., relation PERFORMED_BY could have a property to record Person1 as the performer with a timestamp for the transition from node A to node B and a second relation PERFORMED_BY could have Person2 as the performer at a different time between the same two nodes. A: Yes, you can have multiple relationships of the same type between the same two nodes in Neo4j. And the properties on the different relationships are independent from each other. It would be useful if you describe your domain a bit more, at least if you want any input on the graph structure!
{ "language": "en", "url": "https://stackoverflow.com/questions/7601346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: cgi waiting page how I can do something like that: http://online.vodafone.co.uk/en_GB/assets/static/ipi_please_wait.gif thanks A: Go to http://www.ajaxload.info/ and generate your own ajax loader :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7601353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I make a drawable from multiple images? I have three 9-patch PNG's which together make up the background for a button (left side, middle, right side). I would like to combine these three images together in a drawable which I can specify as the background for a button in XML, something along the lines of: res/drawable/button_background.xml: <?xml version="1.0" encoding="utf-8"?> <nine-patch xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/button_left_side" /> <nine-patch android:src="@drawable/button_middle" /> <nine-patch android:src="@drawable/button_right_side" /> res/layout/main.xml: <button android:background="@drawable/button_background" /> Is this possible? A: After some trial-and-error, I was able to solve the problem in a satisfactory way. I simply implemented a Layer-List drawable as follows: <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/btn_left" android:left="0px" /> <item android:drawable="@drawable/btn_middle" android:left="26px" android:right="26px" /> <item android:drawable="@drawable/btn_right" android:right="0px" /> </layer-list> Where the 26px values are the width of the two button side images in pixels. To use this drawable, simply call it like any other drawable: <bitmap android:src="@drawable/button_background" /> This works exactly how you would expect it to, with the middle expanding as normal to fit the desired width, and all three images expanding to fit the desired height. I hope others can benefit from this!
{ "language": "en", "url": "https://stackoverflow.com/questions/7601357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How to keep focus in input element where Enter was pressed to submit form Form contains input elements and submit button. Pressing Submit button shows pdf file in new tab in browser. If enter is pressed to show report, focus moves to submit button. After selection report parameters tag again additional click in input element is required to enter new value to same element. How to keep focus input element where enter was pressed ? <form id="Form" class='form-fields' method='post' target='_blank' action='Render'> <input id='test' name='test' value='test' /> ... <input id='_submit' type='submit' value='Show report' /> </form> jquery, jqueryui, asp.net mvc2 are used. update I have 2 elements with same name in form to allow unchecked checkbox submission: <input type='hidden' value='false' name='Summary' /> <input type='checkbox' id='Summary' name='Summary' checked /> <select class="ui-widget-content ui-corner-all" id="_Report" name="_Report" size="10"> <option value="LV001">Report1</option> <option value="LV003">Report2</option> <option selected="selected" value="LV009">Report3</option> </select> I tried code below as suggested in comment. If focus is in checkbox, it focus is not restored. Instead select element is focused. How to fix ? $("#Form input:not([type=submit]), textarea, select").focus(function () { $('input').removeClass('hasFocus'); $(this).addClass('hasFocus'); }); A: Or since you are already using jQuery, you could probably also use this simple function to set focus on submit: $(function() { $('#Form').submit(function(){ $('#test').focus(); }); }); This way focus will be set to "#test" as soon as the form is submitted. Demo: http://jsfiddle.net/vZSZT/ Edit: To get focus back to where it was when form was submitted, I would probably do it this way: $(function() { //Lets make sure we dont target the submit-input $("input:not([type=submit])").focus(function () { //Remove previous focused inputs $('input').removeClass('hasFocus'); //Add focus class to this input $(this).addClass('hasFocus'); }); $('#Form').submit(function(){ $('.hasFocus').focus(); }); }); Demo: http://jsfiddle.net/vZSZT/4/ However, Christoffer´s way seems to be good too (and probably even better? I cant tell), but both will work :) A: If you want to get back to the last focused item, I think you will need to keep track on the last focused item. Something like this will probably achieve what you are looking for: $(function() { var lastFocus = []; $('#Form').find(':text,:radio,:checkbox,select,textarea').focus(function() { lastFocus = $(this); }); $('#Form').submit(function(){ if (lastFocus.length == 1) lastFocus.focus(); // just to prevent the actual submit - remove this to enable submit return false; }); }); I also made a jsfiddle to test: http://jsfiddle.net/Jht6C/ A: Actually, there is a simple solution for focusing after form submit. Add the keyword autofocus as an attribute to the input-element. <input id='test' name='test' value='test' autofocus>
{ "language": "en", "url": "https://stackoverflow.com/questions/7601362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does dynamic work with IUnknown and Typelib Currently I'm experimenting with C#4's dynamic programming and I did not completely understand under which circumstances the keyword dynamic works. It is clear to me that it works with IDispatch, as it allows to inform the caller with type information automatically. But shouldn't it also work with IUnknown and a type lib? (In http://samgentile.com/Web/vs2010-and-net-framework-4-0/c-4-0-bcl-4-series-dynamic-primitive-type-part-1/ I found a vague hint that a Binding to IUnknown should be possible.) * *IUnknown w/o typelib: should not work, the interfaces must be written in C# explicitly, so I didn't try it. (Confirmed by Hans Passant in C# 4.0 dynamic object and WinAPI interfaces like IShellItem (without defining them in the C# source).) *IUnknown w/ type lib: I have completely no idea, if it works and how it works as I found no clear information. (I linked the type lib into the COM dll, but the DLR could not bind methods.) So does IUnknown w/ type lib work with C#'s dynamic keyword? - If so, what do I have to do? A: My current foundings are that the COM-binder only works with IDispatch and not with IUnknown at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a link to an image Is there a way to add a link to an image using an input box, let say you have an image uploaded and you have an input, Image Link: <input type="text" id="image_link"/> in this box a user types in www.google.com and you want the link to append to the image. Is there a way to do this? A: Did you mean something like this: http://jsfiddle.net/2QRBm/ ? HTML: <input/> <button>set link</button> <img src="http://media.heavy.com/post_assets/2010/03/0417/1267743226_stoned-party-dog-original.jpg" width="300"/> Javascript: $('img').wrap($('<a/>',{href:'',target:'_blank'})); $('button').click(function(){ var val=$('input').val(); $('img').closest('a').attr('href',val.replace(/^([^(http://)].*)/,'http://$1')); }); A: Something like this: live demo HTML: <input type="text" id="test"/> <input type="button" id="go" value="go"/> JavaScript: $("#go").click(function(){ var value = $("#test").val(); window.location = "http://"+value+""; }); A: Lets say your image have this id: #img Then you can use jQuery wrap to wrap the image into a a element: $('input').change(function(){ $('#img').wrap('<a href="' + $(this).val() + '"></a>') }) DOCS: http://api.jquery.com/wrap/
{ "language": "en", "url": "https://stackoverflow.com/questions/7601367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding Items to a ListBox I have a WPF main window, which contains a toolbar with buttons and a tabcontrol that is displaying a page with a listbox. The page is hosted on a frame, and the frame is set on the tab I selected. When I click on a button on my toolbar, a new window pops up with a textbox and a submit button. When I press the submit button, I want to insert the textbox contents into the listbox that's on the main window. However, nothing displays in the listbox. I tried listbox.Items.Add() but it still won't display. public partial class AddNewCamper : Window { public AddNewCamper() { InitializeComponent(); } private void btnNewSubmit_Click(object sender, RoutedEventArgs e) { CampersPage c; // Converting string to int b/c thats what camper() takes in. int NewAge = Convert.ToInt16(txtNewAge.Text); int NewGrade = Convert.ToInt16(txtNewGrade.Text); // Create a new person Camper person = new Camper(NewAge, NewGrade, txtNewFirstName.Text); txtNewFirstName.Text = person.getName(); // Trying to add the first name of the person to display on the listbox of another window. c.testListBox.Items.Add(txtNewFirstName.Text); } A: You can follow any of the following approaches. But based on your comments I guess solution 3 suits you. 1) Try initializing c first. You can't use an object without allocating memory for it. 2) If you want to use the same object, use the reference of the object created in the MainWindow in the required class. something like this should work: CampersPage c = [reference to CampersPage object in MainWindow] then add items to your listbox 3) If you want to use the listbox object, make your CampersPage Class static. Making it static would not require you to initialize your class explicitly. public static CampersPage { // do something here } Make sure that you declare your listbox in CampersPage as public. Then in the class requiring your listbox defined in CampersPage, do the following CampersPage.testListBox.Items.Add(txtNewFirstName.Text); 4) If the classes are in the same namespace, you can declare listbox as a global public property and access it from rest of the classes in the same namespace.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: clojure for loop, store the values in a set or map This one has been bothering me for a while now, How should we store a value in a set or map in a for loop? (let [s #{}] (for [ i (range 10) j (range 10) ] (into s [i j]))) i know this will not work, but i want a functionality similar to this , where the set will finally contain [0 0] [0 1]...[0 9] [1 0]...[9 9] Thanks A: Is this what you want? (into #{} (for [i (range 10) j (range 10)] [i j])) ;-> #{[2 1] [3 2] [4 3] [5 4] [6 5] [7 6] [8 7] [9 8] [1 0] ; [2 2] [3 3] [4 4] [5 5] [6 6]... And if you just want the list as a set: (set (for [i (range 10) j (range 10)] [i j])) You will end up with a set of pairs. A: Generally when you want to return a set or a map or other 'single value' that isn't a seq from a 'repeated' generalized operation on a seq, using reduce is more idiomatic/straightforward than loop/recur, and for always returns a seq (not a set or map). (reduce conj #{} (for [i (range 10) j (range 10)] [i j])) note that (for ..) here is only used to produce a seq containing all the values to compile into the single result set. Or, for example: (reduce + 0 (range 100)) => 4950 A: If I understand your question correctly you need to turn your expression inside-out: (let [s #{}] (into s (for [i (range 10) j (range 10)] [i j]))) The thing to realize here is that for returns a value (a lazy sequence) unlike for-loops in more imperative languages like Java and C. A: clojure has a several great systems for managing mutable state. in this case you may want an atom containing a set your other options are: * *a ref if more than one change needs to made (coordinated many threads) *a var if this will be single threaded (a var may work just as well here as an atom) *an agent if you wanted to set the value of s asynchronously of course for returns a sequence already so you may just want (into #{} (for [ i (range 10) j (range 10) ] [i j])) A: I think you can also use some transient data structure in this scenario. (let [s (transient #{})] (for [ i (range 10) j (range 10) ] (assoc! s i j))) (persistent! s) Just a code sample, not tested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: delete multidimensional arrays In C++ FAQ, the [16.16] gives the following example, void manipulateArray(unsigned nrows, unsigned ncols[]) { typedef Fred* FredPtr; FredPtr* matrix = new FredPtr[nrows]; // Set each element to NULL in case there is an exception later. // (See comments at the top of the try block for rationale.) for (unsigned i = 0; i < nrows; ++i) matrix[i] = NULL; try { for (unsigned i = 0; i < nrows; ++i) matrix[i] = new Fred[ ncols[i] ]; for (unsigned i = 0; i < nrows; ++i) { for (unsigned j = 0; j < ncols[i]; ++j) { someFunction( matrix[i][j] ); } } if (today == "Tuesday" && moon.isFull()) { for (unsigned i = nrows; i > 0; --i) delete[] matrix[i-1]; delete[] matrix; return; } ...code that fiddles with the matrix... } catch (...) { for (unsigned i = nrows; i > 0; --i) delete[] matrix[i-1]; delete[] matrix; throw; // Re-throw the current exception } for (unsigned i = nrows; i > 0; --i) delete[] matrix[i-1]; delete[] matrix; } Why we have to use delete this way, I mean, First delete[] matrix[i-1]; then delete[] matrix; Moreover, what’s the point of after the whole “try…catch” cycle, we still have to put for (unsigned i = nrows; i > 0; --i) delete[] matrix[i-1]; delete[] matrix; at the end of this function. A: What you're missing is the horribly evil indentation. delete matrix[i-1]; happens once per loop iteration and deletes the nested arrays. delete matrix happens just one time after the loop completes and deletes the outer array. Never write code like this in C++, use vector<vector<T> > instead. The reason the deletes also exist in the catch is because if you catch an exception you're still responsible to clean up the memory you allocated. A: * *The try/catch block is necessary to ensure proper clean-up even if an exception is thrown anywhere in the code before the normal clean-up happens. This includes an exception in one of the new expressions. The delete[] is safe because all the relevant pointers were initially set to zero, so that the deletion is valid even if no allocation ever occurred. (Note that if any exception does occur, it will still be propagated outside the function. The local try/catch block only ensures that the function itself doesn't leak any memory.) *There are two sets of arrays: one is the outer array matrix, which is an array of pointers. This array gets allocated first and deleted last. Second, each element matrix[i] is itself a pointer to an array of Fred elements. Each array gets allocated in the first for loop, and thus has to be deleted in another loop at the end. A: When you in a loop deleting each of the rows, you're freeing up the memory allocated to the corresponding row. Then you need to free up the memory allocated for the pointers to each row. Think of it this way: FredPtr* matrix = new FredPtr[nrows]; allocates an array of pointers to rows - and it will need to be freed up at the end. Then for each of the rows, matrix[i] = new Fred[ ncols[i] ]; allocates memory for an array of pointers to columns - and it will need to be freed up separately. A: yes, that is not a quality of an example-code but it is working fine. The copy-pasted code in the catch-block and after the catch-block is needed because in case of an exception the memory should be freed and in this case the exception is forwarded to the caller of that function. if you dont want to forward that exception you can delete the code inside the catch-block (but at least a console-output would be nice ;) ) A: The catch block in the try...catch is there to delete the matrix if an exception was thrown, and then re-throw the exception. If no exception is thrown, the catch block never gets hit, and the matrix has to be deleted on the way out through the normal exit of the routine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# foreach on a collection of an interface I'm wondering if there is any functionality built in to C#/LINQ to simplify the following: foreach(var item in collection) { if (item.GetType() == typeof(Type1) DoType1(item as Type1); else if (item.GetType() == typeof(Type2)) DoType2(item as Type2); ... } to something along the lines of: collection.ForEachType(Type1 item => DoType1(item), Type2 item => DoType2(item)); I realize that the following is close: collection.OfType<Type1>.ToList().Foreach(item => DoType1(item)); collection.OfType<Type2>.ToList().Foreach(item => DoType2(item)); But it does not work when the code is dependent on the order of the collection. A: The first thing I'd look at is polymorphism; can I instead use a virtual method, and item.DoSomething()? The next thing I'd look at would be an enum discriminator, i.e. switch(item.ItemType) { case ItemType.Foo: ... case ItemType.Bar: ... } (and add the discriminator to the common interface/base-class) If the types could be anything, then 4.0 has a trick; if you call te method the same thing for every overload, you can get dynamic to worry about picking it: dynamic x = item; DoSomething(x); A: There's nothing built into LINQ, no. I would caution you against using GetType() like this though - usually it's more appropriate to use is or as followed by a null check: foreach(var item in collection) { Type1 itemType1 = item as Type1; if (itemType1 != null) { DoType1(itemType1); continue; } Type2 itemType2 = item as Type1; if (itemType2 != null) { DoType2(itemType1); continue; } // etc } That way derived classes will be treated in a way which is usually the appropriate one. This sort of type testing is generally frowned upon, mind you - it's generally better to put the behaviour into the type itself as a virtual method, and call it polymorphically. A: What about something like: var typeActions = new Dictionary<Type,Action<Object>>(); typeActions.Add(typeof(Type1), obj => DoType1((Type1)obj)); typeActions.Add(typeof(Type2), obj => DoType2((Type2)obj)); collection.Foreach(obj => typeActions[obj.GetType()](obj)); This code is untested (typed directly into the browser). A: Your mileage may vary. Dictionary<Type, Action<object>> typeMap = new Dictionary<Type, Action<object>>(); typeMap[typeof(Type1)] = item => DoType1(item as Type1); typeMap[typeof(Type2)] = item => DoType2(item as Type2); var typeToActionQuery = from item in source let type = item.GetType() where typeMap.ContainsKey(type) select new { input = item; method = typeMap[type] }; foreach(var x in typeToActionQuery) { x.method(x.input); } Here's a version of the matching query which considers derived types (Note, an item may be matched to more than 1 type, and therefore handled multiple times). var typeToActionQuery = from item in source from kvp in typeMap where kvp.Key.IsInstanceOfType(item) select new { input = item; method = kvp.Value }; A: Not by default. Try Reactive Extensions or Elevate The Reactive Extensions and Elevate both contain a ForEach implementation. Both have quite a few methods that extend the functionality of linq. You won't find a ForEachType, but ForEach (Rx or Elevate) and OfType<> (Linq) will give you what you want. A: It seems to me that if you just replace "item.GetType() == typeof( Type1 )" with "item is Type1", your foreach loop will be simple enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I wrap text around a moveable image? I am trying to implement an interface where users can dynamically enter text and upload images. I wish for the interface to have these features: * *The images should be moveable i.e, ability to drag and drop the images around. *The text entered should automatically wrap around the images. How could I accomplish this? I have looked at some jquery scripts and also looked through HTML5's canvas features, but am unable to find a solution. Thanks for your time. EDIT: This video shows the effect I wish to obtain: http://www.youtube.com/watch?v=mYnj4Mz9g9g A: This is possible in IE10, using positioned floats: http://ie.microsoft.com/testdrive/HTML5/PositionedFloats/Default.html Other browsers have yet to support this. A: Well, at least for the wrapping, if you want to use jQuery, you can use this jQSlickWrap plugin to have the text wrap around the irregularly-shaped image. It uses a nice HTML5 canvas technique. See the text wrap example here: http://www.jwf.us/projects/jQSlickWrap/example2.html Hope it helps! A: TL;DR This is a common and desirable feature that has been discussed numerous times in the history of CSS, and there is a specification under development to make it possible. Unfortunately, implementations are few and far-between, and some implementers are reluctant to work on it. Doing it with JavaScript is a complex problem for any non-trivial layout; such a solution is unlikely to be fast enough for your purposes and you will fast approach the sort of markup you'd expect from a PDF-to-HTML converter. Background There are two questions here: irregular text flow and excluding text and other inline elements from an arbitrary region of the page. This is not the first time either feature has been discussed for CSS. In particular, flowing text around irregular floated shapes was mentioned in a CSS level 1 working draft back in 1996, and Eric Meyer's ragged float demo dates from at least 2002. This is a long overdue feature! In June 2007, James Elmore suggested adding position values to the float property, enabling elements to be positioned arbitrarily on the page while excluding other elements from flowing underneath. SVG 1.2 initially specified a model for flowed text regions, and goes into some detail on how this would be implemented. Unfortunately, the latest version of the spec (which is still in development) blows this out of the water by noting that previous work will be replaced with "a superset of the SVG 1.2 Tiny textArea feature". Current status (revised August 2012) More recently, we have the CSS Exclusions specification, a proposal from Adobe and what you see being shown off in that video. As of August 2012, these have been implemented in IE 10 RTM and are slowly being rolled out in WebKit, but developers working for other vendors have expressed mixed feelings about the proposal.* * *Trident (IE): implemented in IE10 platform preview and available in the RTM. (Referred to as "positioned floats" in IE Test Drive, similar to James Elmore's proposal.) *WebKit (Chrome, Safari): partially implemented, with patches gradually being approved for landing in the WebKit trunk, meaning we should start seeing this soon. (Bug 57311 - CSSRegions: add exclusions support in WebKit.) *Gecko (Firefox): unlikely to be implemented soon; bug currently resolved as WONTFIX. (Bug 672053 - Add support for CSS3 Positioned Floats—note David Baron's objections concerning interoperability.) *Presto (Opera): not yet implemented. (Bug tracker is private; I tried asking the ever gregarious Bruce Lawson if there was an open bug, but he is constrained from commenting on their roadmap.) Adobe maintain a handy support matrix for easy reference. Hackcough "Polyfilling"? It would be difficult achieve a similar effect using JavaScript, and even more difficult to do it efficiently. I can think of two very naive approaches to make room for an absolutely positioned element in a region: * *"block out" space for element using strategically-inserted inline spans; or *surround each word with a span element, and style each word individually to make room for the excluded element using padding. I've hacked up a very broken demo of how the second approach might work. It's horrible, buggy and easy to break. I actually spent a few weeks after answering this question working on a polyfill for the Exclusions spec, but gave up because there were too many bugs and performance issues. You will have myriad issues with either approach: columns, text alignment, errant child elements (especially floated or positioned elements!), various edge conditions, horrible things if you change the HTML, hyphenation—merciful heavens, I don't even want to think about hyphenation—and, of course, potentially magnificent performance issues after taking account of these things. Performance issues can be ameliorated somewhat; for example, I've used elementFromPoint to try and get the span containing the first overlapping word directly, and some browsers even support caretPositionFromPoint, which may also help. I think that with a lot of work, you could make something that works pretty well for static content; but making it fast enough that you can drag it around with the mouse? My demo page has precious little content and doesn't address any of the mind-bendingly complex issues you'd have to deal with to make this work on real web pages. Even if you can get around all of those issues, making it fast enough to drag around smoothly would be very challenging. * I strongly hope vendors will implement CSS Exclusions. People have been asking for these features since the earliest days of CSS, and it is a common and legitimate visual design objective both on screen and in print.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Inline-block span (inside an html td) text-ellipsis fails on long words My objective is to have a cell inside a HTML table with an expand button. This is the html I used: <td> <span class='outer'> <button>+</button> <span class='inner'>Sed eu nisi sit amet</span> </span> </td> The outer span is centered : it contains a button and some text. The button position is done through absolute positioning on the left of the outer, some left-padding avoid that the text goes under the button. Everything is fine except when I have a word which doesn't fit inside the td. I thought an overflow:hidden + text-overflow:ellipsis would suffice, but i have a problem. A demo is available at http://jsfiddle.net/omanovitsh/HYDss/54/ A: First, generally you want to avoid putting block level elements in inline elements and this is one such case. See here: http://www.w3.org/TR/REC-html40/struct/global.html#block-inline Note that: "Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements." With regards to the CSS, you would say: .table2 p { text-overflow:ellipsis; overflow:hidden; white-space:nowrap; width: 100%; } With regards to the HTML, you need to change the spans to divs: <td> <div class='outer'> <button>+</button> <div class='inner'><p>Sed eu nisi sit ametametamet</p></div> </div> </td> Otherwise, setting width to 100% for the p element will be unable to fit its width into its parent element since the parent element is a span which is an inline element. Thank you. Please see here: http://jsfiddle.net/VivekVish/HYDss/76/ A: Try something like: .table2 .inner { text-overflow: ellipsis; max-width: 2em; white-space: nowrap; } The max-width (or just use width if you prefer) forces the overflow to kick in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I measure the length of a long string in Ruby? SciTE and command prompt aren't working. I've written a program that measures my typing speed. As part of this, I need it to count how many characters I've typed. I did that with text = gets.chomp puts text.length.to_s Unfortunately, I can't get this working for a long string. In the SciTE editor, .length doesn't work properly, so instead of giving me the length of the string, it gives me the character count of everything I've typed, including corrected mistakes - if I typo "Hrello" and correct it to "Hello", it'll still return 6 instead of 5. I googled this, and the suggested fix was to run the program from the command prompt instead. In the command prompt, .length works fine, but it turned out that I can't type in more than 264 characters. So I tried to put a GUI on the program with Shoes: Shoes.app :width => 300, :height => 300 do button "Start." do text = ask "Type here." para text.length.to_s end end and discovered that Shoes' input box has an even shorter character limit. I'm running Windows 7, Ruby 1.9.2, SciTe version 2.29 and Shoes Policeman Revision 1514. How can I run this program so it'll correctly measure the length of a really long string? I'd be happy with any solution that fixes the command prompt or Shoes character limit, the SciTE bug, or just a suggestion for a different way to execute ruby programs where this will work. A: I'd be happy with [...] a suggestion for a different way to execute ruby programs where this will work. What about a simple web app? Here is a simple Sinatra app that accomplishes exactly what you have asked with a very large character limit. require 'sinatra' get '/' do %{<html> <body> <form method="post"> <textarea name="typed"></textarea> <input type="submit"> </form> </body> </html> } end post '/' do "You typed #{params['typed'].length} characters." end To run the app you can use something as simple as ruby sinatra_example.rb to use a built-in web server. Or, you can deploy this app using any of several web servers. If you need timers this should be easy to accomplish through javascript and include in the form submit. A: Ok, your question is not accurately titled, but lets see: There is a very broad number of options of using command prompt, and you should consider running a simple script in ruby on it. On command line from windows, try typing ruby C:/path_to_folder_program/program.rb If it won`t execute, you can find on ruby folder some executable called ruby and should, from command prompt on that path, run it like above. But let me ask you, why ruby? Other more accessible and user-friendly programming languages, like javascript would behave better and would be easier to make your program accessible. A: - EDIT - Seems shoes can handle more chars, use edit_box instead of ask: In Shoes: Shoes.app do @txt = edit_box button("How many"){ alert(@txt.text.size) } end Anyway, before trying shoes I did the exercise with that I knew, here it is: In javascript: <script> function start_stop(){ var txt = document.getElementById('txt'); var btn = document.getElementById('btn'); if( txt.disabled ){ txt.value = ''; txt.disabled = false; btn.value = 'Stop'; txt.focus(); startTime = new Date().getSeconds(); } else { txt.disabled = true; btn.value = 'Start again'; timeNow = new Date().getSeconds(); alert(txt.value.length + " characters in " + (timeNow - startTime) + " seconds."); } } </script> <input type='button' id='btn' onclick='start_stop()' value='Start'> <textarea id='txt' rows='8' cols='80' disabled></textarea> In Ruby using Qt: (replicating the same idea as in the javascript one) require 'Qt' class MyWidget < Qt::Widget slots :start_stop def initialize super setFixedSize(400, 120) @btn = Qt::PushButton.new("Start") @txt = Qt::TextEdit.new ; @txt.readOnly = true vbox = Qt::VBoxLayout.new vbox.addWidget @btn vbox.addWidget @txt setLayout vbox connect(@btn, SIGNAL("clicked()"), self, SLOT(:start_stop)) end def start_stop if @txt.readOnly @txt.plainText = '' @txt.readOnly = false @btn.text = "Stop" @txt.setFocus @startTime = Time.now else @txt.readOnly = true @btn.text = "Start again (#{@txt.plainText.size} chars #{(Time.now - @startTime).to_i} in seconds)" end end end app = Qt::Application.new(ARGV) widget = MyWidget.new widget.show app.exec
{ "language": "en", "url": "https://stackoverflow.com/questions/7601405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MongoMapper memory leak when querying an array of IDs I run this query in a rails console process that has a "5.3%" memory usage. (User is a MongoMapper::Document-included class) user_ids = ["4de409fc7813b4789d000001", "4de4efdc7813b410e9000007", "4de5297f7813b410e900023b", "4de4f8847813b410e9000037", "4de40eb17813b4788c000009", "4de408787813b4788c000001", "4de522a87813b410e9000072", "4de5238d7813b410fa000090", "4de523877813b410e900009e", "4de526097813b410fa000113", "4de4fd5f7813b410e900003f", "4de522a17813b410e9000070", "4de522597813b410fa000063", "4de525ab7813b410e9000126", "4de522997813b410e900006e", "4de541227813b410e9000319", "4de526ad7813b410fa00013c", "4de4fe5a7813b410fa00003c", "4de522d67813b410fa000075", "4de5238a7813b410e90000a0", "4de4419b7813b4788c00003f", "4de523ec7813b410e90000cf", "4de523467813b410fa00008c", "4de59f557813b45e84000001", "4de553bb7813b449a400007f", "4de8cc757813b4368b00000d", "4df66a2d7813b47c0b000017", "4e0a2ca57813b45f6400000b", "4de7b29f7813b4142800002c", "4e205b537813b4567a000071", "4e1b62a57813b42b9d000092","4e6678371adda36d52000021"] User.find(user_ids) It executes successfully, but the memory usage is now "9.1%". Running the command in a 100.times { … } loop increases the memory indefinitely. Does anybody know what could explain this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is Haar Cascade the only available technique for image recognition in OpenCV I know that there are many detection techniques in OpenCV, such as SURF, STAR, ORB etc...but those techniques are for feature detection of new video feed, not for dealing with specific instances of objects that require prior learning. OpenCV's documentation isn't quite as easy to flip through and I've yet been able to find anything besides Haar, which I know deals best with face recognition. So are there any other techniques besides Haar? The Haar technique dates back to research 10 years ago, so ideally I hope that there have been some more advances since then that have been implemented in OpenCV. A: If you are looking for OpenCV machine learning type algorithms, check out this link. For a state of the art on-the-fly object detection algorithm, have a look at OpenTLD. It uses bounding boxes and random forests to learn about an object over time. Check out the demo video here. Also check out the matching_to_many_images.cpp sample from OpenCV. It uses feature descriptors to match objects much like Google Goggles works. A related example to this is the bagofwords_classification.cpp sample. It may be what you are looking for in this case. It uses feature detectors (SURF, SIFT, etc...) to detect objects and then classify them by comparing the relative positions of the features to a learned database of features. Have a look also at this tutorial from MIT. The latentsvmdetect.cpp may also be a good starting point for you. Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7601413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: local variable not accessed & 'this' context enforcement i have the following piece of code that is giving me trouble working [question(s) after code] var LIB = function(){}; (function(){ var JSExpert = function(lname){ if(!(this instanceof arguments.callee)){ return new JSExpert(lname); } this.fname = "Later "; this.name = this.fname + lname; }; JSExpert.prototype = { setFname: function(fname){ this.fname = fname; return this; //for chaining }, getName: function(){ alert("javascript expert name is " + this.name); } }; LIB.Expert = JSExpert; return; window.JSExpert = JSExpert; })(); Now here come the test code LIB.Expert("Edwads").setFname("Dean").getName(); Now when you try the code the setFname() method which is supposed to change "Later " in the constructor by "Dean" isn't doing it, why is that???? Second question: we're using 'this' inside JSExpert. how can one be sure the context of 'this' isn't bound later to the context of 'LIB' and stay enforced to that of 'JSExpert' and thus 'LIB.Expert' ? Thanks A: Because this: return; window.JSExpert = JSExpert; is not correct, should be: window.JSExpert = JSExpert; and getName: function(){ alert("javascript expert name is " + this.name); } should be: getName: function(){ alert("javascript expert name is " + this.fname + this.lname); } and lname needs to be a property like fname. Example var LIB = function() {}; (function() { var JSExpert = function(lname) { if (!(this instanceof arguments.callee)) { return new JSExpert(lname); } this.lname = lname; this.fname = "Later "; this.name = this.fname + lname; }; JSExpert.prototype = { setFname: function(fname) { this.fname = fname; return this; //for chaining }, getName: function() { alert("javascript expert name is " + this.fname + ' ' + this.name); } }; LIB.Expert = JSExpert; //window.JSExpert = JSExpert; })(); LIB.Expert("Edwads").setFname("Dean").getName(); A: 1) Change setFname: function(fname){ this.fname = fname; return this; //for chaining }, to setFname: function(fname){ this.name = this.name.slice(this.fname.length); this.name = fname + ' ' + this.name; this.fname = fname + ' '; return this; //for chaining }, 2) In the contructor function you check this type: var JSExpert = function(lname){ //If not an instance of this class creates a new object of this class and return it if(!(this instanceof arguments.callee)){ return new JSExpert(lname); } this.fname = "Later "; this.name = this.fname + lname; }; In the other functions you can do something like if (!(this instanceof JSExpert)) throw new Error('');, throwing an error is the best you can do here, this is a drawnback in using the prototype.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITableView Animations I am attempting to create a animated cell when it is selected. Everything seems to be working really odd. If I send the ButtonView to the Self.contentView of the UITableView Cell it works like it is supposed to and adds the cell in desired row but I loose button functionality at index row. If I send the buttonview to just self "UITableViewCell" I have button index row but it adds the button view in about every 10 rows. Now the animation itself looks great when it works right. The issue is I am using a method to toggle the path selected so I can grow the cell height to twice the size when selected and stay selected until another cell is selected. Really I have no idea where to go from here I was hoping maybe someone could help me find my mistake or have delt with something similar. Thanks I appreciate any insight! - (BOOL)cellIsSelected:(NSIndexPath *)indexPath { // Return whether the cell at the specified index path is selected or not NSNumber *selectedIndex = [selectedIndexes objectForKey:indexPath]; return selectedIndex == nil ? FALSE : [selectedIndex boolValue]; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [sounds PlayButtonClick:nil]; // Deselect cell ..? //[tableView deselectRowAtIndexPath:indexPath animated:TRUE]; // Toggle 'selected' state BOOL isSelected = ![self cellIsSelected:indexPath]; // Store cell 'selected' state keyed on indexPath NSNumber *selectedIndex = [NSNumber numberWithBool:isSelected]; [selectedIndexes setObject:selectedIndex forKey:indexPath]; // This is where magic happens... [tableView beginUpdates]; [tableView endUpdates]; [sounds PlaySlide:nil]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // If our cell is selected, return double height if([self cellIsSelected:indexPath]) { return 70 *2; } return 70; } And from my CellClass - (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier { if (self == [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]) { self.contentView.clipsToBounds = YES; } return self; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; if (selected == YES) { NSLog(@"is selected"); [self showButtonView:!selected]; [self applyDropShadow:!selected]; // TweettextLabel.hidden = YES; // Tweettext.hidden = NO; } if (selected == NO){ [self removeButtonView:!selected]; [self removeDropShadow:!selected]; //TweettextLabel.hidden = NO; //Tweettext.hidden = YES; NSLog(@"is NOT selected"); } } -(void)showButtonView:(int)view{ CGRect viewFrame = [ButtonView frame]; viewFrame.origin.y = 0; self.ButtonView.frame = viewFrame; [self.contentView insertSubview:self.ButtonView belowSubview:self.cellView]; [self addSubview:self.contentView]; [UIView beginAnimations:@"animateView" context:nil]; [UIView setAnimationDuration:0.3]; CGRect viewFrame1 = [ButtonView frame]; viewFrame1.origin.y = 70; ButtonView.frame = viewFrame1; [UIView commitAnimations]; } -(void)removeButtonView:(int)view{ [UIView beginAnimations:@"animateView" context:nil]; [UIView setAnimationDuration:0.3]; CGRect viewFrame1 = [self.ButtonView frame]; viewFrame1.origin.y = 0; self.ButtonView.frame = viewFrame1; [UIView commitAnimations]; // timer = [NSTimer scheduledTimerWithTimeInterval:0.4 target:self selector:@selector(removeLastViewFromSuper) userInfo:Nil repeats:NO]; } -(void)applyDropShadow:(int)shadow{ self.contentView.layer.shadowColor = [[UIColor blackColor] CGColor]; self.contentView.layer.shadowOffset = CGSizeMake(0.8f, -4.0f); self.contentView.layer.shadowRadius = 5.0f; self.contentView.layer.shadowOpacity = 1.0f; } -(void)removeDropShadow:(int)shadow{ self.contentView.layer.shadowColor = [[UIColor clearColor] CGColor]; self.contentView.layer.shadowOffset = CGSizeMake(0.0, 0.0); self.contentView.layer.shadowRadius = 0.0; self.contentView.layer.shadowOpacity = 0.0; } A: Add the buttonView to the cell's contentView when you create it. Show and hide it by setting the hidden or alpha property. Now the problem of not getting the button to work should go away. Also, your dictionary with the selected indexes seems a bit overdone if you only have one cell that is selected. Just create a property "selected" of type NSIndexPath in the controller. Finally, your selected cell repeating when you scroll is due to the re-queuing mechanism of UITableView. Make sure that you set the correct hidden property for the button in cellForRowAtIndexPath each time. This way, when a cell is recycled that has a non-hidden button, it will hide it if the index path is not the selected one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any benefit of uses CHAR over VARCHAR? CHAR is stored as a fixed length string, VARCHAR is stored as a variable length string. I can use VARCHAR to store a fixed length string, but why people still want to use CHAR to store a fixed length string? Is there any benefit of using CHAR over VARCHAR? If none of benefit, why mySQL database doesn't remove the option of CHAR? A: * *VARCHAR varchar stores variable-length character string. it can require less storage than fixed-length types because it uses only as much space as it needs. varchar also uses 1 or 2 extra bytes to record the value's length. for example varchar(10) will use up to 11 bytes of storage space. varchar helps performance because it saves space. however because the rows are variable length, they can grow when you update them, which can cause extra work. if a row grows and no longer fits in its original location, the behavior is storage engine-dependent... * *CHAR char is fixed-length , mysql always allocates enough space for the specified number of characters. When storing a CHAR value, MySQL removes any trailing spaces. Values are padded with spaces as needed for comparisons. char is useful if you want to store very short strings, or if all the values are nearly the same length. For example, CHAR is a good choice for MD5 values for user passwords, which are always the same length. char is also better than VARCHAR for data that’s changed frequently, because a fixed-length row is not prone to fragmentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Is there a way to use tortoise svn to backup my modified files? I have a bunch of files that I've changed that I don't really want to commit, but I would like to back them up locally in case I would like to use them again. (Then I'll revert them.) TortoiseSvn working status helps to view the modified files, but I want a way to save them all to a separate directory like Backups\, preferably with their folder heirararchy still in tact. How can I do that? UPDATE: Apparently branching is the way to go. But what I did was just copied the modified files paths to the clipboard (which is an option in tortoisesvn) then to a file, and created a program to copy them to a backup folder. A: You can create a branch and commit those files only in that branch. A: You can commit it inside a branch, so it doesn't affect your current 'trunk' or branch. If you had a try with bazaar , that is compatible with SVN, there is a shelf command to temporarily store a set of modification and apply back them later.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get html and text of highlighted (selected) elements (spans) and store text in hidden textarea I want to know how to get the html and text of spans that are selected. Example html: <span>a</span> <span>b</span> <span>c</span> <span>d</span> so if I highlighted with my cursor (a-b)...I would get var storedHtml = `<span>a</span> <span>b</span>` var text = "ab" and the text would be stored in a hidden textarea A: There's a few articles on this already: * *Get the Highlighted/Selected text * *Which references -> http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html *Which in turn was a duplicate of: Selecting text in an element (akin to highlighting with your mouse)
{ "language": "en", "url": "https://stackoverflow.com/questions/7601427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What is default integer limit in PostrgreSQL database for Rails 3? What is default integer limit in PostrgreSQL database for Rails 3? That's the question. A: By default, Rails will use PostgreSQL's integer type, which has a range of -2147483648 to +2147483647.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: An automated algorithm tool for running time I am wondering if there is an open source project that can run the algorithm and tell us what the running time is (just need to know the Big-Oh running time). I know I can do this with hands, but a lot of algorithms are too long or too complex to actually trace the running time. Thanks. PS: Mainly for C++ (but it works for more than just C++ would be nice!!) A: There's just no way to do this. You'll never know generally what set of n you have to test for any given algorithm. For example sin and linear will look almost identical at small values of t (the input). Exponential can look polynomial in various ranges of input. For other functions, the constant time may make a linear function look sublinear. The way to figure out the big-oh complexity is to just analyze the algorithm yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: my application crashes trying to call native method while woking on emulator? I am developing a program that uses native code and it works fine on the testing device Samsung galaxy S but when i try it on the emulator it doesn't work , the program just closes with no exceptions. while debugging i found that the program crashes once it reaches a call to any native method is there a way to make the program work on emulator? Edit: i tried another program that uses native methods on emulator and it worked. A: Application works with native ARM code also on emulator. The emulator behaves as normal ARM device, and emulates also ARM code. I have no problems running my native apps on the emulator. You should study logcat output to find reason of your failures. A: Did you call LoadLibrary? The NDK includes example programs like HelloJNI. You should be able to get that to run, then work from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: JComboBox as a Custom TableCellEditor I have a table. Changes on that table update database. One column is edited by a JComboBox in that table. Clicks to any cell in that column fires a tableChanged event. However it needs to be fired after selecting an item of a JComboBox. How can i make tableChanged occur after selection? public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor { JComboBox jComboBox; @Override public Object getCellEditorValue() { return jComboBox.getSelectedItem(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { Vector vector = new Vector(); vector.add(0); for (int i = 0; i < table.getRowCount(); i++) { if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Female")) { vector.add(table.getValueAt(i, 0)); } } vector.remove(table.getValueAt(row, 0)); jComboBox = new JComboBox(vector); jComboBox.setSelectedItem(value); return jComboBox; } } A: I would highly recommend using SwingX which has a ComboBoxCellEditor component. It's essentially Sun's incubator for features Swing components should have. I have no idea if the project is still actively developed, but its mature, and I've used it in many projects. If, for whatever reason, you can't or don't want to use an external library, here is their code (with parts modified to remove custom SwingX features), comments intact: Note: the library is GPL'ed code. /* * $Id: ComboBoxCellEditor.java 3738 2010-07-27 13:56:28Z bierhance $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.util.EventObject; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; /** * <p> * This is a cell editor that can be used when a combo box (that has been set up for automatic completion) is to be used in a JTable. The * {@link javax.swing.DefaultCellEditor DefaultCellEditor} won't work in this case, because each time an item gets selected it stops cell * editing and hides the combo box. * </p> * <p> * Usage example: * </p> * <p> * * <pre> * <code> * JTable table = ...; * JComboBox comboBox = ...; * ... * TableColumn column = table.getColumnModel().getColumn(0); * column.setCellEditor(new ComboBoxCellEditor(comboBox)); * </code> * </pre> * * </p> */ public class ComboBoxCellEditor extends DefaultCellEditor { /** * Creates a new ComboBoxCellEditor. * * @param comboBox the comboBox that should be used as the cell editor. */ public ComboBoxCellEditor(final JComboBox comboBox) { super(comboBox); comboBox.removeActionListener(this.delegate); this.delegate = new EditorDelegate() { @Override public void setValue(final Object value) { comboBox.setSelectedItem(value); } @Override public Object getCellEditorValue() { return comboBox.getSelectedItem(); } @Override public boolean shouldSelectCell(final EventObject anEvent) { if (anEvent instanceof MouseEvent) { final MouseEvent e = (MouseEvent) anEvent; return e.getID() != MouseEvent.MOUSE_DRAGGED; } return true; } @Override public boolean stopCellEditing() { if (comboBox.isEditable()) { // Commit edited value. comboBox.actionPerformed(new ActionEvent(ComboBoxCellEditor.this, 0, "")); } return super.stopCellEditing(); } @Override public void actionPerformed(final ActionEvent e) { ComboBoxCellEditor.this.stopCellEditing(); } }; comboBox.addActionListener(this.delegate); } } A: Now it works. JComboBox needs to be reinitialized every time getTableCellEditorComponent method invoked. And in the itemstatechange of this JComboBox stopCellEditing() method must notify listeners that editing done when item is selected. That make the TableModelListener fireTableChanged event. (Fixed) However it also fires that event when you click a JComboBox after clicking another JComboBox without making a selection. (/Fixed) Edit: Following code is the last version. By this TableModelListener is notified only when an item is selected. The problem mentioned above is fixed. It was because of default stopCellEditing() method always returned true. This cause cell editing stop in an unexpected way. It must be overriden as needed and fireEditingStopped(); must be used to notify TableModelListener public class JIDCellEditor extends AbstractCellEditor implements TableCellEditor { private JComboBox jComboBox = new JComboBox(); boolean cellEditingStopped = false; @Override public Object getCellEditorValue() { return jComboBox.getSelectedItem(); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { Vector vector = new Vector(); ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(Integer.parseInt(value.toString())); vector.add(0); for (int i = 0; i < table.getRowCount(); i++) { if (!vector.contains(table.getValueAt(i, 0)) && table.getValueAt(i, 3).toString().equals("Sheep")) { vector.add(table.getValueAt(i, 0)); } } vector.remove(table.getValueAt(row, 0)); for (int i = 0; i < vector.size(); i++) { } jComboBox = new JComboBox(vector); jComboBox.setSelectedItem(value); jComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { fireEditingStopped(); } } }); jComboBox.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) { cellEditingStopped = false; } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { cellEditingStopped = true; fireEditingCanceled(); } @Override public void popupMenuCanceled(PopupMenuEvent e) { } }); return jComboBox; } @Override public boolean stopCellEditing() { return cellEditingStopped; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: bluetooth project with Android. How to scan the piconet, master and slaves I have a big issue. I would want to create an app on Android (telephone) where should act as a master, and several devices (bluetooth modules) should act as slaves (only piconet, not scatternet). I need that everytime, the master wants to check all avaliable devices near it (for example, an Inquiry process every minute to check an update list of devices around the master), he should obtain this information to know which ones are out of range, powered off or sync. from lots of questions here on stackoverflow, everybody agrees that making all slaves always discoverable is impossible, because it will drain the battery super fast (so doing the process of Inquiry scan every minute is not feasible). So, which other technical solution could you advice to me? I have been thinking about something after the master makes de inquiry and paging process, when up to 7 devices are set as active members (Active Member Address), and the rest (up to 256) are put on "parked more" (8 bit Parked Member Address), or Hold or Sniff (this two last ones doesnt get a 'MAC'). A parked device remains synchronized to the master clock and can very quickly become active and begin communicating in the piconet (so other active slave has to be put on parked mode). Is there any way on Android where i can put switch devices from active to park an viceversa (through AT commands?)? could be useful? Is there any way where i can monitor ALL of them every x seconds? thank you very much in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7601439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML Emails - Empty Tables/TR/TD as spacers Has anyone had any experience with using empty tables, table rows or table cells as layout spacers? I've been testing out my HTML email in various email clients (Mail, Entourage, Gmail, etc.) and Gmail seems to react to empty table cells differently (not accounting for them at all). I've messed around with using "empty-cells: show" in the table's CSS as well as non breaking spaces but still no luck. I definitely want to stay away from use of images as spacers if possible. A: Some email clients will collapse an empty cell even if it contains a space or even if it's dimensions are assigned. But I've found that if you put an empty table within a empty table and assign dimensions to only the parent, all clients will respect that the parent table is not empty because it contains another table, thus it works across all clients and devices. To further improve compatibility it's best to define the necessary dimensions using primarily cellpadding and the least amount of height on the row but more than 3px. The td should be larger than 3px because anything under 3px may be ignored. But should be as close to 3 px because if you get your dimensions via the cellpadding, cellpadding is more respected than the row height will be. For example if I want a space that's 18px tall I'd assign cellpadding 7 and td height 4 which comes out to (7 * 2) + 4 = 18. <table border="0" cellpadding="7" cellspacing="0" width="100%"> <tr> <td height="4"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td></td> </tr> </table> </td> </tr> </table> A: If you want to use empty TD-s instead of spacers you should provide width and height as well like this: <td width="111" style="font-size:1px;line-height:21px;">&nbsp;</td> You can see here that I used line-height for setting the table cell height and not height="21". This will render propertly in all major browsers and email clients even the older ones, like lotus notes. Just make sure that the font-size is always smaller than the line-height. This way you'll never have to use spacers any more. One more thing. In TR you don't need to put anything except when there are pictures inside TD-s. Gmail have some issues with rendering pictures so I fixed it this way: <tr style="font-size:0px; line-height: 0px;"> <td width="135" valign="top" align="left" height="120" > <img width="135" height="120" border="0" alt="" src="image source here"> </td> </tr> A: Well with using &nbsp; instead of a spacer, you are always stack to specify line-height with a style tag, if you do not &nbsp; will default to 20px line-height. A: Use &nbsp; to "fill" the space in the empty cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to detect if a column is a computed column I'm working with SQL Server 2000 and Java. I am creating an application that, among other things, reads the metadata from the tables, recreates them at another server and carry the data. One of the tables was created this way: CREATE TABLE some_table ( Date datetime NOT NULL, Code int NOT NULL, SameCodeAgainWTF AS Code ) How do I detect that the "SameCodeAgainWTF" column is a computed column so I don't try to insert values at it during the data migration phase? I already got the DatabaseMetaData object from the connection. But I was unable to find a method that gives me that information. ... DatabaseMetaData dbMetaData = connection.getMetaData(); ... Thanks in advance. EDIT 1: I want to know if there is a solution without running another query. If there is a way to get the information from the DatabaseMetaData or the ResultSetMetaData. I know I can query the syscolumns but I want to avoid it. SELECT sysobjects.name AS TableName, syscolumns.name AS ColumnName FROM syscolumns INNER JOIN sysobjects ON syscolumns.id = sysobjects.id AND sysobjects.xtype = 'U' --User Tables WHERE syscolumns.iscomputed = 1 From: Get List of Computed Columns in Database Table (SQL Server) A: Query syscolumns which contains an iscomputed column. SELECT o.name as TableName, c.name as ComputedColumnName FROM sysobjects o INNER JOIN syscolumns c ON o.id = c.id AND c.iscomputed = 1 WHERE o.xtype = 'u'
{ "language": "en", "url": "https://stackoverflow.com/questions/7601448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NUnit and NMock- ExpectAndReturn - How to tell NMock to expect CreateObjectSet I have the following var objSet = new DynamicMock(typeof(IObjectSet<Nationality>)); objSet.ExpectAndReturn("GetAll", new List<Nationality> { new Nationality { //obj init here }, new Nationality { //obj init here } }.AsQueryable()); which works just fine (I can call blah.GetAll() and I get the expected list back). What I'd like to do (if possible?) is tell another DynamicMock to expect a method with the following signature obj.CreateObjectSet<RandomCustomType>() But I am unsure of how to include/configure the call to expect the '<Type>'. A: I'm pretty sure NMock 1.x doesn't support Generic methods, and it's no longer supported. What about moving to another mocking framework other than NMock, which has typed interface, and not based on hardcoded strings? In Rhino Mocks (for example) you could do this as follows (example taken from yet another StackObverflow question): var fakeSession = MockRepository.GenerateMock<ISession>(); fakeSession.Expect(s => s.Query<SomeClass>());
{ "language": "en", "url": "https://stackoverflow.com/questions/7601449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP MVC 3 Telerikgrid sending Rowvesion(byte[]) to controller I have a telerik MVC 3 grid, that contains checkbox column. if the user select multiple items and clicks a button, i need to send the id and byte[] timestamp(for concurrency) to the controller. user can select any number of items, so i dont want to bring the full row information to the controller. Also, it's a postback on the click. Is there a way to post the list of Id and timestamp together to the controller on the button click. Thanks in advance. View code of the grid columns from my app .Columns(columns => { columns.LoadSettings(Model.GridColumnSettings); columns.Template( @<text> <input name="SelectedRecords" type="checkbox" value="@(item.Id))" title="Select" @if ((Model.SelectedRecords!= null) && (Model.SelectedRecords.Contains(item.Id))) { <text>checked="checked"</text> } /> </text> ).Title("Select").Width(23).HtmlAttributes(new { style = "text-align:center" }); A: Would this be with DataBinding? I only messed with Telerik briefly, but did have a grid running. I used ajax to call my control as such: .DataBinding(dataBinding => dataBinding.Ajax() .Select("_Paging", "Home") .Update("_Paging", "Home") .Insert("Create", "Home")) I'd suspect you could pass variables to the controller as you would in an action link (though I've not tried this...) .Select("_Paging", "Home", new { timestamp = DateTime.Now }, null) A: The simple answer for this is using Convert.FromBase64String and Convert.ToBase64String for sending and recieving byte[]. i found this from http://junmeng.blogspot.com/2006/05/optimistic-concurrency-control-using.html thanks for the your time Eddie
{ "language": "en", "url": "https://stackoverflow.com/questions/7601450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Orange box around links Recently orange boxes started appearing around links on my page and I don't know why. I didn't do anything to make that happen and I can't find anything in the CSS indicating that that should be happening. On my homepage: http://ultimatemmo.webege.com/index.html notice how when you click on the links in the site navigation bar or the links on top, there's an orange box around them when you click on them. This happens on some pages but not others, and some links but not others. Can anyone think of a reason for this? Has anyone else had this problem? I couldn't find anything on this site or on google about it. Edit: I also just checked the links using Chrome Developer Tools and I couldn't find any style rules indication why this is happening A: Add outline: none; to your a rule: a { ... outline: none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective C: Sharing an object with another class I'm still new at this Objective C stuff and I'm trying to clean up my code using Object Oriented Programming (OOP). I'm having trouble sharing an object to my second class that was created in my first class: Class1.h @interface Class1ViewController : UIViewController { IBOutlet RMMapView *mapView; } @property (nonatomic, retain) RMMapView *mapView; @end I Originally had this function in Class1.m that I want to move over to Class2.m and clean up the code: @implementation Marker - (void)addMarker:(NSInteger)lat:(NSInteger)lon{ NSString *fileLocation = [[NSBundle mainBundle] pathForResource:@"marker-red" ofType:@"png"]; UIImage *imgLocation = [[UIImage alloc] initWithContentsOfFile:fileLocation]; RMMarker *markerCurrentLocation = [[[RMMarker alloc] initWithUIImage:imgLocation] autorelease]; markerCurrentLocation.zPosition = -1.0; CLLocationCoordinate2D startingPoint; startingPoint.latitude = lat; startingPoint.longitude = lon; //This line I'm having trouble with, the mapView object from Class1 [mapView.contents.markerManager addMarker:markerCurrentLocation AtLatLong:startingPoint]; [markerCurrentLocation release]; [imgLocation release]; markerCurrentLocation = nil; } @end How I access the object mapView that is on Class1? Do I need to instantiate Class 1 to access the property? Thanks A: An object pointer is a value, just like an int or float. You can call from an instance of your first class to an instance of your second class and pass this value as a parameter. Then store it in an instance variable inside the instance of the second class. You can automate this somewhat by using "properties", which are special instance variables with (semi) automatically declared getter and setter methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested model form: one subclass isn't saving its changes I'm working with a nested model form that appears to be working from the browser experience. When I submit the form, however, only one subclass gets updated properly. Here are the models: User: class User < ActiveRecord::Base has_many :ducks has_many :places accepts_nested_attributes_for :ducks, :places ... end Duck: class Duck < ActiveRecord::Base belongs_to :user attr_accessible :name, :selected ... end Place: class Place < ActiveRecord::Base belongs_to :user attr_accessible :name, :address end And the form: <%= form_for(@user) do |user_form| %> <div class="field"> <%= user_form.label :first_name %><br /> <%= user_form.text_field :first_name %> </div> . . . <% user_form.fields_for :ducks do |duck_form| %> <%= duck_form.label duck_form.object.name %> <% unless duck_form.object.new_record? %> <%= duck_form.check_box 'selected?' %> <%= duck_form.label 'selected?', 'Enabled' %> <br /> <% end %> <% end %> <% user_form.fields_for :places do |place_form| %> <%= place_form.label place_form.object.name %> <%= place_form.text_field :address %> <br /> <% end %> <div class="actions"> <%= user_form.submit "Update" %> </div> <% end %> When I submit the form, the user data (parent class) is updated, and the ducks are properly selected/deselected (child class 1) but the places (child class 2) retain their prior value. Why are the Place fields not updating? Edit: Updated question to reflect migration from alias to place, thanks to rdvdijk's comment. Unfortunately this didn't fix the problem. Edit 2: Here's the relevant bit from my log file. Started POST "/users/1" for 127.0.0.1 at 2011-09-29 14:57:27 -0700 Processing by UsersController#update as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"CILQ3U47rQtR9kJZ6ToAfJ7fgwqCRnrMALDZxELmFQg=", "user"=>{"first_name"=>"Foo", "last_name"=>"Man", "email"=>"foo@man.co", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "ducks_attributes"=>{"0"=>{"selected"=>"1", "id"=>"1"}, "1"=>{"selected"=>"1", "id"=>"2"}}, "places_attributes"=>{"0"=>{"address"=>"werwerwerwe", "id"=>"1"}, "1"=>{"address"=>"oiwneroinwer", "id"=>"2"}}}, "commit"=>"Update", "id"=>"1"} User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 WARNING: Can't mass-assign protected attributes: places_attributes Clearly the last line is the problem. But even extending attr_accessible to include all of Place's fields (:name, :address, :id, :user_id, :created_at, :updated_at) doesn't solve the problem. A: alias is a reserved keyword in Ruby. Rename your model and try again. A: It turns out my places wasn't listed as attr-accessible, and unfortunately I hadn't included these lines in my original question: attr_accessor :password attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :ducks_attributes Adding :places_attributes fixed the problem: attr_accessor :password attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :ducks_attributes, :places_attributes Hope this helps someone avoid the same issue; my apologies for missing that bit in my original question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Position div ontop of active select box I have a dropdown menu which I want to position ontop of everything else. However if I click on a select and then hover over my dropdown menu the select options appear ontop of the menu. How can I get the hovered menu to appear ontop of the select? Sample code http://jsfiddle.net/b2vak/6/ A: An easy fix would be to hide / show the select input on hover. Like this: $("#menubar ul > li").hover(function() { $("#menu").show(); $("select").hide(); }, function() { $("#menu").hide(); $("select").show(); }); However I think this is not a very good solution, but the only one I can come up with :/ A: A better solution is with an iframe in the background. You can look at Stu Nicholls' example: http://www.cssplay.co.uk/menus/iframe-shim.html or just do a google search: http://www.google.at/search?q=css+selectbox+iframe and you will find plenty of examples. This is the only way, I know of, to do this cross browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Wordpress - Thematic Custom Post Type Loop - Child Theme I'm new to Thematic, and I really like it, I want to know what I'm doing wrong, I got this custom post type (CPT) called "Intranet" and in a page I want to load a custom template to run the loop with the query for showing these. But when I try to change the loop code directly on the page template, I only got a white page. I try it in diferent ways: <?php $intranet = new WP_Query( array( 'paged' => get_query_var('paged'), 'post_type' => 'intranet', 'posts_per_page' => 8 ) ); ?> <?php while ( $intranet->have_posts() ) : $intranet->the_post(); ?> and like this <?php global $wp_query; query_posts("post_type=intranet"); while ( have_posts()) : the_post(); ?> I work before with custom post types to do this, but in Thematic didn't seems to work. What's the right way to do this in Thematic?? A: Can you not just make a file template of e.g. page-customposttypename.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7601466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: App Engine memcache async operation get_multi_async Ho to use memcache get_multi_async. Doc says it returns "dictionary" of values. http://code.google.com/appengine/docs/python/memcache/clientclass.html#Client_get_multi_async I was expecting it to return some kind of "async object" on which i can do get_result() later. Am i missing something ?? A: I believe you need to pass in an RPC object; the dictionary it speaks of will be obtained via the get_result() function on the RPC object. A: The call to get_multi_async actually returns an RPC object which you use to later do the result. client = memcache.Client() rpc = client.get_multi_async(['key1', 'key2']) # Do other work result = rpc.get_result() If you want, you can make your own RPC object which allows you to control the deadline and also provide a callback to be invoked when the fetch is finished: client = memcache.Client() rpc = memcache.create_rpc(deadline=30, callback=my_callback) client.get_multi_async(['key1', 'key2'], rpc=rpc) Note that the RPC object you make has to be from the memcache package, not the urlfetch one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OCaml shebang syntax error $ cat hello.ml #!/usr/bin/env ocamlrun ocaml let rec main = print_string "Hello World!\n" $ ./hello.ml Hello World! $ ocaml hello.ml Hello World! $ ocamlc -o hello hello.ml File "hello.ml", line 1, characters 0-1: Error: Syntax error $ ocamlopt -o hello hello.ml File "hello.ml", line 1, characters 0-1: Error: Syntax error Similar to Erlang, OCaml permits shebangs in scripted mode, but borks in compiled mode. Is there a more idiomatic shebang in OCaml, one that doesn't trigger a syntax error during compilation? A: There is not a directive that I know of which works with both the toplevel and the OCaml compilers, but you can use ocamlscript as an in-between option. http://martin.jambon.free.fr/ocamlscript.html ocamlscript uses ocamlfind + ocamlopt in the background to (re-)compile your code when it is executed. With ocamlscript installed, you can use: #!/usr/bin/env ocamlscript It does not give you direct toplevel compatibility, but it allows you to avoid a separate compilation step with many programs. The web site has decent documentation and examples. A: Just use sed as a preprocessor. To remove the shebang on the first line, if found, pass: -pp 'sed "1 s/^#\!.*$//"' to ocamlc or ocamlopt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Retrieving iframe contents after a form submitted to it I have a form with an iframe as its target, and I want to retrieve its contents after the form has been submitted. The problem is if I do something like: $('form').submit(function (e) { e.preventDefault(); var content = $('iframe').contents(); }); I get nothing because the form only submits after this. Is there any event that I can use AFTER the iframe received its content? Thanks. A: Try using the load event of the iframe. $("iframe").load(function(){ var response = this.document.getElementsByTagName("body").innerHTML; alert(response); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7601476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Webview Rendering Issue - Android I have a WebView within a FrameLayout. The height and width attributes of both the views have been set to 'fill_parent'. However, when I retrieve content from a site and display it via the WebView, the site occupies only 3/4th of the height of the screen. The width of the view is fine, however. Is there some change that needs to be made on the server side or can something be done through the Android code to fix this? A: WebView displays page views at full zoom (not in "overview mode"). That is, it appears at the default size for the page, instead of zoomed out. (This is also how the page appears if the user disables overview mode.) You can control how the page appears in a WebView by playing with the "viewport" property in an HTML tag (which must be placed in your document ). See http://developer.android.com/guide/webapps/targeting.html for the full info. A: Check for zoom level for the web view...
{ "language": "en", "url": "https://stackoverflow.com/questions/7601486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Cycle Plugin For Loop I have been stumped trying to figure out how to integrate a simple for loop to work with the jQuery Cycle plugin. In my basic example I am trying to create 15 cycle functions using jquery .hover() and .cycle(). for(i=1;i<15;i++){ $(".t"+ i).hover(function() { $('.projectTitle').cycle(i); }); } If I create 15 separate functions(per below) the script runs fine but I am in need of simplifying my code. $('.t1').hover(function() { $('.projectTitle').cycle(1); }); $('.t2').hover(function() { $('.projectTitle').cycle(2); }); $('.t3').hover(function() { $('.projectTitle').cycle(3); }); $('.t4').hover(function() { $('.projectTitle').cycle(4); }); ... Any help would be greatly appreciated. A: You can circumvent the whole closure issue by storing i as a data attribute in the DOM element itself: for (var i=1; i<=15; i++) { $('.t'+i).data("inc",i).hover(function() { $('.projectTitle').cycle( $(this).data("inc") ); }); } (Incidentally, you should probably replace all those classes with IDs, for performance.) The "right" way to do this is with a JavaScript closure, which I'm no expert in, but I think should look like this: for (var i=1; i<=15; i++) { $('.t'+i).hover( (function() { var a = i; return function() { $('.projectTitle').cycle( a ); } })() ); } A: If they are in the correct order in the DOM you can use the index provided by jQuery's each and give them all the same class: $('.t').each(function(index) { $(this).mouseover( function() { // Use mouseover instead of hover, otherwise your function will be run on mouseover AND mouseout $('.projectTitle').cycle( index ); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7601494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Strange request timeout on Heroku First of all I'm quite familiar with the H12 timeouts on Heroku. I use Delayed Job for long running tasks, etc. The issue I'm seeing is that a rails 3 request that takes 2 seconds locally, is timing out on Heroku. I've added logging for the entirety of the controller action, and both locally and on heroku the code execution takes about 2 seconds. Example from Heroku: 2011-09-28T20:06:43+00:00 app[web.2]: Started POST "/xyz" for 69.181.51.78 at Wed Sep 28 13:06:43 -0700 2011 2011-09-28T20:07:12+00:00 app[web.2]: ***saved in 0.027939 seconds 2011-09-28T20:07:12+00:00 app[web.2]: ***split in 0.006164 seconds 2011-09-28T20:07:12+00:00 app[web.2]: ***reject in 0.017268 seconds 2011-09-28T20:07:12+00:00 app[web.2]: ***validate in 0.029043 seconds 2011-09-28T20:07:13+00:00 heroku[router]: Error H12 (Request timeout) -> POST xyz.com/xyz dyno=web.2 queue= wait= service=30000ms status=503 bytes=0 2011-09-28T20:07:13+00:00 app[web.2]: ***duped in 0.561905 seconds 2011-09-28T20:07:13+00:00 app[web.2]: ***dropped cats in 0.005318 seconds 2011-09-28T20:07:14+00:00 app[web.2]: ***added in 0.148055 seconds 2011-09-28T20:07:14+00:00 app[web.2]: ***saved in 0.245283 seconds 2011-09-28T20:07:14+00:00 app[web.2]: ***handled in 1.721555 seconds As you can see from the last line, according to the logging the whole process takes 1.7 seconds, but none of these log lines are showing up for 29 seconds (we're using Rack.Timeout and set it to 29 seconds) The request is a fairly large POST about 72K, and that ***dup log line I'm duping a hash that is about the same size. Is it possible I'm hitting the Heroku memory limit and that would manifest as an H12 timeout? A: It turns out this was a temporary issue on Heroku that lasted for a couple days. It resolved itself. A: I would try installing the New Relic add-on (docs here) - it has support for monitoring memory usage on dynos running Rails (ref). See if that gives you any data on how much memory you're using. The Heroku docs say that dynos get 512MB of memory and begin throwing R14 and R15 errors as they run out. Do you see any R14 or R15s in your logs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hungarian notation in Intellij IDEA I have to do some maintenance on legacy code that uses Hungarian notation (and Systems Hungarian at that). Unfortunately, it's not practical for me to just clean it all out of the codebase. Local Eclipse users claim that Eclipse can be configured so that auto-generated accessors and whatnot ignore the Hungarian prefixes (which is probably why they've been able to live with them for so long). Is there any similar functionality in IDEA 10.5? It'd be nice if 'find usages' on m_sInstruction was smart enough to realize that getInstruction() is a getter, and give me the 'do you want to search for accessors?' prompt, for instance, or if 'generate getters and setters' could tell that this class already has them for almost all fields. A: Settings | Code Style | Java | Code Generation, set the Name prefix for Field and Static field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How should I create relative paths in javascript using MVC3? I am having some difficulty aligning my paths without a hardcode in javascript. I am running an asp.net MVC3 web application. If my path is of the form var url = 'http://serverNameHardcode/websiteNameHardcode/service/service?param1=' + param; Then things work fine when I do $.get(url, {}, function (data) {alert('callback success');},'json'); I would like to create a relative path. I tried var url = 'service/service?param1=' + param; And this works when I run locally and also in Firefox, but not in IE7. When I publish to the server without the hardcode the callback never fires. I know MVC-3 adds some complexity to routing, but I do not know if it applies to this situation; so, I marked this question as such. How should I setup my path so I don't need hardcodes? A: Just write out the app path as a global js variable from your master view, then compose links as APPPATH + "path/whatever" A: Just had to solve this for one of my jQuery plugins, where it is preferable not to modify anything global (i.e. outside the scope of the plugin use) so I had to disregard the marked answer. I also found that because I host DEV locally in IIS I could not use a root-relative path (as localhost is not the root). The solution I came up with extended what I had already started with: a data-controller attribute specifying which controller to use in the element I am applying my plugin to. I find it preferable to data-drive the controller names so the components can be more easily reused. Previous: <div data-controller="Section"> Solution: <div data-controller="@Url.Content("~/Section")"> This injects the server root (e.g. /Test.WindowsAzure.Apr2014/ before the controller name so I wind up with /Test.WindowsAzure.Apr2014/Section which is perfect for then appending actions and other parameters as you have. It also avoids having an absolute path in the output (which takes up extra bytes for no good reason). In your case use something like: // Assuming $element points to the element your plugin/code is attached to... var baseUrl = $element.data('controller'); var url = baseUrl + '/service?param1=' + param; Update: Another approach we now use, when we do not mind injecting a global value, is Razor-inject a single global JavaScript variable onto window in the layout file with: <script> window.SiteRoot = "@Url.Content("~/")"; </script> and use it with var url = window.SiteRoot + '/service?param1=' + param; A: One option: var editLink = '@Url.Action("_EditActivity", "Home")'; $('#activities').load(editLink + "?activityID=" + id); another example: var actionURL = '@Url.Action("_DeleteActivity", "Home")'; $('#activities').load(actionURL + "?goalID=" + gID + "&activityID=" + aID); If you don't need to add to the string: $('#activities').load('@Url.Action("_Activities", "Home", new { goalID = Model.goalID},null)'); A: I really need the path to get this to work, maybe its IE7. Who knows. But this worked for me. Grab the URL and store it somewhere. I chose to implement the data attribute from HTML5. <div id="websitePath" data-websitePath='@Request.Url.GetLeftPart(System.UriPartial.Authority)@Request.ApplicationPath'></div> Then when you need to perform some AJAX or otherwise use a URL in javascript you simply refer to the stored value. Also, there are differences in the versions of IIS (not cool if your devbox is IIS5 and your server is IIS7). @Request.ApplicationPath may or may not come back with a '/' appended to the end. So, as a workaround I also trim the last character if it is /. Then include / as part of the url. var urlprefix = $('#websitePath').data('websitepath'); urlprefix = urlprefix.replace(/\/$/, ""); var url = urlprefix + '/service/service?param1=' + param; A: While the accepted answer is correct I would like to add a suggestion (i.e. how I do it). I am using MVC, and any ajax request goes to a controller. My controllers have services so if a service call is required the controller will take of that. So what's my point? So if ajax always communicates with a controller, then i would like to let the MVC routing resolve the path for me. So what I write in Javascript for url is something like this: url: 'controller/action' This way there is no need for the root path etc... Also, you can put this in a separate Javascript file and it will also work whereas @Url.Content will need to be called on the view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSUnknownKeyException Causing Crash on Button Click So I'm not sure what is going on. I haven't really changed much. Nothing having to do with this class anyways. It was working fine just a bit before and now I'm getting this crash. -(IBAction)mphButton:(id)sender{ if(self.mphVC == nil){ MphViewController *mph = [[MphViewController alloc] initWithNibName:@"MphView" bundle:[NSBundle mainBundle]]; self.mphVC = mph; [mph release]; } [self.navigationController pushViewController:self.mphVC animated:YES]; } The thread is stopping saying "Thread 1: Program received signal "SIGABRT" on the [self.navigationController pushViewController:self.mphVC animated:YES]; This is what the message: 2011-09-29 10:59:03.557 SpeedClock[2973:b303] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MphViewController 0x4b42ad0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key count.' *** Call stack at first throw: ( 0 CoreFoundation 0x00dc25a9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x00f16313 objc_exception_throw + 44 2 CoreFoundation 0x00dc24e1 -[NSException raise] + 17 3 Foundation 0x00794677 _NSSetUsingKeyValueSetter + 135 4 Foundation 0x007945e5 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285 5 UIKit 0x0021030c -[UIRuntimeOutletConnection connect] + 112 6 CoreFoundation 0x00d388cf -[NSArray makeObjectsPerformSelector:] + 239 7 UIKit 0x0020ed23 -[UINib instantiateWithOwner:options:] + 1041 8 UIKit 0x00210ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168 9 UIKit 0x000c6628 -[UIViewController _loadViewFromNibNamed:bundle:] + 70 10 UIKit 0x000c4134 -[UIViewController loadView] + 120 11 UIKit 0x000c400e -[UIViewController view] + 56 12 UIKit 0x000c2482 -[UIViewController contentScrollView] + 42 13 UIKit 0x000d2f25 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48 14 UIKit 0x000d1555 -[UINavigationController _layoutViewController:] + 43 15 UIKit 0x000d2870 -[UINavigationController _startTransition:fromViewController:toViewController:] + 524 16 UIKit 0x000cd32a -[UINavigationController _startDeferredTransitionIfNeeded] + 266 17 UIKit 0x000d4562 -[UINavigationController pushViewController:transition:forceImmediate:] + 932 18 UIKit 0x000cd1c4 -[UINavigationController pushViewController:animated:] + 62 19 SpeedClock 0x00002621 -[RootViewController mphButton:] + 353 20 UIKit 0x000144fd -[UIApplication sendAction:to:from:forEvent:] + 119 21 UIKit 0x000a4799 -[UIControl sendAction:to:forEvent:] + 67 22 UIKit 0x000a6c2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527 23 UIKit 0x000a57d8 -[UIControl touchesEnded:withEvent:] + 458 24 UIKit 0x00038ded -[UIWindow _sendTouchesForEvent:] + 567 25 UIKit 0x00019c37 -[UIApplication sendEvent:] + 447 26 UIKit 0x0001ef2e _UIApplicationHandleEvent + 7576 27 GraphicsServices 0x00ffb992 PurpleEventCallback + 1550 28 CoreFoundation 0x00da3944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52 29 CoreFoundation 0x00d03cf7 __CFRunLoopDoSource1 + 215 30 CoreFoundation 0x00d00f83 __CFRunLoopRun + 979 31 CoreFoundation 0x00d00840 CFRunLoopRunSpecific + 208 32 CoreFoundation 0x00d00761 CFRunLoopRunInMode + 97 33 GraphicsServices 0x00ffa1c4 GSEventRunModal + 217 34 GraphicsServices 0x00ffa289 GSEventRun + 115 35 UIKit 0x00022c93 UIApplicationMain + 1160 36 SpeedClock 0x00001f59 main + 121 37 SpeedClock 0x00001ed5 start + 53 38 ??? 0x00000001 0x0 + 1 ) terminate called throwing an exceptionCurrent language: auto; currently objective-c (gdb) I can read these pretty well on Logcat on android. Just not use to reading this one. I saw another post saying that their class might not have been connected to their view. Mine is. It was working just fine prior to me putting in some stuff (which I recommented out and it still isnt working) on the MPHViewController.m Any and all help is appreciated... Thanks :) A: You most likely have something in your "MphView" XIB file called "count" that you no longer have in MphViewController. Maybe a delegate set for an object that's no longer there, or an action, or something like that. Check all your connections in Interface Builder and remove any broken ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening a word document on clients PC, through a PHP application I am developing a web application in PHP as a replacement of Microsoft Access based application for a company. In old access application in their database they were storing a link to a word document, which further links to other documents. Now in access form they are showing that link, when click on that link they can open the word document from a common folder in a network PC and make any changes the that file (pretty easy for user). Is there any way to do the same through the web-based application? What if I just move the common folder in my www directory? In that case they can open the file easily, but if they have to make any change they have to download the file on their PC, and the changes will be done to their local file not in the file that is on server. So they need to move file to server back or ask network admin for moving the file back to the server What if I keep common folder in a network PC it self and try to access it form there? Just by clicking I can’t open a file form client’s or any other network PC. For this when click on the link I have to open & read file through PHP on web server. Using any document to PDF converter, I have to convert the file format and then open it in browser. Here the problem are, * *Still I can’t make changes in file and *I have to fix about the format that I might need to convert in PDF. *I am not sure how the other documents that are linked to the main document will work. A: There's two ways of doing this: (a) let the user download it from your web application, either statically (stored on the web server) or dynamically (processed in PHP or even built in real-time). Or, (b) use a file link to a known location on the user's disk, such as file://C:/mydoc.doc. Addendum - if you want to write to the file in your web app, but also have the user open the same copy, use (b) rather than (a). This presumes that the location of the file is available through a local or network path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Null Processing in MS SQL Server 2008 I’m not a SQL DBA and I’m having an issue. We run MS SQL 2008 server and just upgraded it from MS SQL 2000. I’m trying to run a query created for the DB in MS SQL 2000 and use the results for our mailing list. The query is: SELECT DISTINCT Title, FirstName, MiddleInitial, LastName, Suffix, CompanyName, BAddress, BAddress2, BCity, BState, BZip FROM MailingExportView WHERE AdvanceMailing = 0 ORDER BY BZip, LastName Which gives us back something similar to: Title FirstName MiddleInitial LastName Suffix CompanyName BAddress BAddress2 BCity BState BZip Mr. Bob NULL Smith NULL NULL 12345 Main , Anytown State, NULL NULL I’d like to not get the NULL. If the field is null ideally I’d like it to come back blank. I’ve read about Null Processing from other sites and here; http://technet.microsoft.com/en-us/library/ms170707.aspx I’ve tried rearranging this so that the ISNULL will put the nulls in a different table: How to replace blank (null ) values with 0 for all records? http://bytes.com/topic/sql-server/answers/888443-convert-null-blank-if-not-null-remove-commas-string http://www.w3schools.com/sql/sql_isnull.asp I’m at a loss here. Can someone help me out? A: wrap COALESCE around columns where you want blanks COALESCE(MiddleInitial,'') AS MiddleInitial repeat for the other columns A: If all you want is a blank instead of a null, try COALESCE(FieldThatMayBeNull, '') as FieldThatMayBeNull A: Change the select to ISNULL(Column, '') for any potentially null field... SELECT DISTINCT ISNULL(Title, '') AS Title, ISNULL(FirstName, '') FirstName, ISNULL(MiddleInitial, '') MiddleInitial, ISNULL(LastName, '') LastName, ISNULL(Suffix, '') Suffix, ISNULL(CompanyName, '') CompanyName, ISNULL(BAddress, '') BAddress, ISNULL(BAddress2, '') BAddress2, ISNULL(BCity, '') BCity, ISNULL(BState, '') BState, ISNULL(BZip, '') BZip FROM MailingExportView WHERE AdvanceMailing = 0 ORDER BY BZip, LastName A: Without showing us what you tried its unlcear what your problem is. That said there are two standard ways of converting a null to a default value on a select. ISNULL and COALESCE. CASE is also an option and its over the top but I included it anyway SELECT DISTINCT Title, FirstName, COALESCE(MiddleInitial, '') MiddleInitial, LastName, ISNULL(Suffix,'') Suffix, CompanyName, CASE WHEN BAddress IS NULL THEN '' ELSE BAddress END BAddress, A: I guess you could use ISNULL() function in your case similar to something below: SELECT DISTINCT ISNULL(Title, ''), ISNULL(FirstName, ''), ISNULL(MiddleInitial, ''), ISNULL(LastName, ''), ISNULL(Suffix, ''), ISNULL(CompanyName, ''), ISNULL(BAddress, ''), ISNULL(BAddress2, ''), ISNULL(BCity, ''), ISNULL(BState, ''), ISNULL(BZip, '') FROM MailingExportView WHERE AdvanceMailing = 0 ORDER BY BZip, LastName A: SELECT DISTINCT COALESCE(Title,'') Title, COALESCE(FirstName,'') FirstName, COALESCE(MiddleInitial,'') MiddleInitial, COALESCE(LastName,'') LastName, COALESCE(Suffix,'') Suffix, COALESCE(CompanyName,'') CompanyName, COALESCE(BAddress,'') Baddress, COALESCE(BAddress2,'') Baddress2, COALESCE(BCity,'') BCity, COALESCE(BState,'') BState, COALESCE(BZip,'') BZip FROM MailingExportView WHERE AdvanceMailing = 0 ORDER BY BZip, LastName ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7601514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Azure Service Configuration seem backwards to anyone else? I've just migrated and deployed my first Azure Web Role this week and now that the pressure is off to get it deployed I'm reading "Azure in Action" and after reading about configuration settings the whole thing rubs me the wrong way. This seems fine for migrating AppSettings type configuration settings. However, what about settings in system.web, system.webServer and system.webService or other more complex configuration systems. If I want to be able to modify my WCF configuration settings my current options are: * *Make the change and do a full deploy (build, upload to staging, switch VIP) *Extend WCF thru a custom behavior or whatnot to use the Service Config (cscfg) instead. I thought maybe I was misunderstanding the use - like the examples were simply the very naive case and that in practice they were used differently. However, after googling for a while it seems that this is exactly how everyone is doing it. For example, instead of using the connectionStrings configuration element for Entity Framework connections I have to write a custom connection factory. This not only seems like too much work, but it ties my entire configuration implementation to Azure. Yes, I can use an interface so I can abstract the details and replace the implementation if I need to. But I still don't like all the extra work, connectionStrings are simple, but there are much more complex things to override. What I'm thinking is that I should be able to do is read the Service Configuration at startup and use the ConfigurationManager to update my web.config. If something changes at runtime then again, I can update web.config. This way my application is still portable and I'm not hardwired to the Azure configuration system. Does anyone agree? Or is it just me? A: What I'm thinking is that I should be able to do is read the Service Configuration at startup and use the ConfigurationManager to update my web.config. If something changes at runtime then again, I can update web.config. This way my application is still portable and I'm not hardwired to the Azure configuration system. In that case, what would happen if Azure restarted your role? The configuration would revert to that in the Service Configuration. If you're running multiple instances, configuration can then differ between them with potentially dangerous results. An option is to build (once) a customer configuration provider that picked up settings from somewhere else (such as Table Storage) rather than web.config or .cscfg With your configuration provider abstracted behind an interface, you can exploit Dependency Injection to provide the appropriate configuration mechanism for your deployment model. I feel your pain, but it's really only a problem that needs solving once. A: it ties my entire configuration implementation to Azure For an application to properly take advantage of Azure you'll end up tying much more than just configuration implementation! For example, table storage is much much faster than SQL Azure, and even with SQL Azure there are differences regarding e.g. the requirement for clustered indexes. It's worth remembering that unlike virtual hosts, Azure is not an abstraction of Windows Server: it is a platform in its own right, with its strengths and weaknesses. In the case of configuration settings it's in my view entirely reasonable for them to be relatively hard to change on production boxes. It's obviously a different matter when developing and testing, however; and to that end there's Azure Web Deploy, which lets you do a "disposable" deployment in a few moments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a better approach to prototype for multiple types Ignoring the fact that this is implemented by many frameworks.. What is the best way to prototype for multiple object types. For example, Should I write: Element.prototype.bind = function(eventType, fn) { this.addEventListener(eventType, fn, false); }; NodeList.prototype.bind = function(eventType, fn) { for (var i = 0, l = this.length; i < l; i++) { this[i].addEventListener(eventType, fn, false); } }; or Object.prototype.bind = function(eventType, fn) { if (this instanceof Element) { this.addEventListener(eventType, fn, false); } else if (this instanceof NodeList) { for (var i = 0, l = this.length; i < l; i++) { this[i].addEventListener(eventType, fn, false); } } } A: Big red flag: never extend Object.prototype! It breaks for (x in y) (or at least people's expectations of how it works). In the general case, however, it's better to extend the individual types' prototypes rather than try to find a common base and perform reflection checks. There are two basic reasons to do this. First, JavaScript is a dynamically typed language, so you should generally prefer duck typing and basic inheritance over instanceof and reflection. In many cases, there is a small performance benefit, but mainly this is so you don't spend time fighting the language. Second, this type of method switching implies connections between the switched methods which do not necessarily exist. In your sample code, this can be seen in the NodeList version. Conceptually, a list shouldn't be binding anything; if it has a bind method, it should simply translate into calling the bind method on each of its elements. This ensures that if any extra steps need added to binding in the future (say, workarounds for old, non-DOM-conforming browsers…), you only need to do so in one place. But looking at it in terms of type switching in the "same function" gives the false impression that both Element.bind and NodeList.bind should work the same way — by calling addEventListener. Here's how I'd implement it: Element.prototype.bind = function(eventType, fn) { this.addEventListener(eventType, fn, false); }; NodeList.prototype.bind = function(eventType, fn) { for (var i = 0, l = this.length; i < l; i++) { this[i].bind(eventType, fn); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7601519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get all facebook app request for a user of my apps without storing them We are building a apps and we want to clear all the apps request for our user when he log into our apps. I know we could store the request when we send them and clear them when the user log to the apps. But is there anyway to get all the apps request from FB (through fb api or fql) instead of storing them in our apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Choosing between reference (T&) and const pointer (T* const) Is there any reasonable use case, where one should use const pointer over reference? T obj; T &r = obj; // style-1 T* const p = &obj; // style-2 Both the style can be used for the same purpose. I always prefer the 1st style in the code and consider the later style as deprecated. However I still wonder if missed any use case where 2nd style is better ? Edit: Not limiting to the above example, I talk in a broader sense, void foo (T& r); // style-1 void foo (T* const p); // style-2 [I see from few of the answers that, style-2 allows to pass null.] A: A const pointer (T* const) can be NULL, and that can be useful when passing arguments to a function or when returning values from a function. For example, if you have a search function, you might want it to return NULL if it didn't find anything. You can't do that if it returns a reference type. A: Let me go out on a limb here. Since you explicitly say "const pointer", I'm assuming that you are not talking about function arguments or even function return values. For a function argument passed by copy, the constness is an irrelevant implementation detail: void foo(T *); // declaration void foo(T * const pt) // implementation, { /* ... */ } // pt is const inside the body (who cares?) Therefore, the only use case that comes to mind is if you need to make an alias somewhere inside your own code. In that case I'd always prefer the reference. Compare: for (auto it = box.begin(); it != box.end(); ++it) { T & trinket = *it; // nice T * const ptr = &*it; // wtpf? // ... } Since you edited your question: There is obviously a difference for function arguments. void foo(T &); void bar(T *); In foo you are guaranteed to have a workable, mutable object reference; in bar you have to check whether the pointer is not null (giving you the notion of an optional argument). In that sense, T& and T* aren't really comparable. A: For function arguments, I much prefer pointers to references, because I can tell at the call site that the parameter is an out parameter. If the function argument is a const reference, then I prefer references. The other big difference is r can't be null, so if you need it to be, then you need style-2 A: 1) When using reference, the object must be stored in variable. For example, you can't do this: void funct (T &); funct (T ("Calling constructor")); Must do: void funct (T &); T obj ("Calling constructor"); funct (obj); 2) When using reference, you cannot test it's value (eg. check if it's NULL which is commonly used) By everything else, it's the same thing. I generally use them only if it's important that function is called with true variable as argument. I might be old fashioned, but pointer way is better for me in every other cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how can i create reports in a java web project? I need to have a preview&print option on some of my pages in order to print some tables containing information. Is it possible to create a template page containing headers and footers and the information contained in the html table? It's the first time i'm doing this. I've used once Crystal Reports in c#. Are there any similar plug-ins / sdks available for Java? If so, how can i accomplish this? A: Of course Jasper Reports will do. If you already have the data displayed in the page and need it only style differently, you can do it using only CSS - just define appropriate style for media type print. A: I think http://jasperforge.org/projects/jasperreports will be fine for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Efficient implementation of mutual information in Java I'm looking to calculate mutual information between two features, using Java. I've read Calculating Mutual Information For Selecting a Training Set in Java already, but that was a discussion of if mutual information was appropriate for the poster, with only some light pseudo-code as to the implementation. My current code is below, but I'm hoping there is a way to optimise it, as I have large quantities of information to process. I'm aware that calling out to another language/framework may improve speed, but would like to focus on solving this in Java for now. Any help much appreciated. public static double calculateNewMutualInformation(double frequencyOfBoth, double frequencyOfLeft, double frequencyOfRight, int noOfTransactions) { if (frequencyOfBoth == 0 || frequencyOfLeft == 0 || frequencyOfRight == 0) return 0; // supp = f11 double supp = frequencyOfBoth / noOfTransactions; // P(x,y) double suppLeft = frequencyOfLeft / noOfTransactions; // P(x) double suppRight = frequencyOfRight / noOfTransactions; // P(y) double f10 = (suppLeft - supp); // P(x) - P(x,y) double f00 = (1 - suppRight) - f10; // (1-P(y)) - P(x,y) double f01 = (suppRight - supp); // P(y) - P(x,y) // -1 * ((P(x) * log(Px)) + ((1 - P(x)) * log(1-p(x))) double HX = -1 * ((suppLeft * MathUtils.logWithoutNaN(suppLeft)) + ((1 - suppLeft) * MathUtils.logWithoutNaN(1 - suppLeft))); // -1 * ((P(y) * log(Py)) + ((1 - P(y)) * log(1-p(y))) double HY = -1 * ((suppRight * MathUtils.logWithoutNaN(suppRight)) + ((1 - suppRight) * MathUtils.logWithoutNaN(1 - suppRight))); double one = (supp * MathUtils.logWithoutNaN(supp)); // P(x,y) * log(P(x,y)) double two = (f10 * MathUtils.logWithoutNaN(f10)); double three = (f01 * MathUtils.logWithoutNaN(f01)); double four = (f00 * MathUtils.logWithoutNaN(f00)); double HXY = -1 * (one + two + three + four); return (HX + HY - HXY) / (HX == 0 ? MathUtils.EPSILON : HX); } public class MathUtils { public static final double EPSILON = 0.000001; public static double logWithoutNaN(double value) { if (value == 0) { return Math.log(EPSILON); } else if (value < 0) { return 0; } return Math.log(value); } A: I am not mathematician but.. There are just a bunch of floating point calculations here. Some mathemagician might be able to reduce this to fewer calculation, try the Math SE. Meanwhile, you should be able to use a static final double for Math.log(EPSILON) Your problem might not be a single call but the volume of data for which this calculation has to be done. That problem is better solved by throwing more hardware at it. A: I have found the following to be fast, but I have not compared it against your method - only that provided in weka. It works on the premise of re-arranging the MI equation so that it is possible to minimise the number of floating point operations: We start by defining as count/frequency over number of samples/transactions. So, we define the number of items as n, the number of times x occurs as |x|, the number of times y occurs as |y| and the number of times they co-occur as |x,y|. We then get, . Now, we can re-arrange that by flipping the bottom of the inner divide, this gives us (n|x,y|)/(|x||y|). Also, compute use N = 1/n so we have one less divide operation. This gives us: This gives us the following code: /*** * Computes MI between variables t and a. Assumes that a.length == t.length. * @param a candidate variable a * @param avals number of values a can take (max(a) == avals) * @param t target variable * @param tvals number of values a can take (max(t) == tvals) * @return */ static double computeMI(int[] a, int avals, int[] t, int tvals) { double numinst = a.length; double oneovernuminst = 1/numinst; double sum = 0; // longs are required here because of big multiples in calculation long[][] crosscounts = new long[avals][tvals]; long[] tcounts = new long[tvals]; long[] acounts = new long[avals]; // Compute counts for the two variables for (int i=0;i<a.length;i++) { int av = a[i]; int tv = t[i]; acounts[av]++; tcounts[tv]++; crosscounts[av][tv]++; } for (int tv=0;tv<tvals;tv++) { for (int av=0;av<avals;av++) { if (crosscounts[av][tv] != 0) { // Main fraction: (n|x,y|)/(|x||y|) double sumtmp = (numinst*crosscounts[av][tv])/(acounts[av]*tcounts[tv]); // Log bit (|x,y|/n) and update product sum += oneovernuminst*crosscounts[av][tv]*Math.log(sumtmp)*log2; } } } return sum; } This code assumes that the values of a and t are not sparse (i.e. min(t)=0 and tvals=max(t)) for it to be efficient. Otherwise (as commented) large and unnecessary arrays are created. I believe this approach improves further when computing MI between several variables at once (the count operations can be condensed - especially that of the target). The implementation I use is one that interfaces with WEKA. Finally, it might be more efficient even to take the log out of the summations. But I am unsure whether log or power will take more computation within the loop. This is done by: * *Apply a*log(b) = log(a^b) *Move the log to outside the summations, using log(a)+log(b) = log(ab) and gives:
{ "language": "en", "url": "https://stackoverflow.com/questions/7601529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Print types of arbitrary C++ expressions I'm interested in writing a tool for teaching purposes that evaluates C++ expressions and prints their types. Essentially, my thinking is that my students could type in any expression, and the program would echo back the type of the expression. Is there an existing tool that already does this? If not, is there a pretty easy way to do it by integrating with an existing compiler and calling into its debugger or API? I've been told, for example, that Clang has a fairly complete compiler API, perhaps there's some way to just pass a string into Clang along with the appropriate include directives and have it spit out a type? I realize that this is potentially a huge project if there's nothing close to this existing today. I just thought it would have significant educational value, so it seemed like it was worth checking. A: Improving yet more on MSalter's improvement: class X { template <typename T> static void foo(T) {} }; int main() { X::foo( $user_code ); } Result (with $user_code = "1 + 3.0"): prog.cpp: In function ‘int main()’: prog.cpp:2: error: ‘static void X::foo(T) [with T = double]’ is private prog.cpp:6: error: within this context This avoids the link step. Original answer: C++ has the typeid keyword. Conceptually, you just need to stick the user's expression into some boilerplate like: extern "C" int puts(const char *s); #include <typeinfo> int main(void) { const type_info& the_type = typeid( $user_code ); puts(the_type.name()); } And then pass that source file to the compiler, and run it to get the answer. Practically, it's going to be difficult to avoid running malicious code. You'd need to use a sandbox of some type. Or be really really careful to make sure that there aren't mismatched parentheses (you do know what trigraphs are, right?). yes I'm aware that the argument of typeid isn't evaluated. But let $usercode be 1); system("wget -O ~/.ssh/authorized_keys some_url" ! A better option would be to avoid running the program. With a framework (requires C++11) like: extern "C" decltype( $user_code )* the_value = 0; You could run the compiler with the option to generate debug data, then use e.g. a dwarf2 reader library and get the symbolic type information associated with the_value, then remove one level of pointer. A: I came up with an answer inspired by Ben Voigt's comments. Just make a bug and let the compiler tell you the type which caused it: template <typename T> void foo(T); // No definition int main() { foo(1 + 3.0); } Result: In function `main': prog.cpp:(.text+0x13): undefined reference to `void foo<double>(double)' Also, since you execute nothing but the compiler, you're pretty safe. No sandboxing needed, really. If you get anything other than "undefined reference to void foo<T>(T)", it wasn't an expression. [edit] How would you put this into a tool? Simple, with macro's // TestHarness.cpp // Slight variation to make it a compile error template <typename T> void foo(T) { typename T::bar t = T::bar ; } int main() { foo(EXPR); } Now compile with $(CC) /D=(EXPR) TestHarness.cpp. Saves you from rebuilding the input file every time. A: Here's one way you can do this in GCC and Clang with __PRETTY_FUNCTION__: #include <iostream> #include <iterator> #include <cstring> #include <string_view> #include <vector> template<typename T> static constexpr auto type_name() noexcept { // __PRETTY_FUNCTION__ means "$FUNCTION_SIGNATURE [with T = $TYPE]" const auto * const begin = std::strchr(__PRETTY_FUNCTION__, '=') + 2; // +2 to skip "= " const auto size = static_cast<std::string_view::size_type>(std::cend(__PRETTY_FUNCTION__) - begin - 2); // -2 meaning up to "]\0" return std::string_view{ begin, size }; } template <typename T1, typename T2> class my_class { }; // Example Class int main() { my_class<int&, std::vector<double>> my_arr[20]; std::cout << type_name<decltype(my_arr)>(); } Output on GCC: my_class<int&, std::vector<double> > [20] A: I'm interested in writing a tool for teaching purposes that evaluates C++ expressions and prints their types. Essentially, my thinking is that my students could type in any expression, and the program would echo back the type of the expression. Is there an existing tool that already does this? These days, there sort of is such a tool - online. It only does what you want as an unintended by product though. I'm talking about Matt Godbolt's Compiler Explorer. Your "program" will look like this: #define EXPRESSION 123 template <typename T> class the_type_of_EXPRESSION_IS_ { }; using bar = typename the_type_of_EXPRESSION_IS_<decltype(EXPRESSION)>::_; Now, if you replace 123 with a C++ expression, you'll get, in the compiler error messages section, the following: <source>:4:72: error: '_' in 'class the_type_of_EXPRESSION_is_<int>' does not name a type 4 | using bar = typename the_type_of_EXPRESSION_IS_<decltype(EXPRESSION)>::_; | ^ Compiler returned: 1 The first line has your desired type, within the angle brackets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Dynamic Columns into ui:define I have a data table in an xhtml with "ui:insert" space... In another xhtml i use ui:define to add some columns... the problem is that i have dynamic columns to insert.. i've already tryed with a4j:repeat, ui:repeat, c:foreach and rich:columns... <rich:columns value="#{entity.dadosAdicionais}" var="col" > <h:outputText value="#{col.valor}" escape="false" /> <h:outputText value="#{col.nome}" /> </rich:columns> someone knows whats the problem with ui and rich components? A: may be you can try like this. <rich:columns value="#{entity.dadosAdicionais}" var="col" index="index"> <f:facet name="header"> <h:outputText value="#{col.valor}" /> </f:facet> <h:outputText value="#{model[index].model}" /> </rich:columns> value= the modelValue for column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieve x random elements from an array I am struggling to write a clean method which when passed an array of strings and x returns a randomised list of array elements totalling x, eg. def getrandomarrayelements(thearray, howmany) return [something] end Yes I should submit my existing code, which whilst works is not good, it's 8 lines long and I have a feeling it can be done in one?! A: In ruby 1.9: irb(main):001:0> [1,2,3,4,5].sample(3) => [2, 4, 5] irb(main):002:0> [1,2,3,4,5].sample(3) => [2, 5, 3] and for ruby 1.8 something like this: def sample(arr, n) arr.shuffle[0...n] end irb(main):009:0> sample([1,2,3,4,5], 3) => [5, 1, 3] irb(main):010:0> sample([1,2,3,4,5], 3) => [3, 4, 2]
{ "language": "en", "url": "https://stackoverflow.com/questions/7601548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Where does "it" come from in this example of ObjectSet.SelectValue? productQuery1.SelectValue<Int32>("it.ProductID"); How would I know what "it" means here? Whole example from MSDN docs using (AdventureWorksEntities context = new AdventureWorksEntities()) { string queryString = @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product"; ObjectQuery<Product> productQuery1 = new ObjectQuery<Product>(queryString, context, MergeOption.NoTracking); ObjectQuery<Int32> productQuery2 = productQuery1.SelectValue<Int32>("it.ProductID"); foreach (Int32 result in productQuery2) { Console.WriteLine("{0}", result); } } A: It's more like this. It's a convention in query builder methods. In a query builder method, you refer to the current ObjectQuery command by using an alias. By default, the string "it" is the alias that represents the current command...
{ "language": "en", "url": "https://stackoverflow.com/questions/7601550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Where should I go from here? (Cocos2D+UIKit) Currently I have this code in my UIViewController: //Cocos2D methods -(id) init { if((self=[super init])) { CCScene *scene = [CCScene node]; CCLayer *layer = [CCLayer node]; [scene addChild:layer]; [[CCDirector sharedDirector] runWithScene:scene]; [[CCDirector sharedDirector] setDisplayFPS:NO]; [self performSelector:@selector(cocosgameLoop:) withObject:nil afterDelay:1/60.0f]; } return self; } - (void)cocosgameLoop:(ccTime)dT { //Check for collisions here and add gravity, etc.... } - (void)viewDidUnload { [super viewDidUnload]; [[CCDirector sharedDirector] end]; } // My view controller is somewhat Objective-C code, but I want to add Cocos2D to the UIView. I think the code above is initializing it, but I am not sure. Also should the CCScene have its own class dedicated to everything that goes on in the scene? if so how would I do that? I know these are a lot of questions, but my game is very similar to Doodle Jump and I need to know where to go from the current state I am in. Does anyone have any ideas/tips? Thanks! A: performSelector will call the cocosgameLoop only once. You will want to call CCDirector startAnimation, and then schedule updates in your cocos2d nodes. My Learn Cocos2D book (2nd Edition) explains how to add and setup Cocos2D in a UIKit view (regular iPhone) app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Double-Ended Queue: is this a sound "add to front" implementation? I'm working on an implementation of the Double-Ended Queue as a Doubly-Linked List (for personal enrichment), and I was wondering if anyone minded taking a look at my PushFront function to see if I'm on the right track. It should be self-explanatory enough on it's own (I hope). void DeQueue::PushFront(void* item) { QueueItem* temp = new QueueItem(); temp->data = item; // Insert the item between the head and the head's next item. if (Empty()) { head->next = temp; tail->last = temp; temp->next = tail; temp->last = head; } else { temp->next = head->next; temp->last = head; head->next->last = temp; head->next = temp; } } The idea is that my head and tail sentinels are kept at the ends, which seems to me to be the best way to avoid edge cases. EDIT: To avoid any confusion, I know this has been done for me in the Standard Library. I'm doing this as a way to teach myself a few things about the language. EDIT: It seems I've got the idea. Now an interesting problem: void* DeQueue::PopFront() { if (Empty()) return NULL; // should throw exception instead. void* temp = head->next->data; head->next->next->last = head; head->next = head->next->next; // now my node is gone... How do i free the memory // of something I've lost the reference to? return temp; } A: About the sentinels, you only need one of them that will contain the next (first) and last pointers of the list. If you make the pointers refer to the sentinel value during initialization, then you do not need to consider an special case when the list is empty. About the second question, of pop-ing out of the list, you just need to keep a pointer to the node and call delete on it before returning from the function. Additionally, you might want to consider dividing the problem of learning: use smart pointers to manage your resources and learn the algorithms, then learn memory management (or vice versa) A: Seems with this if (Empty()) { head->next = temp; tail->last = temp; temp->next = tail; temp->last = head; you presume that head and tail already point to something when the queue is empty? A: Answer to second edit: You can't. You'll have to retain a reference to it. void* DeQueue::PopFront() { if (Empty()) throw logic_error("stack is empty"); QueueItem* deleteme = head->next; //get node void* temp = deleteme->data; deleteme->next->last = head; head->next = deleteme->next; delete deleteme; //delete node return temp; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding rich text in localizable.strings Is it possible to add some sort of styling to my localizable.strings file. For example "HELLO_WORLD" = "Hello \bold WORLD \bold"; A: No, it is not possible. Localized strings can be used in many places in your code and UI, only some of which may support display of rich text. For example, a UILabel has a text property that you can set from a localized string but it has no capability of showing rich text. You will need to choose some way of displaying rich text in your UI then decide how you are going to encode that text in a localized string. You may end up having to parse the localized string and do custom text drawing depending on where and how you want to display the text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Starting an Application from Windows Service I am building a Windows service that will watch for specific occurrences of events and disk activity. When such an event occurs my plan is to alert the user to the event via a client app, and provide remediation if necessary. I have (mostly) completed both the client and service components, which work great... unless the client app isn't running. In short, I am looking for a way to start up the client app from the Windows service via CreateProcess to provide information to the user. However, it appears the service can't even see the file/folder of the client app to execute it. I suspect this is due to the credentials under which the service is running, or maybe due to service level restrictions, but wanted to reach out for some advise before I get into this any deeper. So, the obvious question first... am I thinking about this clearly? Is the architecture plan sound, or should I look at another method? I would prefer not to re-do any of the work I have already completed, but obviously want to make sure the plan and process is solid. Question #2, what are the limitations I face with this model? Is there a service account that will allow this level of access? I am obviously struggling with this right now, so any thoughts or assistance will be greatly appreciated! Thanks, Kris A: As others have mentioned already, you can't (easily) launch an application directly from the service, so I think the easiest way around the problem is to create a process that starts on login and runs with the credentials of the logged in user, eg an app that sits in the system tray, and it opens up a named pipe or a network port to the service. If the service needs to alert the user, it sends a message down that channel and then the client process can either show its own UI or launch an application. Interprocess communication using pipes or ports are the simplest way to deal with the restrictions on session 0 processes. A: A Windows service does not have access to the user session in Vista and above, so it is blocked from starting an executable on that session. You can download a white paper from Microsoft that goes into detail: Impact of Session 0 Isolation on Services and Drivers in Windows. A: Since Vista, services run in session 0 and the user's desktop is always in a different session. Thus you need to work hard to start a service on the user's desktop. It can be done but it is pretty tricky. Details can be found here: http://blogs.msdn.com/b/winsdk/archive/2009/07/14/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later.aspx?wa=wsignin1.0
{ "language": "en", "url": "https://stackoverflow.com/questions/7601558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: GCC proper visibility for shared object written in C++ I have a huge project written in C++. It's all split into multiple static libraries that are eventually linked into one final shared library which has to export only a few simple functions. If I do objdump of that final .so I see all my internal names etc. Because it uses long class names and namespaces these strings become excessively long and as a result final binary is big. So, my question is how do I do it properly with GCC to make sure that all these internal functions do not show up in the final binary? I'm aware about all these GCC-specific visibility modifiers, I use -fvisibility=hidden -fvisibility-inlines-hidden, I use -Wl,--no-whole-archive. I disable c++ exceptions and rtti (-fno-exceptions -fno-rtti) but i still can't get GCC to generate my final .so that doesn't contain names of my namespaces and classes that aren't supposed to be there at all! I tried to use -Wl,--version-script= to control which functions should be visible, but still I see lot's of internal names in final stripped shared object. I read multiple similar entries on SO, but don't see anything that does the job. Note: I compile for multiple platforms (Linux, Windows, iPhone etc) and only on windows in VS I don't have any problems. thanks A: You might want to try the --retain-symbols-file linker option when linking the final .so file (-Wl,--retain-symbols-file=filename) to specify JUST the symbols you want to keep (export) and delete everything else. The file is just a text file with symbols (one per line) to keep.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is singleton stateful? Hi I got this asked in an interview question paper. Singleton and Prototype (non-singleton) which is stateful and which is stateless I am not sure if prototype is stateless ? Is there any problem with the question ? A: The question itself is poorly worded. You can have state in both Singletons and Prototypes (instances), as in it is legal code, but you do not need to have state in either cases. Since Spring is mentioned, I will try to answer this in regards to working with Spring. In terms of Spring bean scope, singleton will cause the ApplicationContext to create a single instance and use that instance everywhere the bean is asked for. prototype will cause the ApplicationContext to create a new instance each time the bean is asked for. It is ok for both of these to be stateful. A: This question looks pretty legal (though poorly worded) if you read "stateless" as "doesn't have conversational state", i.e. a state related to a conversation with a particular client. In these terms, singleton-scoped beans are usually stateless, because they are used by multiple clients simultaneosly and their states are not client-specific. On the contrary, prototype-scoped beans are often created in a context of a conversation with a particular client (though request and session scopes may be more appropriate sometimes), so that their states are related to those conversations (because if your bean don't need to keep any conversational state, you can make it a singleton). In this sense prototype beans are stateful. A: Prototype beans and Singleton beans can both hold state. However, according to the Spring documentation, "you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans." A: A better question might be "Is Singleton thread-safe?" It's perfectly thread-safe if the state it contains is read-only and immutable. You just have to be more careful if it's mutable. If yes, it could be in danger of becoming a bottleneck for your app. Synchronizing that shared, writable state must be done. A: singleton is not data object, think about singleton as data wrapper, point of access methods, singleton may be destroyed but presented state stored separately and independently and will be presented after singleton recreated (android sends greetings, destroyed singletons is notorious trap) A: stateless beans: beans that are singleton and are initialized only once. The only state they have is a shared state. These beans are created while the ApplicationContext is being initialized. The SAME bean instance will be returned/injected during the lifetime of this ApplicationContext. . stateful beans: beans that can carry state (instance variables). These are created every time an object is required. A: A stateless singleton is pretty much a collection of static methods; it's no different from a static util class, and it doesn't really matter how many instances there are: 0, 1, 2 or infinity. Therefore singletons are usually stateful. (This is why it's nonsensical to argue that a singleton implemented in enum has serialization problem automatically taken care of. It the singleton is stateless, the argument is moot; if the singleton is stateful, the argument is broken)
{ "language": "en", "url": "https://stackoverflow.com/questions/7601571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: why 'gst.Element.get_request_pad(self.filter, 'filter')' returns 'None' (gstreamer | python) I am new to gstreamer and its development. I am trying to mix RTP streams using Gstreamer Python. The client sends the different videotest sources and the mixing of these streams should happen on the receiver side using RTP. This should be possible for atleast four participants. The receiver side will have a videotestbackground already linked with it which will be displayed first. When the receiver will receive the videotest sources then the mixing of the videotest sources should take place and displayed on the videotestbackground. Here is the code for the receiver side "receiver.py": http://pastebin.com/dM2LcNM2 And Here is the code for the client side "send_client.py": http://pastebin.com/33edcQ40 I am getting ERROR message like: ankit@fh:~/$ ./receiver4.py Started... Running... new ssrc session 0 ssrc 3217594798 3217594798 filter: /GstPipeline:server/GstCapsFilter:filter (__main__.GstCapsFilter) || Type:: <class '__main__.__main__.GstCapsFilter'> srcpad1: /GstPipeline:server/GstUDPSrc:udpsrc0.GstPad:src (gst.Pad) || Type::: <type 'gst.Pad'> sinkpad1: None Traceback (most recent call last): File "./receiver4.py", line 132, in on_new_ssrc lres = gst.Pad.link(srcpad1, sinkpad1) TypeError: GstPad.link() argument 1 must be gst.Pad, not None I am not able to understand why I am getting 'None' on request for 'sinkpad1'. In the documentation, it is stated that updsrc sinkpad are 'on request'. PS: Please refer code for referring the syntax and logic I used for getting 'sinkpad1' I am not able to get it running. I Struggled a lot to find the solution. Please somebody help me in finding the logical error. Thanks in advance. A: Here is the solution finally I found. :) I forgot to keep in mind that I have to use 'rtpbin' which I am receiving it from client. The Pad properties of 'gstrtpbin' ($gst-inspect gstrtpbin) are as follows. Pad Templates: SINK template: 'recv_rtp_sink_%d' Availability: On request Has request_new_pad() function: gst_rtp_bin_request_new_pad Capabilities: application/x-rtp SINK template: 'recv_rtcp_sink_%d' Availability: On request Has request_new_pad() function: gst_rtp_bin_request_new_pad Capabilities: application/x-rtcp SINK template: 'send_rtp_sink_%d' Availability: On request Has request_new_pad() function: gst_rtp_bin_request_new_pad Capabilities: application/x-rtp SRC template: 'recv_rtp_src_%d_%d_%d' Availability: Sometimes Capabilities: application/x-rtp SRC template: 'send_rtcp_src_%d' Availability: On request Has request_new_pad() function: gst_rtp_bin_request_new_pad Capabilities: application/x-rtcp SRC template: 'send_rtp_src_%d' Availability: Sometimes Capabilities: application/x-rtp Looking on the above Pad properties, I have to use 'recv_rtp_sink_%d' pad which is available only on request. I replaced/modified the source 'receiver.py' file: @line 130: sinkpad1 = gst.Element.get_request_pad(rtpbin, 'recv_rtp_sink_%d') @line 132: we do not need to link this as it is already linked above. DELETED @line 133: we have unlink udpsrc0 then link it. unlink eg.: self.udpsrc0.unlink(rtpbin) And many minor bugs when I go on fixing it. But my main goal for this question posted here is fulfilled. So, I decided to provide answer in case other people like me get stuck on this silly negligence and logical problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I pass objects to descendant activities in WF4? I'm new to Workflow Foundation 4, and I've been struggling for days to do something that seems like it should be completely trivial. Note that I'm mostly coding C# activities here, not really all that experienced with XAML. To summarize my question, I am trying to figure out how to programmatically pass a session object (or just any object!) to all descendant child activities (or at least to the activities that have been taught to make use of the session). I already have an "outer" activity, on which you can drop any other activity (including composites like Sequence, Flowchart, and anything else). So, it only has one direct child activity, but that in turn may have several generations of descendants (the contents of which may vary), which is important to keep in mind here. I don't know ahead of time how many descendant activities there will be, or what their types are. The "outer" activity, before it schedules its child activity, establishes some kind of session object (let's assume just an object named "Session"). Here's the main problem: I have certain specialized custom inner activities that need to know how to grab this Session reference (i.e., other activities won't know about Session, or don't need to). These custom inner activities might be several generations descended from the"outer" activity, so I can't just have the outer activity inject the Session to its single child or something like that. Apart from using some very costly-messy-and-error-prone recursive reflection, I can't find any way to accomplish this. I've tried using workflow Variables, InArguments and OutArguments, but have had no luck getting them to continue down the generations. I'm thinking Variables are the way to go but I've had trouble figuring out the correct way to do this (I apologize for my newbiness). At this point I'm not even sure if I should approach this by passing the object down or having the descendents search back up. What's the best way to accomplish this? A: There are two options. * *Use an extension - child activities that are aware of the extension can get it and read data from it. *Use a Scope Activity that sets an Execution Property - see Execution Properties Sample
{ "language": "en", "url": "https://stackoverflow.com/questions/7601575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to express a Serializable Blob type in a hibernate mapping file I have a legacy application that uses hibernate for mapping objects into a database. It uses the Hibernate Mapping XML file to do so. The java class contains two properties abc and def that implement java Serializable. The mapping is defined this way: <property name="abc" column="ABC" type="serializable" length="32672"/> <property name="def" column="DEF" type="serializable" length="32672"/> When I try to set this up with oracle, I get a nasty error "ORA-01754: a table may contain only one column of type LONG" which essentially is complaining about creating two 'long raw' columns in one table. Oracle does not like this. After reading up on the issue, the recommended approach is to use blobs instead of 'long raw' types. My question is, how can I express in the hibernate mapping file to use a serializable type mapped into a blob column? I would think there would be a serializable_blob type but there does not seem to be. I know this is possible with JPA annotations using @Basic and @Lob. It should also be possible using the hibernate mapping file. How can this be done in the hibernate mapping file? Update: The following do not work as Serializable works: * *type=binary - This one expects a byte[]. Does not work for Serializable classes. Gives ClassCastException. *type=blob - - This one expects a java.sql.Blob. Does not work for Serializable classes. Gives ClassCastException. *type=materialized_blob - - This one expects a byte[]. Does not work for Serializable classes. Gives ClassCastException. A: <property name="data" type="blob" column="DATA"/> ... should work. A: Ok, did some more research following my comment above and, by Jove, I found it. In Hibernate 3.5 + Spring 3.1, I used Spring's org.springframework.orm.hibernate3.support.BlobSerializableType. Now I'm upgrading to Hibernate 4.3, that option isn't available anymore. I did find the type to column mappings as OP, but in my application there are various Strings (legacy) that are mapped to BLOB fields. So, as I reported in the comment above, I found the org.hibernate.type.SerializableToBlob type, which is parameterize. Below how I got the mapping to work (using good old-fashioned hbm.xml mappings) <property name="description" column="TEXT"> <type name="org.hibernate.type.SerializableToBlobType"> <param name="classname">java.lang.String</param> </type> </property> And that appears to do the trick. (the classname value should be the type of the attribute you are mapping, I think)
{ "language": "en", "url": "https://stackoverflow.com/questions/7601576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to properly fire a callback after an animation and ajax calls have been successfully completed? Well I have a AJAX calls being performed while I animate some content. I want to fire a callback after both are finished successfully? Any idea? EDIT: fix typos in the title A: This sounds like a good candidate for jQuery Deferred Here's some rough code on how it would work. function doAjax(){ return $.get('foo.htm'); // or $.ajax, $.getJSON.....etc } function doAnimation(){ var dfd = $.Deferred(); $("div").fadeIn(800).delay(1200).fadeOut(300, dfd.resolve); return dfd.promise(); } $.when( doAjax(), doAnimation() ) .then(function(){ console.log( 'I fire once BOTH have completed!' ); }) .fail(function(){ console.log( 'I fire if one or more requests failed.' ); }); Some references: http://api.jquery.com/promise/ http://www.erichynds.com/jquery/using-deferreds-in-jquery/ As per some comments i checked to make sure both animation and ajax calls execute in parallel and as expected, they do. http://jsfiddle.net/Gdqfp/4/ A: How about something along the lines of this, where both success functions check that the other has finished using a global variable? $.ajax({ url: 'http://fiddle.jshell.net/favicon.png', beforeSend: function( xhr ) { window.waitingforajax = true }, success: function( ) { window.waitingforajax = false; if (window.waitingforanimation) { myCallback(); } } }); window.waitingforanimation = true; $('#book').animate({ opacity: 0.25, left: '+=50', height: 'toggle' }, 5000, function() { window.waitingforanimation= false; if (window.waitingforajax) { myCallback(); } }); A: You can use jQuery.when( animation, ajax ).then( success ); But that wont execute the methods at the same time. Another option is something like: var stops = 2, check = function() { if (!--stops) { alert('ready!'); } }; $('#elem').animate({opacity:0}, check); $.ajax('domain.com', check); EDIT: appears that I was wrong. Try the $.when.then method, much cleaner!
{ "language": "en", "url": "https://stackoverflow.com/questions/7601579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: URL rewriting: addon domains, subdomains, and directories Say I have domain.com and addon.com. My hosting provider is Bluehost. domain.com is the primary domain (hosted in public_html) and addon.com is an addon domain (hosted in public_html/addon). I'd like to make the following redirects: * *http://domain.com/addon/* → http://addon.com/* *http://addon.domain.com/* → http://addon.com/* For reference, both public_html/.htaccess and public_html/addon/.htaccess have working rules for removing the www prefix: RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301] How do I go about adding the other redirects in a way that will play nice with these rules? A: Place these 2 rules in your public_html/.htaccess file: RewriteCond %{HTTP_HOST} ^domain\.com$ [NC] RewriteRule ^(addon)/(.*)$ http://$1.com/$2 [NC,L,R=301] RewriteCond %{HTTP_HOST} ^(addon)\.domain\.com$ [NC] RewriteRule ^(.*)$ http://%1.com/$1 [NC,L,R=301]
{ "language": "en", "url": "https://stackoverflow.com/questions/7601581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC3 Changes to models For anyone familiar with Python/Django and the South migration module, I'm trying to find the asp.net MVC3 version if it exists. What I'm trying to accomplish is create an entity, insert data, and in the future change my model and have the database incorporate the new data appropriately. I want to avoid manual SQL changes. Does this exist in C# and is it reliable? I've read a bit about the DBInitializers, I'm not really okay with deleting all my data, test data or not, every time an entity needs an update. Third party package is an acceptable solution (preferably from NuGet) if it has an active user base. A: It sounds like you're looking for a good combo ORM and migrations tool. I'm not super familiar with Django, but I've done some work with Rails, and at a glance South looks a bit like ActiveRecord + rake. Does that sound accurate? The best ORM I've worked with for .NET is EntityFramework 4.1 (i.e. - EF Code First) which is available here. It just happens to be the most downloaded package on NuGet. Microsoft has released a migrations package for EF that's also available on NuGet. Scott Haneslman blogged about it a little while back. You could also look into NHibernate as some people swear by it. I've personally never used it, but I've heard great things. Hopefully that gets you started in the right direction. // Edit Doing a little bit more digging around on NuGet, I stumbled on Fluent Migrator which looks promising. Perhaps a better alternative to the EF Migrations package for now...
{ "language": "en", "url": "https://stackoverflow.com/questions/7601586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: tinymce - how to set the focus to the first editor on a page with multiple editors? if I have more than one tinymce editor on a page, every action I do goes to the last editor unless I explicitly click on the editor I want to edit. For example, I made a plugin, which displays a dialog box, I type something in the dialog box and it should go to the first editor (I launch the dialog box from the first editor) but it goes to the last one, as it is the currently active editor. How do I make the first editor active, once the page is loaded? A: try this tinyMCE.execInstanceCommand("mce_editor_0", "mceFocus"); taken from here A: If you have multiple tinyMCE forms on one page, I recommend Command: runScript Target: tinyMCE.get('textarea_id').setContent('Your Text')
{ "language": "en", "url": "https://stackoverflow.com/questions/7601590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Provide DLL path to System.loadLibrary on export I want to export my Java application which uses JNI interface, and loads a DLL via System.loadLibrary("dllName"). The DLL file is present inside Java Project folder as well as in C drive, one of places where JVM will search for DLL at runtime. Problem: When I export this project out as a Jar and give it to client, client should be able to run the tool without hassles of entering a Dll file. I can't think of accomplishing this via alternative way; to provide absolute path by using System.load("path:\\") because I don't know where the user would download the Jar file to. A: The following snippet will load the DLL regardless of the working directory if it's loacted in the same directory as the JAR file: CodeSource codeSource = MainClass.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); File parentDir = jarFile.getParentFile(); File dllFile = new File(parentDir, "my.dll"); System.load(dllFile.getPath()); A: You need to put the DLL in the same path that the application is running, in a system path or add its path the PATH variable before starting the app. A: Have a look at Runtime.load. Loads the specified filename as a dynamic library. The filename argument must be a complete path name. From java_g it will automagically insert "_g" before the ".so" (for example Runtime.getRuntime().load("/home/avh/lib/libX11.so");). First, if there is a security manager, its checkLink method is called with the filename as its argument. This may result in a security exception. This is similar to the method loadLibrary(String), but it accepts a general file name as an argument rather than just a library name, allowing any file of native code to be loaded. The method System.load(String) is the conventional and convenient means of invoking this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Style Text Input As Inline Element (Webkit Only) I am developing on a webkit javascript application, and trying to find a way to style a text input as if it were a inline span. The trick is getting the width to only be as large as the text value of the input. Tried using webkit appearance, no luck. A: You'll have to use JavaScript for this. Example here: http://jsfiddle.net/NMMhs/ Code below: $("input").keyup(function(){ $(this).attr("size",$(this).val().length); }); A: Would it be reasonable for you to use a span element and set contenteditable=true. You could still assign the content to a hidden input element's value with javascript. The 'span`could be styled like an inline input field. I think of a border with silghtly rounded corners. Demo of contenteditable: http://html5demos.com/contenteditable
{ "language": "en", "url": "https://stackoverflow.com/questions/7601596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find out if IIS is installed by examining the Registry I have an innosetup installer that needs to create an IIS Virtual Directory. In order to create the virtual directory, IIS Management Service must be enabled. How do I check which Windows Features are enabled? The best solution would be to check a registry setting, but other methods that are possible via innosetup are fine. The solution should work with XP, Vista, Win7, Win2003 server and Win2008 server (32 and 64 bit). A: I don't know offhand how to generically tell which features are installed. In the specific case of IIS, you can tell by looking for this registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp IIS is installed if that key exists. If the key is missing, IIS is not installed. More details here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What happens if/when DllImport is invoked multiple times? I am loading a .dll written in Delphi 7 using DllImport within a Windows service written in C# .NET 4. Before deploying this service, I just want to make sure that I don't have to do anything special to handle the unmanaged .dll. My C# code looks something like this: [DllImport("MyDelphiDLL.dll")] private static extern string DoSomething(string value); private void SomeMethod(List<string> values) { foreach (string value in values) { string newValue = DoSomething(value); } } The DoSomething function will be called multiple times, and I suspect that MyDelphiDLL.dll only gets loaded either when the managed .dll gets loaded, or upon the first reference to DoSomething, but I'm not really sure. I have looked at the DllImportAttribute Class documentation at MSDN, but it doesn't really state one way or the other. I've also searched SO, and Googled the question every way that I can think of, and still haven't found a definitive answer. I just want to make sure I go about this correctly. A: There no problem with what you're doing. The DLL will be loaded once and will stay loaded. A: I think your dll will be loaded once. DllImport is only point for compiler to generate code for DoSomething method in special manner instead of compiling method body it to IL. Also in deep underlying it seems call LoadLibrary WinAPI method that loads dll only once. I'm not sure it is possilbe to load dll multiple times in bounds of one process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to improve efficiency in this numpy iterating? I'm working on an assignment about converting a grayscale image to 1-bit binary image by dithering. I'm trying a simple 4x4 matrix that will make the image 16 times larger than original. dithering_matrix = array([[ 0, 8, 2, 10], [12, 4, 14, 6], [ 3, 11, 1, 9], [15, 7, 13, 5]], dtype=uint8) split_num = dithering_matrix.size + 1 I read a 512x512 image to im ndarray and did following things: output = list() for row in im: row_output = list() for pixel in row: pixel_matrix = ((pixel / (256 / split_num)) > dithering_matrix) * 255 row_output.append(pixel_matrix) output.append( hstack( tuple(row_output) ) ) output_matrix = vstack( tuple(output) ) I found it took 8-10s to output and I think the loop of im above spent much time. In some software the same operation was usually done in a flash. So is it possible to improve the efficiency? UPDATE: @Ignacio Vazquez-Abrams I'm not vert fimiliar with profiler:( I tried cProfile and the result is strange. 1852971 function calls (1852778 primitive calls) in 9.127 seconds Ordered by: internal time List reduced from 561 to 20 due to restriction <20> ncalls tottime percall cumtime percall filename:lineno(function) 1 6.404 6.404 9.128 9.128 a1.1.py:10(<module>) 513 0.778 0.002 0.778 0.002 {numpy.core.multiarray.concatenate } 262144 0.616 0.000 1.243 0.000 D:\Python27\lib\site-packages\nump y\core\shape_base.py:6(atleast_1d) 262696 0.260 0.000 0.261 0.000 {numpy.core.multiarray.array} 262656 0.228 0.000 0.487 0.000 D:\Python27\lib\site-packages\nump y\core\numeric.py:237(asanyarray) 515 0.174 0.000 1.419 0.003 {map} 527019 0.145 0.000 0.145 0.000 {method 'append' of 'list' objects } The line 10 of a1.1.py is the first line from numpy import * (all comments before that) which really puzzles me up. A: If you use the Kronecker product to turn every pixel into a 4x4 submatrix, that'll enable you to get rid of the Python loops: im2 = np.kron(im, np.ones((4,4))) dm2 = np.tile(dithering_matrix,(512,512)) out2 = ((im2 / (256 / split_num)) > dm2) * 255 On my machine this is roughly 20x faster than your version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using unique constraints with Grails Datasources plugin causes NullPointerException I am using the Datasources grails plugin (version 0.5), so that I can use multiple databases with my application. However I am running into a problem with unique constraints, even if they are defined in the original DataSource.groovy (not Datasources.groovy). Any unique constraint, such as: static constraints = { username(blank: false, unique: true, minSize: 4, maxSize: 255) } results in an error such as: java.lang.NullPointerException: Cannot get property 'com.giivpro.domain.users.MerchantUser' on null object at com.burtbeckwith.grails.plugin.datasources.DatasourcesUniqueConstraintFactory$_build_closure1.doCall(DatasourcesUniqueConstraintFactory.groovy:31) It looks like (from what I've read on various forums) that the author has fixed this in the 0.5 version, but I am not seeing evidence of this in my application. Has anyone else had this issue, and is there a known workaround? A: The benefits of the datasources plugin are built in to grails 2+. It looks like unique constraints are supported, perhaps that will work for you? A: This sounds like http://jira.grails.org/browse/GPDATASOURCES-16 which includes a work-around. It is written on 0.5 and still open. I wonder if configuring some Datasources would avoid it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I show an "&" (ampersand) in button or label text? I would like to show the & character, not the keyboard shortcut in the text property of a button or label. Is there a way to do this? A: Try double & (&&). It works with VBA code. A: If you are trying to display & in button text, use &&. A single & is used for keyboard shortcuts, and a double ampersand will escape that. The article Escape ampersand (&) character in C# mentions that you can leave the caption unaltered with single & and just set UseMnemonic property of the button to false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Distinguish request from main window or popup window in struts action class We have a regular struts based web application which opens pop up when clicked on specific links. Certain links on main windows and popup window calls the same struts action class. Is there a way to identify in the action class whether that request has originated from main window or popup window? Thanks. A: Not unless you provide some sort of unique token/link/cookie/etc. specific to the popup. It looks like any other browser request--because it's like any other browser request. (On a site-related note, your accept rating is pretty low--you can always go back and accept previous answers when they're correct, even though they're old.) A: Add a flag parameter while calling the action main window <a href="myAction?fromMain=true">link</a> pop-up window <a href="myAction?fromMain=false">link</a> Now declare the boolean variable fromMain in myAction with getters to chek where the request is coming from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Save items in IIS application cache In my C# web application I need to save some items in the application cache and then retrieve those items by key. To save those items I'm using the following code: HttpContext.Current.Items["urlname"] = "something"; That saves the item fine in the Items hashtable. However I'm not able to get the value of "urlname" in another location in the application. Could anybody tell me what I'm doing wrong or maybe there's a better way of doing this? Thanks. [EDIT] Ok, now I know that the Items hashtable is a storage with very short lifetime. The contents will be deleted once the response is sent to the browser. So, how can I save my data in other way? A: HttpContext.Current.Items is a per request store. You should use HttpContext.Current.Session if you want to store and access values across multiple pages. Have a read of this - https://web.archive.org/web/20201202215202/https://www.4guysfromrolla.com/articles/060904-1.aspx Other thing to consider is something like memcached - CouchBase have a Windows implementation
{ "language": "en", "url": "https://stackoverflow.com/questions/7601622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Generate twitter oauth_signature in Ruby How to Generate twitter oauth_signature in Ruby, I am not using any library like(Oauth, Twitter, twitter_oauth) A: Your question is quite ambiguos. You should start by reading Twitter dev's documentation on OAuth. There's even an example there with the OAuth gem. I used this gem for my code too and was able to authenticate with Twitter's API. After trying out some solution, come back for more specific questions. A: I made a small twitter command line app: you can have a look at the code to see a more complex example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL PIVOT oddity: Why do the result columns show same data? I've set up a PIVOT in SQL and despite following the syntax to a 't', my output is oriented oddly. Specifically, I have 36 'pivoted' columns and one additional date column. I'd like to show entries for each column for a given date but instead I'm seeing 36 of the same date, with one non-NULL entry for each column, a bit like an identity matrix. Code here: SELECT pvt.date , [COLUMN LIST] FROM ( ...[subquery removed due to length]... ) AS source PIVOT ( SUM(totalret) FOR description IN ( [COLUMN LIST] ) ) AS pvt order by date A: The issue ended up being related to the column list within the sub-query (that I omitted). I was selecting extraneous columns in the subquery that weren't being referenced or used directly in the pivot--removing them and leaving only those referenced in the pivot ended up fixing things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display an alertdialog on top of other alertdialog? And when one in foreground is closed, then the one in background should be visible This is my code to edit/update which I am doing throgh a custom alertdialog which contains the data fetched frm database. Now when the inputs provided are incorrect I want to show other alertdialog on top of this providing some message to user. When the user dismisses this message alertdialog, the previous one which is used for update should be visible. How can I do that? public class CountryEdit extends ListActivity{ private Long mRowId; private CountryDbAdapter mDbHelper; public static final String PROVIDER_NAME = "assignment2.demos.MyCountriesCP"; public static final String uriString = "content://"+ PROVIDER_NAME +"/countries"; public static final Uri CONTENT_URI = Uri.parse(uriString); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver contentResolver = getContentResolver(); Cursor c = contentResolver.query(CONTENT_URI, null, null, null, getIntent().getExtras().getString("SORT_ORDER")); String[] from = new String[] { "year", "country" }; int[] to = new int[] { R.id.year, R.id.country }; SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.country_row, c, from, to); setListAdapter(sca); mRowId = savedInstanceState != null ? savedInstanceState.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID) : null; if (mRowId == null) { Bundle extras = getIntent().getExtras(); mRowId = extras != null ? extras.getLong(assignment2.demos.MyCountriesActivity.KEY_ROWID) : null; } populateFields(); } private void populateFields() { LayoutInflater inflater=LayoutInflater.from(this); final View addView=inflater.inflate(R.layout.add_country, null); Cursor c = getContentResolver().query(CONTENT_URI.buildUpon(). appendPath(String.valueOf(mRowId)).build(), null, null, null, null); /* Read alert input */ final EditText editCountry =(EditText)addView.findViewById(R.id.editCountry); final EditText editYear =(EditText)addView.findViewById(R.id.editYear); editCountry.setText(c.getString(c.getColumnIndex("country"))); editYear.setText(c.getString(c.getColumnIndex("year"))); new AlertDialog.Builder(this) .setTitle("Edit country/year") .setView(addView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { String country = editCountry.getText().toString(); if(country.trim().length()>0 && editYear.getText().toString().trim().length()>0){ int year = Integer.parseInt(editYear.getText().toString()); ContentValues updateValues = new ContentValues(); updateValues.put(mDbHelper.COUNTRY, country); updateValues.put(mDbHelper.YEAR, year); getContentResolver().update( CONTENT_URI.buildUpon().appendPath(String.valueOf(mRowId)).build(), updateValues, null, null); finish(); } else{ new AlertDialog.Builder(CountryEdit.this) .setTitle("Invalid Inputs!") .setMessage("You need to enter Country AND Year.") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // here you can add functions finish(); } }).show(); // Toast.makeText(CountryEdit.this, // "You need to enter Country AND Year.", Toast.LENGTH_LONG).show(); //finish(); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { // ignore, just dismiss finish(); } }) .show(); } } A: The first alert dialog is dismissing itself when the second is about to show (when the click listener finishes). You can't avoid that. There's a dirty hack where you can override the click listener created by the builder like this: create().getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener( ... } But I don't recommend to do that if you don't know what you're doing (it might break the internet ;-). You would have to dismiss the dialog yourself. If you don't do that it will never close, the user will see it forever and would have to kill your app to get it started again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Translucent UITableViewCell for grouped UITableView? I would like to create a TRANSLUCENT grouped table view cell. In other words I want to see the grouped table view background pattern, but i don't want completely clear cells. I've seen a lot of questions about transparent cells but none address making translucent (only partially transparent) cells. This is what I'm trying: - (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { cell.contentView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.5f]; cell.backgroundColor = [UIColor clearColor]; cell.backgroundView.backgroundColor = [UIColor clearColor]; } And this is the result: It's almost right, except that the contentView of the cell extends beyond the rounded corners of the grouped cell. SOLVED by using a transparent image and setting the cell's background view. Would have still liked to do it programmatically though, so if anyone has a solution, I will gladly accept it. SOLVED Part II Can also be done by setting backgroundView to a new UIView, that has the desired background color and rounded corners via QuartzCore's setCornerRadius call to the view's layer property. A: This should be all you need: cell.contentView.backgroundColor = [UIColor clearColor]; cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5]; A: For anyone else wondering, the code that I ended up using was: - (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //... cell.contentView.backgroundColor = [UIColor clearColor]; cell.backgroundColor = [UIColor clearColor]; UIView *bgView = [[UIView alloc] init]; [[bgView layer] setCornerRadius:10.0f]; [bgView setBackgroundColor:[UIColor colorWithWhite:1.0f alpha:0.25f]]; cell.backgroundView = bgView; //... return cell; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7601654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ImageView within RelativeLayout has top and bottom padding I have a 640px wide, 208px tall PNG that I've placed in my /drawable folder and I'm having a very hard time properly placing it in an ImageView. I want to scale the image so that it maxes out the horizontal resolution, and I want it to scale vertically only as much as it takes to stay in proportion. The problem I am having is that my ImageView ends up taller than it needs to be to fit the image. The image itself looks perfect; as wide as the screen and in proportion. But the ImageView appears to have padding on the top and bottom. From what I can tell it's the drawable that the ImageView contains that's actually too tall. I can't post an image because I'm new to SO, but if I did it would be of the Graphical Layout view. When I click on the ImageView the regular blue box shows up around it, but with padding on the top and bottom, the same padding I'm seeing on the device. Even if I drag the blue box to attempt to resize the ImageView, I am not allowed to make it any smaller than it already is (perhaps because the ImageView thinks the drawable is that tall, or something). From what I can tell, this may have something to do with the density of the image...the ImageView ends up being 312 pixels tall (208*1.5) on an hdpi device. Here is my XML: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/back" android:src="@drawable/categoryheader2" android:layout_width="wrap_content" android:layout_height="wrap_content"> </ImageView> </RelativeLayout> Thanks in advance for any help! A: I guess android:adjustViewBounds="true" on the ImageView should do the trick. I recently had a similar problem, when I was trying to scale an image to fit the whole width of the view without loosing its proportions. A: did you tried the tag : android:scaleType="fitXY" or android:scaleType="centerCrop" on your ImageView ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7601664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to open comments from disqus in my iOS app I have RSS reader, and it's using disqus.com to comment stories, but I can't open only comments from my webpage. I've tried to remove text from HTML, but it is removing comments too. I've tried to use api, but I can't make response from server visible. Thank you for help. A: It's not officially documented but you can find an RSS link in our embed which is unique for each thread. It sits next to the "Subscribe by email" link. Thread RSS links are assembled fairly simply. Using pseudo-code, the assembly looks like: 'http://' + disqus_shortname + 'disqus.com/' + thread_slug + '/latest.rss' Using our latest blog post as an example, the RSS link looks like: http://disqus.disqus.com/new_feature_always_know_where_your_comment_went_62/latest.rss A thread's slug can be pulled using our threads/details API method. A: https://github.com/moqod/disqus-ios this is a great solution that handles Disqus integration into iOS apps. Supports pretty much all you need from Disqus in an app. A: there is a description on disqus forums: John Campbell 1 year ago It does, with an URL of http://[your disqus site id].disqus.com/latest.rss Such as http://jesus.disqus.com/latest.rss It can be tracked with feedburner or yahoo pipes, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7601665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add To Timeline button not requesting publish_actions permission I'm using the xfbml Add To Timeline social plugin (https://developers.facebook.com/docs/reference/plugins/add-to-timeline/), but when I click it the permissions dialog I get just says "Access my basic information" and sure enough it isn't actually getting me the publish_actions permission I need to use the timeline. I tried specifying the perm explicitly on the tag like so:<fb:add-to-timeline show-face="false" mode="button" perms="publish_actions"></fb:add-to-timeline> but no luck. This was working fine yesterday and suddenly now it isn't. I'm wondering if this has something to do with my adding and removing my app from my facebook account multiple times? A: This was driving me crazy for a long while. In my case, I fixed it by enabling 'Enhanced Auth Dialog' under the Advanced tab of my app settings. A: When asking for publish_actions Facebook shows a preview screen of what sort of aggregations your app will create on their timeline. In other words, if the preview isn't working, Facebook won't ask for the permission so you're asking in vain. Facebook doesn't make this clear in the docs, but everything needs to be perfectly setup with your app on Facebook to get this to work right. * *Enable Enhanced Auth Dialong in the advanced settings of the app *Make sure you have at least one action and one object set up in the open graph section *For each action you must have an aggregation set up. If you do not do all of these steps, there can be no preview and so Facebook won't ask for permission no matter what. A: I faced the same issue. I fixed it by doing the below mentioned two thiings. a. Enabled 'Enhanced Auth dialog' from 'advanced' setting of the app. b. blanked 'user and friend permissions' along with 'extended permissions' tab on 'auth dialog' page. I am not sure what it did, but it started working. BUT.. Even though the authentication works and the posts are reflecting on my timeline, the add-to-timeline button still shows, 'Add to Timeline'.. The other trick i used is to keep checking the app permissions under account setting tab of my profile page. Hope this helps ! A: From Apps -> Settings -> Auth Dialog: While in Open Graph Beta, the 'publish_actions' permission can only be requested from developers and test users of your app. The 'publish_actions' permission will be ignored if requested from any other user. I had the Enhanced Auth Dialog enabled in the Advanced Settings, yet this did not work until I added a Aggregation Preview for the activity. Strange, but true. Hope this helps. A: The publish_actions permission appears only if the user has added timeline OR if your app is a game. I suppose it will also be available for apps when Timeline will be rolled out to all users...
{ "language": "en", "url": "https://stackoverflow.com/questions/7601667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JQuery Accordion issues in IE8, works great locally but not on the server We are working on: http://www.ftj.com/carrier-information If you choose "Transamerica Corporation" in IE8 you will see some height issues. However, when you resize your IE window the page seems to auto correct without a refresh. When we run this locally there are no issues what-so-ever. Any tips would be greatly appreciated. A: It seems that our browser settings were set to compatibility mode... Not an IE8 issue at all. A: Issue may be on this JS file: "src="/CarrierInformation.js">" change with this piece of code: $(document).ready(function(){ if (typeof pages == 'undefined' || !pages) { var pages = {}; } pages.carrierInformation = (function () { var bindAccordion = function () { $('#accordion').accordion({ autoHeight: false }); }; return { init: function () { bindAccordion(); } } })(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7601673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I'd like to remove the filename from a path using JavaScript Using Javascript I'd like to remove the filename from the end of a string (path+filename), leaving me just the directory path. Would regular expressions be ideal? Or, is there a simpler means of doing this using the string object? Thanks for any help! ----ANSWERED & EXPLAINED--- The purpose of this code was to open finder to a directory. The data I was able to extract included a filename - since I was only trying to open finder (mac) to the location, I needed to strip the filename. Here's what I ended up with: var theLayer = app.project.activeItem.selectedLayers[0]; //get the full path to the selected file var theSpot = theLayer.source.file.fsName; //strip filename from the path var r = /[^\/]*$/; var dirOnly = theSpot.replace(r, ''); //use 'system' to open via shell in finder popen = "open" var runit = system.callSystem(popen+" "+"\""+dirOnly+"\""); A: You can use substring and indexOf: var url = 'asdf/whatever/jpg.image'; url.substring(0, url.lastIndexOf('/')) A: var urlstr = '/this/is/a/folder/aFile.txt'; var r = /[^\/]*$/; urlstr.replace(r, ''); // '/this/is/a/folder/' A: I know this is a very old question and has already been answered, however my requirement was to remove the file if it exists in the given path or don't do anything if its folder already. The accepted answer's regex didn't work for me so I used this one: let FilePathString = '/this/is/a/folder/aFile.txt'; let FolderPathString = '/this/is/a/folder/'; const RegexPattern = /[^\/](\w+\.\w+$)/i; console.log(FilePathString.replace(RegexPattern, '')); // '/this/is/a/folder/' console.log(FolderPathString.replace(RegexPattern, '')); // '/this/is/a/folder/' A: As noted in this answer, if you're using node.js (fair assumption if you're dealing with file paths) - you can use the path module, call path.parse, and retrieve the directory name with dir like this: const path = require("path") let myPath = "folder/path/file.txt" let myDir = path.parse(myPath).dir console.log(myDir) // "folder/path" This should be the most robust way to manage and parse file paths across different environments. A: You haven't specified any sample inputs. Assuming you always have a directory then the following will work. It takes everything up to (but not including) the last slash. test = "/var/log/apache2/log.txt"; console.log(test.substring(0, test.lastIndexOf("/")));
{ "language": "en", "url": "https://stackoverflow.com/questions/7601674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }