text
stringlengths
8
267k
meta
dict
Q: receiving only the filename in a shell command I want to get only the filename (and no the full path) when running a shell command on some file extension (In the context menu of it) It is probably done somehow in the registry, in the file extension under HKCR. Any of %1 %l %L gives the full path. I want only the filename thanks The idea is good, but I can't make it work I created the file- GetFileName.bat I put it somewhere it is in the%path% it looks like that: @set Ret="%~n1" and in the registry I put the following command cmd /k GetFileName "%L" & hh.exe -decompile extracted %Ret% which means: * Run this- GetFileName "%L" * and then- hh.exe -decompile extracted %Ret% but the %Ret% doesn't give me the result of the GetFileName, although it contains the environment variable Ret with the correct value. I guess it doesn't allow in the registry to use this environment variable because it is in the same line A: You can use the %~n modifier to extract a filename from a path in a script argument, but it does not appear to recognize other environment varaibles, so you'll have to stuff it into a separate batch file: getext.bat: @set Ret=%~n1 and then C:\> getext hello.bat C:\> echo %Ret% hello
{ "language": "en", "url": "https://stackoverflow.com/questions/7603830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kohana 3.2 Validation_Exception will not support errors() I am trying to add the error messages to my validation object. It says that errors is not a method of Validation_Exception. That I know... The thing is that I though the $e variable would be the instance of the Validation Class in the model. My question is how can attach the error messages? Error: ErrorException [ Fatal Error ]: Call to undefined method Validation_Exception::errors() Controller: 208 // redirect to the user account 209 $this->request->redirect('user/profile'); 210 } catch (Validation_Exception $e) { 211 // Get errors for display in view 212 // Note how the first param is the path to the message file (e.g. /messages/register.php) 213 $errors = $e->errors('register/user'); 214 // Move external errors to main array, for post helper compatibility 215 $errors = array_merge($errors, (isset($errors['_external']) ? $errors['_external'] : array())); 216 $view->set('errors', $errors); 217 // Pass on the old form values 218 $_POST['password'] = $_POST['password_confirm'] = ''; Model: $validation = Validation::factory($fields) ->rules('username', $this->_rules['username']) ->rule('username', array($this, 'username_available'), array(':validation', ':field')) ->rules('email', $this->_rules['email']) ->rule('email', array($this, 'email_available'), array(':validation', ':field')) ->rules('password', $this->_rules['password']) ->rules('password_confirm', $this->_rules['password_confirm']); //->labels($_labels); if (Kohana::config('useradmin')->activation_code) { $validation->rule('activation_code', array($this, 'check_activation_code'), array(':validation', ':field')); } if(!$validation->check()) { throw new Validation_Exception($validation, __('Your registering information is not valid.')); } I really don't see why this error is accuring. A: You have basically answered your own question - Validation_Exception doesn't have errors method. You need to call it from Validation object instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What happens in C++ when I pass an object by reference and it goes out of scope? I think this question is best asked with a small code snippet I just wrote: #include <iostream> using namespace std; class BasicClass { public: BasicClass() { } void print() { cout << "I'm printing" << endl; } }; class FriendlyClass { public: FriendlyClass(BasicClass& myFriend) : _myFriend(myFriend) { } void printFriend() { cout << "Printing my friend: "; _myFriend.print(); } private: BasicClass& _myFriend; }; int main(int argv, char** argc) { FriendlyClass* fc; { BasicClass bc; fc = new FriendlyClass(bc); fc->printFriend(); } fc->printFriend(); delete fc; return 0; } The code compiles and runs fine using g++: $ g++ test.cc -o test $ ./test Printing my friend: I'm printing Printing my friend: I'm printing However, this is not the behavior I was expecting. I was expecting some sort of failure on the second call to fc->printFriend(). Is my understanding of how the passing/storing by reference works incorrect or is this something that just happens to work on a small scale and would likely blow up in a more sophisticated application? A: When you store a reference to an object that has ended its lifetime, accessing it is undefined behavior. So anything can happen, it can work, it can fail, it can crash, and as it appears I like to say it can order a pizza. A: It works exactly as for pointers: using something (pointer/reference) that refers to an object that no longer exists is undefined behavior. It may appear to work but it can break at any time. Warning: what follows is a quick explanation of why such method calls can seem to work in several occasions, just for informative purposes; when writing actual code you should rely only on what the standard says As for the behavior you are observing: on most (all?) compilers method calls are implemented as function calls with a hidden this parameter that refers to the instance of the class on which the method is going to operate. But in your case, the this pointer isn't being used at all (the code in the function is not referring to any field, and there's no virtual dispatch), so the (now invalid) this pointer is not used and the call succeeds. In other instances it may appear to work even if it's referring to an out-of-scope object because its memory hasn't been reused yet (although the destructor has already run, so the method will probably find the object in an inconsistent state). Again, you shouldn't rely on this information, it's just to let you know why that call still works. A: Undefined behavior. By definition you cannot make assumptions about what will happen when that code runs. The compiler may not be clearing out the memory where bc resides yet, but you can't count on it. I actually fixed the same bug in a program at work once. When using Intel's compiler the variable which had gone out of scope had not been "cleaned up" yet, so the memory was still "valid" (but the behavior was undefined). Microsoft's compiler however cleaned it up more aggressively and the bug was obvious. A: You have a dangling reference, which results in undefined behavior. A: * *look here: Can a local variable's memory be accessed outside its scope? *It will almost will work, since you have no virtual functions, and you don't acces fields of BasicClass: all methods you call have static binding, and 'this' is never used, so you never actually access "not allocated memory".
{ "language": "en", "url": "https://stackoverflow.com/questions/7603833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to remove Controller and function name from URL in CodeIgniter I am having a serious issue with one application developed in CI. Currently my URLs look like this http://www.example.com/content/index/mission/ I want to remove /content/index/ from URL So, It should look something like this. http://www.example.com/mission I have routing and .htaccess method as well. But nothing seems to be working. Here is my .htaccess file Options +FollowSymLinks RewriteEngine on RewriteBase / RewriteCond $1 !^(index\.php|images|css/js/style/system/feature_tab/robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [QSA,L] I have also tried routing of CI by defining reouters in config/router.php But it was not working :( A: For your specific example, you'll want to create a route (in application/config/routes.php) that maps $route['mission/'] to "content/index/mission" In other words, $route['mission/'] = "content/index/mission"; See the CI documentation regarding URI routing for more info A: You can go into application/config/routes.php and set your own URL routing rules. (i.e. use something totally different than Controller/Funcction). There should be an array called $route which lets you assign mappings of url => controller/function. Hope this helps. Check out this guide, its right up you're alley: http://codeigniter.com/user_guide/general/routing.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7603845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make functions for my pymongo/twitter script? I'm working on creating scripts using python, mongodb and the pymongo module to fetch certain aspects of the Twitter API and store them in a mongo database. I've written some scripts to do different things: access the search API, access the user_timeline, and more. However, I have been just getting to know all of the tools that I'm working with and it's time for me to go back and make it more efficient. Thus, right now I'm working on adding functions and classes to my scripts. Here is one of my scripts without functions or classes: #!/usr/local/bin/python import twitter import datetime from datetime import date, timedelta, datetime import pymongo from pymongo import Connection # Twitter handle that we are scraping mentions for SCREEN_NAME = '@twitterapi' # Connect to the database connection = Connection() db = connection.test collection = db.twitterapi_mentions # Change the name of this database t = twitter.Twitter(domain='search.twitter.com') # Fetch the information from the API results = [] for i in range(2): i+=1 response = t.search(q=SCREEN_NAME, result_type='recent', rpp=100, page=i)['results'] results.extend(response) # Create a document in the database for each item taken from the API for tweet in results: id_str = tweet['id_str'] twitter_id = tweet['from_user'] tweetlink = "http://twitter.com/#!/%s/status/%s" % (twitter_id, id_str) created_at = datetime.strptime(tweet['created_at'], "%a, %d %b %Y %H:%M:%S +0000") date = created_at.date().strftime("%m/%d/%y") time = created_at.time().strftime("%H:%M:%S") text = tweet['text'] identifier = {'id' : id_str} entries = {'id' : id_str, 'tweetlink' : tweetlink, 'date' : date, 'time' : time, 'text' : text, 'twitter_id':twitter_id } collection.update(identifier, entries, upsert = True) These scripts have been working well for me, but I have to run the same script for multiple twitter handles. For instance I'll copy the same script and change the following two lines: SCREEN_NAME = '@cocacola' collection = db.cocacola_mentions Thus I'm getting mentions for both @twitterapi and @cocacola. I've thought a lot about how I can make this into a function. The biggest problem that I've run into is finding a way to change the name of the collection. For instance, consider this script: #!/usr/local/bin/python import twitter import datetime from datetime import date, timedelta, datetime import pymongo from pymongo import Connection def getMentions(screen_name): # Connect to the database connection = Connection() db = connection.test collection = db.screen_name # Change the name of this database t = twitter.Twitter(domain='search.twitter.com') # Fetch the information from the API results = [] for i in range(2): i+=1 response = t.search(q=screen_name, result_type='recent', rpp=100, page=i) ['results'] results.extend(response) # Create a document in the database for each item taken from the API for tweet in results: id_str = tweet['id_str'] twitter_id = tweet['from_user'] tweetlink = "http://twitter.com/#!/%s/status/%s" % (twitter_id, id_str) created_at = datetime.strptime(tweet['created_at'], "%a, %d %b %Y %H:%M:%S +0000") date = created_at.date().strftime("%m/%d/%y") time = created_at.time().strftime("%H:%M:%S") text = tweet['text'] identifier = {'id' : id_str} entries = {'id' : id_str, 'tweetlink' : tweetlink, 'date' : date, 'time' : time, 'text' : text, 'twitter_id':twitter_id } collection.update(identifier, entries, upsert = True) getMentions("@twitterapi") getMentions("@cocacola") If I use the above script then all of the data is stored in the collection "screen_name" but I want it to be stored in the screen name that is passed through. Ideally, I want @twitterapi mentions to be in a "twitterapi_mentions" collection and I want @cocacola mentions to be in a "cocacola_mentions" collection. I believe that using the Collection class of pymongo might be the answer and I've read the documentation but can't seem to get it to work. If you have other suggestions of how I should make this script more efficient they would be incredibly appreciated. Otherwise, please excuse any mistakes I've made, as I said, I'm new to this. A: Use getattr to retrieve the attribute by string name: collection = getattr(db, screen_name) A: I'd go with: collection = db[screen_name] I think it's more straightforward.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to read Internet Explorer in java lets say I'm Using Internet Explorer to look at stackoverflow.com is there a way to get the informations I'm looking at stackoverflow.com or is this impossible A: You should look into Selenium. It is a browser automation framework that allows you to control a browser (such as Internet Explorer) through code in Java, .NET, Ruby, or Python. Edit: If you're wondering if it's possible for an external Java application to know that the user happens to have IE open and is looking at a certain website, I can't help you there. That isn't to say it isn't possible; I just don't know whether it is or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How Can i read the preview frames from the actual opensource android Camera How can i read the preview frames from the actual camera source code? I am trying to modify the actual source code of camera application in android for reading the preview frames. Can anyone help me with this. A: You shouldn't have to change the actual source code for reading frames. Implementing the Camera.PreviewCallback interface should suffice. It returns raw data from the camera. A: Before messing with the source of the camera app try the example here: CameraPreview Then implement the Camera.PreviewCallback. The captured frame comes in YUV420SP so you have to convert it to rgb in order to convert it into a colored bitmap and show it on screen. Like this : @Override public void onPreviewFrame(byte[] data, Camera camera) { int imageWidth = camera.getParameters().getPreviewSize().width ; int imageHeight =camera.getParameters().getPreviewSize().height ; int RGBData[] = new int[imageWidth* imageHeight]; byte[] mYUVData = new byte[data.length]; System.arraycopy(data, 0, mYUVData, 0, data.length); decodeYUV420SP(RGBData, mYUVData, imageWidth, imageHeight); Bitmap bitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888); bitmap.setPixels(RGBData, 0, imageWidth, 0, 0, imageWidth, imageHeight); } static public void decodeYUV420SP(int[] rgb, byte[] yuv420sp, int width, int height) { final int frameSize = width * height; for (int j = 0, yp = 0; j < height; j++) { int uvp = frameSize + (j >> 1) * width, u = 0, v = 0; for (int i = 0; i < width; i++, yp++) { int y = (0xff & ((int) yuv420sp[yp])) - 16; if (y < 0) y = 0; if ((i & 1) == 0) { v = (0xff & yuv420sp[uvp++]) - 128; u = (0xff & yuv420sp[uvp++]) - 128; } int y1192 = 1192 * y; int r = (y1192 + 1634 * v); int g = (y1192 - 833 * v - 400 * u); int b = (y1192 + 2066 * u); if (r < 0) r = 0; else if (r > 262143) r = 262143; if (g < 0) g = 0; else if (g > 262143) g = 262143; if (b < 0) b = 0; else if (b > 262143) b = 262143; rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Marshalling error while using OPENSAML2 in a servlet environment (Tomcat web server) I am trying to setup my Service provider using OpenSAML2 libraries. I am trying to set up a servlet which would accept HttpRequest from user's browser and based on the request parameters I want to create a SAML Authentication request packet. I am able to create the SAML packet, however I want to Base64 encode the SAML so that I can redirect the user browser to the Identity provider server. In order to do that I am trying to marshall the SAML Authentication Request using 'org.opensaml.saml2.core.impl.AuthnRequestMarshaller#marshall(AuthnRequest)'. This works fine when I try it outside of the web server environment (standalone JAVA application). However when I run it as a servlet component I get an error saying "No marshaller available for {urn:oasis:names:tc:SAML:2.0:assertion}Issuer, child of {urn:oasis:names:tc:SAML:2.0:protocol}AuthnRequest", where Issuer is a component of the AuthnRequest object. I am using Tomcat 5.5.34 webserver. It would be nice if someone can help me figure out whats happening here. It would help others trying to write their own Service Providers as well. Surprisingly very less documentation is available for this. Thanks, Kaustubh A: You need to have following jars inside Tomcat common/endorsed directory.. * *resolver-2.9.1.jar *serializer-2.9.1.jar *xalan-2.7.1.jar *xercesImpl-2.9.1.jar *xml-apis-2.9.1.jar Here is an example of SAML2 service provider [also includes the sample WAR]. A: Prabath's answer is on the dot. I faced the same issue, and resolved it by endorsing xalan and xerces in the Sun iJDK. Check out the official guide from the Shibboleth site. Look under "Installing the Library" for openSAML deployment requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UITextField inside UIScrollView - I want to detect tap when it's focused As topic's title says I want to do something when user touches UITextField and do something else when he will do it again. I noticed that there's no UITextFieldDelegate method that is giving this kind of information. Anyone could help me with that? To make it sure - I don't want to recognize double tap on UITextField but getting notification always when user touched UITextField to do something on second click. Thanks! A: If you want to use your own special logic in UITextField it would be easier to use custom class implementing UIKeyInput protocol (see: http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UIKeyInput_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIKeyInput)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nested exists clauses vs adjacent exists clauses Can someone please tell me which of this 2 querys is better than the other and why? Should I use a join instead? select * from grandChildTable gct where exists( select * from childTable ct where some condition and gct.parentId = ct.Id and exists( select * from Table t where some other condition and ct.parentId = t.Id)) select * from grandChildTable gct where exists( select * from childTable ct where some condition and gct.parentId = ct.Id) and exists( select * from Table t where some other condition and gct.grandParentId = t.Id) NOTES: The GrandChildTable has the IDs for both the ChildTable and Table because the IDs are compound. The tables doesn't have references to any of the others. The relationships between the tables are: GrandChild to Child n:1 Child to Table n:1 A: In this case (comparing to parent tables where you have less rows then the child) there may little difference using JOINs. However EXISTS is typically quicker and proven so. I would also expect the optimiser to generate identical plans for the 2 EXISTS based ones: examine the query plans and see if there are any differences (also this Red Gate link). If not, go for readability.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting buddypress user name in a javascript file From within my buddypress PHP templates I usually get the username of any given user by referencing the user ID like this:- <?php echo bp_core_get_username( '{{userID}}' ) ?> However I need to retrieve the username from within an external Javascript file. The user ID is already passed in as var aData[11]. I have tried the following with no luck:- $('td:eq(3)', nRow).html( '<div class="table-row"><a href="http://www.mysite.com/members/' + <?php echo bp_core_get_username( '"' + aData[11] + '"' ) ?> + '/song/?songsID=' + aData[10] + '"><h4 class="nomargin">' + aData[0] + '</h4></a>' + aData[1] + '</div>' ); I am trying to return a URL... This cirrently gives me: http://www.mysite.com/members//song/?songsID=6 Whe it should be: http://www.mysite.com/members/username/song/?songsID=6 Any ideas? Edit: Below is the server side code that I am using to ouput the JSON <?php $aColumns = array( 'song_name', 'artist_band_name', 'author', 'song_artwork', 'song_file', 'genre', 'song_description', 'uploaded_time', 'emotion', 'tempo', 'songsID', 'user' ); $sIndexColumn = "songsID"; /* DB table to use */ $sTable = "wp_dbt_songs"; /* Database connection information */ $gaSql['user'] = ""; $gaSql['password'] = ""; $gaSql['db'] = ""; $gaSql['server'] = ""; $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or die( 'Could not open connection to server' ); mysql_select_db( $gaSql['db'], $gaSql['link'] ) or die( 'Could not select database '. $gaSql['db'] ); $sLimit = ""; if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ) { $sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ". mysql_real_escape_string( $_GET['iDisplayLength'] ); } if ( isset( $_GET['iSortCol_0'] ) ) { $sOrder = "ORDER BY "; for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) { if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) { $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]." ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", "; } } $sOrder = substr_replace( $sOrder, "", -2 ); if ( $sOrder == "ORDER BY" ) { $sOrder = ""; } } $sWhere = ""; if ( $_GET['sSearch'] != "" ) { $sWhere = "WHERE ("; for ( $i=0 ; $i<count($aColumns) ; $i++ ) { $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR "; } $sWhere = substr_replace( $sWhere, "", -3 ); $sWhere .= ')'; } /* Individual column filtering */ for ( $i=0 ; $i<count($aColumns) ; $i++ ) { if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' ) { if ( $sWhere == "" ) { $sWhere = "WHERE "; } else { $sWhere .= " AND "; } $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' "; } } $sQuery = " SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))." FROM $sTable $sWhere $sOrder $sLimit "; $rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error()); /* Data set length after filtering */ $sQuery = " SELECT FOUND_ROWS() "; $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error()); $aResultFilterTotal = mysql_fetch_array($rResultFilterTotal); $iFilteredTotal = $aResultFilterTotal[0]; /* Total data set length */ $sQuery = " SELECT COUNT(".$sIndexColumn.") FROM $sTable "; $rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error()); $aResultTotal = mysql_fetch_array($rResultTotal); $iTotal = $aResultTotal[0]; $output = array( "sEcho" => intval($_GET['sEcho']), "iTotalRecords" => $iTotal, "iTotalDisplayRecords" => $iFilteredTotal, "aaData" => array() ); while ( $aRow = mysql_fetch_array( $rResult ) ) { $row = array(); for ( $i=0 ; $i<count($aColumns) ; $i++ ) { if ( $aColumns[$i] == "version" ) { /* Special output formatting for 'version' column */ $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ]; } else if ( $aColumns[$i] != ' ' ) { /* General output */ $row[] = $aRow[ $aColumns[$i] ]; } } $output['aaData'][] = $row; } echo json_encode( $output ); ?> A: The html you're setting is being set on the client side, not on the server side, meaning that the php code will not be evaluated. I guess what you can do is either put the already-evaluated username in a hidden tag and get that using jquery or expose it to the javascript on the page within script tags. EDIT: So is the userID or the username in the json as well? If not, you could probably put it there. I'm still not so sure what the situation is. But if you're currently passing the userID in the json and actually want the username as bp_core_get_username would return it, why not just put the already retrieved (with bp_core_get_username) username into the json as well? In other words, in your php code, figure out what the username is based on the userid with bp_core_get_username and then pass that into the json. That is, if I'm understanding the situation correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: loop error when numbers entered why this loop executes 3 times when a number is entered? I only want 's' or 'm' to be accepted.. how could I fix this? cout << "Are you married or single (m/s): "; cin >> status; status = tolower(status); //converting to lower case //validating imput for marital status while((status != 'm') && (status != 's')) { cout << "Sorry, you must enter \"m\" or \"s\" \n" << "Are you married or single (m/s): "; cin >> status; status = tolower(status); } A: Your variable status is probably declared as: char status; So, cin >> status reads a single character from the input. However, you probably typed more than one because the input is buffered and you needed to press Enter. Instead, use this declaration: string status; which will get the whole line of input, and then you can inspect the characters within the line. A: You can use getchar() to save into status, it reads only one character from buffer.. cout << "Are you married or single (m/s): "; getchar(status); //validating imput for marital status while((status != 'm') || (status != 's')) //status can be a male OR a female { cout << "Sorry, you must enter \"m\" or \"s\" \n" << "Are you married or single (m/s): "; getchar(status); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS hover menu positioning troubles I'm building a CSS hover menu for my site: http://test.fairfood.org. I can't seem to figure out how to position each nested ul to display underneath it's parent li. They all show up at the same place. The submenus also disappear behind the carrousel even though the nested ul's have position absolute and a high z-index. What am I overlooking here? A: I suggest stripping all your style from the ul li elements and just call them like this: http://jsfiddle.net/MmsVS/ This is the style I use for my own menus.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shared_ptr release Possible Duplicate: How to release pointer from boost::shared_ptr? Detach a pointer from a shared_ptr? I'm attempting to release a shared_ptr (the way you can release a unique_ptr). I know this doesn't make sense when the shared_ptr isn't unique, but I have a shared_ptr which is guaranteed to be unique. I've tried... m_pObj.reset((T*)nullptr, [](T* const){}); ...but it just deletes the object anyway. I'm not sure what that deleter argument is good for if shared_ptr winds up calling delete anyway. Is there any way to achieve this (solutions specific to VS2010 are welcome if there is no other way). A: Before this get's closed as dup, I'll add my take on this. I think there are a lot of good reasons why you would occasionally want to release a shared_ptr (or boost::scoped_ptr). However, the people who designed these classes think that you should not be able to do this. (It's their baby, they have a right to.) As far as I can see, it is simply not possible to detach a shared_ptr. You will need to either use another class or come up with a design where you do not need to detach it. And I should read the dupes as you can actually hack it together using a very special deleter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Better data structure or algorithm than iterative searching on multidimensional arrays to find corresponding values? For a site I am working on I use a library to get a list of states. It returns a numerically indexed array of states, each with three keys: stateCode, stateName, and stateSeg. It looks like this: array 0 => & array 'stateCode' => string 'AL' (length=2) 'stateName' => string 'Alabama' (length=7) 'stateSeg' => string 'alabama-al' (length=10) 1 => & array 'stateCode' => string 'AK' (length=2) 'stateName' => string 'Alaska' (length=6) 'stateSeg' => string 'alaska-ak' (length=9) 2 => & array 'stateCode' => string 'AZ' (length=2) 'stateName' => string 'Arizona' (length=7) 'stateSeg' => string 'arizona-az' (length=10) I often find myself with one of the three values and needing to look up its corresponding value. To do this I find myself constantly having to iterate through the array of states to find the data I need. Like this: foreach ($this->data['stateList'] as $state) { if ($state['stateCode'] == $searchParams['state']) { $stateSeg = $state['stateSeg']; break; } } $url = BASEURL . '/' . $stateSeg . ".html"; This seems inefficient to me. I think the most efficient solution I’ve been able to come up with is to turn states into objects and put them in array with multiple keys for stateCode, stateSeg, and stateName each pointing to the same state object, so they can be referenced like this: stateList[‘CA’]->getStateSeg(); or stateList[‘Arizona’]->getStateCode(); or stateList[‘alaska-ak’]->getStateName(); etc… This also seems like kind of a hack which would result in a rather large array (150 keys pointing to 50 objects) with replicated data (keys replicating data stored within objects). Anyway, just thought I’d see if there is some kind of pattern for this type of problem. This array of states isn't the only thing I’ve come across where I’ve had to do this sort of iterative searching on multidimensional arrays to find corresponding values. Question is tagged PHP and the code above is in PHP, but I am interested in elegant solutions in any language. A: If php supports references and I know the state, I'd just pass a reference to the appropriate array element and extract from it the necessary field. Alternatively, if you never know in advance what state you can get, create and use a map (associative container/array), let its efficient implementation take care of quickly finding whatever you need. Seems like you may need several of them. Also, I wonder if you could get rid of everything except the "alaska-ak" strings. The data appears highly redundant. A: Could you store the states in a mysql/sqlite table and use the database engine to do the lookup? A: I think your basic idea with the object and the arrays is not that bad, but instead of creating actually objects, I would just refer to the existing objects (better: array data). Let's see your original list again: array 0 => & array 'stateCode' => string 'AL' (length=2) 'stateName' => string 'Alabama' (length=7) 'stateSeg' => string 'alabama-al' (length=10) 1 => & array 'stateCode' => string 'AK' (length=2) 'stateName' => string 'Alaska' (length=6) 'stateSeg' => string 'alaska-ak' (length=9) 2 => & ... Each state object has an identifier, the array key: 0, 1, 2, ... . All you need to do is to create three indexes based on key. You use the value as key (e.g. "AL" for "stateCode" index) and as value you take the array index, 0: $indexStateCode['AL'] = 0; You can then already look this up quickly: $states[$indexStateCode['AL']]; Encapsulate this into a class with ArrayAccess and then on request instantiate the state object. You don't need it earlier. A: This seems inefficient to me It isn't. Even worse-case, iterating through 50 items is probably an order of magnitude faster than querying a db. a library to get a list of states Not sure why you'd need a library to do this. But I'd either change the library to return the array how you need it, or wrap it in another module. The data is somewhat redundant... All you need is two items: the state code and the state name. You can construct the "state seg" from those two. So keep a state code map and a state name map.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use of PHP generated sites in SEO? I've got a site that is based around a contact form. This form is generated according to the variables passed in the URL, and the information passed is put in headers in the body, and also in the title. Additionally images are customized, so basically the whole content is changed according to these variables. So I've run a sitemap generator, and it's actually generated lots of these www.site.tld/me.php?a=hi&b=pie, www.site.tld/me.php?a=hi&b=chocolate, www.site.tld/me.php?c=hi&hello.... you get the point. So, my question is: is it smart to use this to my advantage, include these in the sitemap and customize them for SEO, or should I just ignore it and omit it from the sitemap? A: In general having dynamic urls is okay, but you don't necessarily want them indexed for SEO purposes. In general its better to have a well organized url structure, as its seen to be more appealing. (i.e. site.com/article/sports/baseball123 is better than site.com?id=123433). So depending on your content (whether its static or dynamic) you may want to move to that type of a url structure, and have your pages indexed. On the other hand if you need to keep dynamic urls (for some reason) and depending on the nature of the content, it may be best to leave them out of the equation from an SEO perspective. It ultimately comes down to what you're serving from these pages. A: Search engine friendly urls by using apache rewrite module search apache mod_rewrite in google there are many ways to do this and there are some ways that work much better than others. Google will index your site based on the content on the page rather than the url or any meta information. Using the mod rewrite makes it easier for your viewers but as far as search engines are concerned it dont really matter. Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7603879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Like Button Not Showing Counts This happens on any web browser. When I go to the page, I see the like button not showing any counts. Then I... * *Press on the Like button. *I then see the box say +1. *I refresh the page. *I no longer see the +1 and I see the Like button as if it was never pressed. I can repeat steps 1-4 endlessly with the same results - I never see the total live count. It would seem like it's not keeping counts, but when I query it via: https://api.facebook.com/method/fql.query?query=select total_count,like_count,comment_count,share_count,click_count from link_stat where url='https://www.myswebsite.com/'&format=json I see the live stats - so I know it's working. I've also tried different variations of http://developers.facebook.com/docs/reference/plugins/like/ - and old versions as well. I've isolated the code to just be the facebook code with nothing else on the page. For some reason, when I use https://www.myswebsite.com/ it doesn't show. I try other URLs like http://www.google.com with the code, and it works fine, I can see the count. It's an SSL web site. Does this have anything to do with it? Also, when we initially launched the site with the Like button, it was http://mywebsite.com originally. Then we switched it to http://www.myswebsite.com, and then setup a SSL wildcard to function with both. I'm not sure if caching has anything to do with it. Thanks! A: This blog post might give you some help. What the post says is that you can "sort of" clean your URL with Facebook URL linter tool Also there is a bug reported related to this issue
{ "language": "en", "url": "https://stackoverflow.com/questions/7603880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: I want to make a concealed "password" in Java In Java I want to make such that when I'm typing a String as input the letters of the string do not appear on the console screen. Is there anyway I can do that? A: Maybe Java 6's Console.readPassword()?
{ "language": "en", "url": "https://stackoverflow.com/questions/7603890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php pdo prepare repetitive variables While writing a pdo statement, is it possible to repeat the value of a variable? I mean: $query = "UPDATE users SET firstname = :name WHERE firstname = :name"; $stmt = $dbh -> prepare($query); $stmt -> execute(array(":name" => "Jackie")); Please note that I repeat the ":name" nameholder whereas I provide the value only once. How can I make this work? A: The simple answer is: You can't. PDO uses an abstraction for prepared statements which has some limitations. Unfortunately this is one, you have to work-around using something like $query = "UPDATE users SET firstname = :name1 WHERE firstname = :name2"; $stmt = $dbh -> prepare($query); $stmt -> execute(array(":name1" => "Jackie", ":name2" => "Jackie")); In certain cases, such as emulated prepared statements with some versions of the PDO/MySQL driver, repeated named parameters are supported; however, this shouldn't be relied upon, as it's brittle (it can make upgrades require more work, for example). If you want to support multiple appearances of a named parameter, you can always extend PDO and PDOStatement (by classical inheritance or by composition), or just PDOStatement and set your class as the statement class by setting the PDO::ATTR_STATEMENT_CLASS attribute. The extended PDOStatement (or PDO::prepare) could extract the named parameters, look for repeats and automatically generate replacements. It would also record these duplicates. The bind and execute methods, when passed a named parameter, would test whether the parameter is repeated and bind the value to each replacement parameter. Note: the following example is untested and likely has bugs (some related to statement parsing are noted in code comments). class PDO_multiNamed extends PDO { function prepare($stmt) { $params = array_count_values($this->_extractNamedParams()); # get just named parameters that are repeated $repeated = array_filter($params, function ($count) { return $count > 1; }); # start suffixes at 0 $suffixes = array_map(function ($x) {return 0;}, $repeated); /* Replace repeated named parameters. Doesn't properly parse statement, * so may replacement portions of the string that it shouldn't. Proper * implementation left as an exercise for the reader. * * $param only contains identifier characters, so no need to escape it */ $stmt = preg_replace_callback( '/(?:' . implode('|', array_keys($repeated)) . ')(?=\W)/', function ($matches) use (&$suffixes) { return $matches[0] . '_' . $suffixes[$matches[0]]++; }, $stmt); $this->prepare($stmt, array( PDO::ATTR_STATEMENT_CLASS => array('PDOStatement_multiNamed', array($repeated))) ); } protected function _extractNamedParams() { /* Not actually sufficient to parse named parameters, but it's a start. * Proper implementation left as an exercise. */ preg_match_all('/:\w+/', $stmt, $params); return $params[0]; } } class PDOStatement_multiNamed extends PDOStatement { protected $_namedRepeats; function __construct($repeated) { # PDOStatement::__construct doesn't like to be called. //parent::__construct(); $this->_namedRepeats = $repeated; } /* 0 may not be an appropriate default for $length, but an examination of * ext/pdo/pdo_stmt.c suggests it should work. Alternatively, leave off the * last two arguments and rely on PHP's implicit variadic function feature. */ function bindParam($param, &$var, $data_type=PDO::PARAM_STR, $length=0, $driver_options=array()) { return $this->_bind(__FUNCTION__, $param, func_get_args()); } function bindValue($param, $var, $data_type=PDO::PARAM_STR) { return $this->_bind(__FUNCTION__, $param, func_get_args()); } function execute($input_parameters=NULL) { if ($input_parameters) { $params = array(); # could be replaced by array_map_concat, if it existed foreach ($input_parameters as $name => $val) { if (isset($this->_namedRepeats[$param])) { for ($i=0; $i < $this->_namedRepeats[$param], ++$i) { $params["{$name}_{$i}"] = $val; } } else { $params[$name] = $val; } } return parent::execute($params); } else { return parent::execute(); } } protected function _bind($method, $param, $args) { if (isset($this->_namedRepeats[$param])) { $result = TRUE; for ($i=0; $i < $this->_namedRepeats[$param], ++$i) { $args[0] = "{$param}_{$i}"; # should this return early if the call fails? $result &= call_user_func_array("parent::$method", $args); } return $result; } else { return call_user_func_array("parent::$method", $args); } } } A: In my case this error appeared when I switched from dblib freedts to sqlsrv PDO driver. Dblib driver handled duplicate parameters names with no errors. I have quite complicated dynamic queries with lots of unions and a lot of duplicated params so I used following helper as a workaround: function prepareMsSqlQueryParams($query, $params): array { $paramsCount = []; $newParams = []; $pattern = '/(:' . implode('|:', array_keys($params)) . ')/'; $query = preg_replace_callback($pattern, function ($matches) use ($params, &$newParams, &$paramsCount) { $key = ltrim($matches[0], ':'); if (isset($paramsCount[$key])) { $paramsCount[$key]++; $newParams[$key . $paramsCount[$key]] = $params[$key]; return $matches[0] . $paramsCount[$key]; } else { $newParams[$key] = $params[$key]; $paramsCount[$key] = 0; return $matches[0]; } }, $query); return [$query, $newParams]; } Then you can use it this way: $query = "UPDATE users SET firstname = :name WHERE firstname = :name"; $params = [":name" => "Jackie"]; // It will return "UPDATE users SET firstname = :name WHERE firstname = :name1"; with appropriate parameters array list($query, $params) = prepareMsSqlQueryParams($query, $params); $stmt = $dbh->prepare($query); $stmt->execute(params);
{ "language": "en", "url": "https://stackoverflow.com/questions/7603896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to remove validation from a jQuery script I found this script from a tutorial but I don't want the validation part, just the posting part.. I tried to delete the validation related commands but it doesn't work. Maybe I did it wrongly, but my thought is if all of these are needed to run the submitHandler. Thank you. $(document).ready(function(){ $("#myform").validate({ debug: false, rules: { name: "required", message: "required", email: { required: true, email: true } }, messages: { name: "Please let us know who you are.", email: "A valid email will help us get in touch with you.", message: "Please write a subject." }, submitHandler: function(form) { $.post('mailme.php', $("#myform").serialize(), function(data) { $('#results').hide().html(data).fadeIn('slow'); }); } }); }); A: You don't want to use the .validate() function then. You probably want to use .post() to submit the form: http://api.jquery.com/jQuery.post/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Could someone explain to me how I might go about using PostGIS (it's installed)? Assume I'm building a webapp for some enduser, and I'm already using postgres for the more mundane parts. One feature that might look cool (of dubious utility) is for them to map out their own property. I find some Google Maps API or something to pull up the relevant satellite view of the property, and now it's their job to dutifully enter in where various features are on the property. Buildings, parking, a few other point locations, a few other arbitrary area locations. Is all this just entering the points and polygon corners into whichever table? I feel like I'm missing something, because I could do that without anything special like PostGIS. Where does the cool stuff come into play? I've found a few pages here and there with Google, but my eyes just glaze over... I don't have a PhD in cartography. I do have a few ideas for dumb little doodle apps involving maps, and I'd love to use this. Or at least know why it's overkill for my purposes. My apologies in advance if this isn't appropriate. A: Of course you could have your users enter point and polygon corner coordinates in any non-spatial database. But be aware that all you will be able to do with that data is store and view it. If you want to e.g. find out the area of the polygons, you'll have to write your own functions instead of being able to use well-tested PostGIS functionality. If it comes to even more sophisticated applications like checking the topology of your dataset, you'll be in over your head without a proper tool. With more information as to what are the goals of your application, it would be easier to tell if you can get by without PostGIS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Modal UINavigationController Background Loading After Animation for PresentModalViewController I am having trouble with the background in my modal UIViewController displaying before the animation begins. I have a simple UINavigationController which loads a UIViewController. I then present the UINavigationController via a presentModalViewController call which slides it up from below. Within the UIViewController's loadView method I set up the standard self.view and create a background UIImageView. This background loads, but only after the modal animation is complete. I have done this type of thing many times before and remember having this issue once but can't for the life of me find what my "magic" solution was. My code is below: PhotoVideoViewController *photo = [[PhotoVideoViewController alloc] init]; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:photo]; NSLog(@"start present modal view controller"); [self.navigationController presentModalViewController:nav animated:YES]; [photo release]; [nav release]; PhotoVideoViewController loadView: - (void)loadView { UIView *myview = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.view = myview; [myview release]; NSLog(@"background loading"); UIImageView *background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background-main.png"]]; background.frame = CGRectMake(0, -45, 320, 480); [self.view addSubview:background]; [background release]; } The "start present modal view controller" displays in the log BEFORE "background loading" log shows up which tells me something is wrong obviously. I have tried to put the [photo release]; before the presentModalViewController but it does NOT resolve the issue. I have also done my research here and none of the other posts answer my issue: UINavigationController with presentModalViewController UINavigationController and presentModalViewController * *Both of these apply to the proper way to use the UINavigationController as a modal screen with a UIViewController within it. Any help is greatly appreciated. I've tried several permutations and am at a loss. It has the be the right order of things, but I'm obviously not getting the perfect order in my code. Thank you in advance! J A: Resolved the issue - simple mistake. Had a background set but was using "jpg" rather than "png" ;) Lots of time wasted on this one sadly. Its always the typos that get me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I properly implement git submodules using Gitolite? I would like to create submodules within my hosted repository using Gitolite. Submodules are easy enough in git outside of Gitolite. However, Gitolite seems to complicate things. A: It's no different than having a second repository side by side. Once you create the second repository like you did for the first, add a submodule to the first one using the same url that you have for the second one when you created it. git submodule add <same url as if you were just cloning> <some path> git submodule update --init --recursive Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determine key points in the change in frequency I have an application in which I am analyzing a system where there are a large number of interactions. And I need to make certain choices based on the frequency of the occurrences of unique items in the system. For example, if you had this list of letters: A, B, F, G, A, T, S, B, S, B, S, Q, Z, B, Q, S Here is a list showing how often each letter occurs (occurrences): A - 2 B - 4 F - 1 G - 1 Q - 2 T - 1 S - 4 Z - 1 So the frequency of the occurrences are as such (occurrence occurrences): 4 - 2 2 - 2 1 - 4 The above is a tiny example, but I've attached an image which is a simple line graph of a larger system In this graph the numbers along the bottom aren't really important. They are just marking the number of unique frequencies. And the Y-axis marks the value of that frequency. What I'm looking for is a mathematical/programmatic way to find the point where that line begins to break upwards. My searches haven't yielded what I'm looking for as I'm not really sure what the proper terminology is, or the name of the concept. Right now, we have to manually choose that point based on a human looking at the numbers and saying "here". But I want to, at the very least, already have a "recommended" value chosen, and at the most, be able to remove the human component completely. For clarification, my current algorithm is producing a list of number pairs occurrence to occurrence frequency. My use of the word "frequency" in no way relates to electromagnetic signals, but rather to how often an occurrence occurs. But I thought that saying "occurrence occurrences" would be more confusing! In this system, the general trend is that a few entities will show up in a large number of interactions, more entities will show up in a medium number of interactions, but the greatest number of entities will show up in just a few, or even no, interactions. It would be tough to imagine a scenario where it was different than that... worst case would probably be a plateau. But there could definitely be a dip after a jump at any point from the beginning to the end. The illustration above just doesn't show that. We cannot assume that there will be a point where it will begin to rise with no drops afterwards. Here is my data. (The simple graph above was produced with the Occurrence Frequency column data only): This list, as you can see, is sorted in descending order on the occurrence column. This is from a small system with 904 unique entities. Those entities have 38 unique occurrence rates. If you started at the top of this list, you could say: "2 entities occur 309 times" "1 entity occurs 130 times" etc. Ultimately what I'm trying to determine is the importance of an entity based on how often it occurs in the system. I need to be able to flag certain items as "important", but all items can't be important. And the method/algorithm I'm looking for would help to identify at what point in that list do I stop considering items important. If you look at the list, you can see where the lower occurrences start becoming more frequent. I don't think that I can sort on the right column because the left column is really the key data. Greater occurrences = more importance. But I still need to figure out how to determine that. A: Is there any reason the larger example isn't sorted? If you sort it by increasing Y values, then you can take the slope of each consecutive pair, and call the breakpoint where the slope changes significantly. You can tweak the rules for "changes significantly" to meet your exact needs. It might be as simple as "the slope that increase most compared to the previous", or "the first slope that varies more than X% from the running average slope". Or maybe the largest rss of the differences between the slope at the test point and the one before and the one after. After the edit, I think it may be as simple as taking a percentage. Multiply each X and Y, and take the sum over all entries. That's the total number of events observed. Now start from the bottom if your table, and start subtracting each row's product from the total until you get to less than X% of the original total. What you are left with is the "significant" events that contributed most to the total. I have a feeling this is a common problem in statistics, but I don't have enough background to say what the proper terminology is, although standard deviations come to mind. A: All you need to do is to refine this "find the point where that line begins to break upwards". Besed on what you say I can assume and take as a precondition that the line always brakes upwards and since that point it will never go down (not even a single step). This means in your example it'll return 33, not 32. It also assumes you'll have at least 2 values... if you have one there is nothing to compare it to, right? :) So, the algorithm to solve this would be something like: repeat $previousYValue = get the highest Y value $previousXValue = get the X value corresponding to $previousYValue $currentXValue = $previousXValue - 1 $currentYValue = get the Y value for $currentXValue until ($currentYValue > $previousYValue) print "The line breaks upwards at point: $previousXValue with value $previuosYValue" Hope that helps A: Based on your statement: Ultimately what I'm trying to determine is the importance of an entity based on how often it occurs in the system. I need to be able to flag certain items as "important", but all items can't be important. And the method/algorithm I'm looking for would help to identify at what point in that list do I stop considering items important. I would examine the problem in terms of probability and statistics instead of a function graph. Using your sample data, the probability of a certain letter x occurring is simply the number of x's in the data divided by the total count of letters. Some simple possibilities to try out: * *select the set of most probable events that account for 50% of total events *select all event with probability > 0.1 *select the n most probable events. You could use much more advanced probability theory, but one of these might be good enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error during reading and writing test file in simple MPI code I have an MPI code where processes read a binary file and write it back again. The way the data is distributed is that process 0 reads (and then writes) the first half of the file whereas process 1 reads (and then writes) the second half of the file. The issue here now is that the input and the output files do not match (diff shows that they differ). If there is only 1 process, everything works ok. Can someone point out what is going wrong? Using OpenMPI, compiled as: mpicc -Wall test_mpi.c -o test_mpi Run as: mpirun -np 2 ./test_mpi Thanks in advance. #include <stdio.h> #include <stdlib.h> #include <mpi.h> int main(int argc, char** argv) { int rank, np, i; //np = no. of processes MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &np); int filesize = 48*1048576; //input filesize 48MB double *data = (double*) malloc (filesize/np); FILE* fpa; fpa = fopen ( "512_featurevec.out", "rb"); fseek(fpa, filesize/np*rank, SEEK_SET); printf("read: %d\n", (int)fread(&data[0], sizeof(double), filesize/(np*sizeof(double)), fpa)); fclose(fpa); char* outfile = "outfile.txt"; for(i=0; i<np; i++) { if(rank == i) { fpa = fopen ( outfile, "ab"); fseek(fpa, filesize/np*rank, SEEK_SET); fwrite ( &data[0], sizeof(double), filesize/(np*sizeof(double)), fpa); fclose ( fpa ); } } free(data); MPI_Finalize(); exit(0); } A: It looks like the issue is due to the fact that each child is opening the file for writing, which leads to contention. Try having the file name depend on the rank (for example, writing to out file.txt.(rank) and see if all of the outputs match up. A: If you're already using MPI and going to the trouble of using seek to partition up the file, rather than using POSIX I'd suggest using MPI-IO (standard as part of MPI2, c. 1996 or so): Good references are: * *http://www.mhpcc.edu/training/workshop2/mpi_io/MAIN.html *http://beige.ucs.indiana.edu/B673/node179.html and at our centre we have the first part of this, which I think is pretty good: * *https://support.scinet.utoronto.ca/wiki/images/a/aa/ParIO-HPCS2011.pdf An MPI-IOed version of your code above is this: #include <stdio.h> #include <stdlib.h> #include <mpi.h> int main(int argc, char** argv) { int rank, np; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &np); const int filesize = 48*1048576; //input filesize 48MB const int ndoubles = filesize/(sizeof(double)*np); double *localdata = malloc(ndoubles*sizeof(double)); /* create a type which describes our view of the file -- * in particular, just our subarray of the global array */ int globalsizes[1] = {filesize}; int localsizes[1] = {ndoubles}; int starts[1] = {ndoubles*rank}; MPI_Datatype fileview; MPI_Type_create_subarray(1, globalsizes, localsizes, starts, MPI_ORDER_C, MPI_DOUBLE, &fileview); MPI_Type_commit(&fileview); /* read in only our data */ MPI_File fpa; MPI_Status status; MPI_File_open(MPI_COMM_WORLD, "512_featurevec.out", MPI_MODE_RDONLY, MPI_INFO_NULL, &fpa); /* note could use MPI_File_seek instead of file set view */ MPI_File_set_view(fpa, (MPI_Offset)0, MPI_DOUBLE, fileview, "native", MPI_INFO_NULL); MPI_File_read_all(fpa, localdata, ndoubles, MPI_DOUBLE, &status); MPI_File_close(&fpa); /* write out data - it will have same layout, we're just writing instead of erading*/ MPI_File_open(MPI_COMM_WORLD, "output.dat", MPI_MODE_WRONLY|MPI_MODE_CREATE, MPI_INFO_NULL, &fpa); /* note could use MPI_File_seek instead of file set view */ MPI_File_set_view(fpa, (MPI_Offset)0, MPI_DOUBLE, fileview, "native", MPI_INFO_NULL); MPI_File_write_all(fpa, localdata, ndoubles, MPI_DOUBLE, &status); MPI_File_close(&fpa); free(localdata); MPI_Type_free(&fileview); MPI_Finalize(); return 0; } A: Answering my own question, but this works: char* outfile = "outfile.txt"; for(i=0; i<np; i++) { if(rank == i) { fpa = fopen ( outfile, "ab"); fseek(fpa, filesize/np*rank, SEEK_SET); fwrite ( &data[0], sizeof(double), filesize/(np*sizeof(double)), fpa); fclose ( fpa ); } MPI_Barrier(comm); } For some reason, if proc 1 arrives before proc 0 and fseeks an empty file to some value, it does position the file pointer to the correct offset (verified by ftell), but writes from offset 0 only. (I must be doing something trivially wrong, but anyway).
{ "language": "en", "url": "https://stackoverflow.com/questions/7603916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: stripping file.html out of the link So, I am writing a script that is suppose to illuminate different sections of the nav. each nav link is set up to be /directory/subdir/. It worked until I realized there needs to be more to this. if you are in a directory that is not the index file it doesn't work since it was directly matching HREF attribute. Now, how would I strip out the filename.html from the link and just get the directory? Thanks for all your help contributors! A: If i don't misunderstand, you're trying to hilight the your menu's link with href="/dir/abc/" while the page address is something like : /dir/abc/index.shtml /dir/abc/detail.shtml /dir/abc/etc.shtml right ? I've edited your code a bit. Hope this help : var loc = document.location.pathname; var nav = $('.mainNav a'); nav.each(function(index, element) { var href = $(this).attr('href') //-- edited if (loc.indexOf(href)==0) { //-- edited var node = nav.eq(index).parent('li'); var gpnode = node.parents('li'); node.addClass('active'); gpnode.addClass('active'); } }); A: /****** LINK DETECTION ******/ var nav = $('.mainNav a'); var loc = document.location.pathname; var pathname = document.location.pathname.substring(1); var parts = pathname.split(/\//); var x = parts.length; var hrefStr = "/"+parts[0]+"/"+parts[1]+"/"; switch (x) { case 2: $('.mainNav a').each(function(index, element) { if ($(this).attr('href') === loc) { var node = nav.eq(index).parent('li'); var gpnode = node.parents('li'); node.addClass('active'); gpnode.addClass('active'); } }); break; default: $('.mainNav a').each(function(index, element) { if ($(this).attr('href') === hrefStr) { var node = nav.eq(index).parent('li'); var gpnode = node.parents('li'); node.addClass('active'); gpnode.addClass('active'); } }); } /****** END LINK DETECTION ******/
{ "language": "en", "url": "https://stackoverflow.com/questions/7603917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Override previously used functions I'm in the process of making an irc bot with PHP. While developing, I want to be able to dynamically load and unload classes/functions. Mind you, the PHP is keep-alive. ex: Main File: class stuff { function stuff() { echo 'this'; } function replaceFunction() { remove(stuff); add(stuff); } } $stuff = new stuff(); Next I edit a function: function stuff() { echo 'that'; } So ideally, now that it's edited, all I have to do is trigger replaceFunction() to update the old function. How can I make this actually work? A: If the only thing you need is to have a class that has a function and you want to be able to exchange the functionality of that function by triggering the replaceFunction, you can assign some closure to that class or similar: class stuff { private $callback; public function __construct() { $this->callback = array($this, 'stuff'); } public function __invoke() { call_user_func($this->callback); } private function stuff() { echo 'This'; } function replace($function) { $this->callback = $function; } } $stuff = new stuff; $stuff(); # original function $stuff->replace(function() { echo 'That'; }); $stuff(); # replaced function Or the short version: $stuff = function() {echo 'This';}; $stuff(); # original function $stuff = function() {echo 'That';}; $stuff(); # replaced function The class has the benefit that you have more control about assigning and invoking the function. A: Maybe you can remove the functions first runkit_function_remove ( string $funcname ); Use function_exists() to check if the function already exists. EDIT: class stuff { function replaceFunction() { runkit_function_remove('stuff'); function stuff() { echo 'New stuff'; } } } $stuff = new stuff(); $stuff->replaceFunction();
{ "language": "en", "url": "https://stackoverflow.com/questions/7603919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jar protocol and php page I have a need to hide a locationbar in a child's page (html) for firefox, but The parent page is (php). I found article about that; http://kerneltrap.org/node/65367. I have now HTML file and .JS file that hide the location bar after signed it. But there is a php file, php's file that call the html to do what i need. I found jar protocol can call html without any problem; but Jar can't call php file, is there a solution for that, or jar is not support php. advise me please A: just rename your html file to php and use a include or require to call the php file. As a php file anything not inside a <? yourcodehere ?> or <?php yourcodehre ?> is interpretted as html.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can an X # of rows be generated without using stored procedures or functions? I have written the below VIEW using a UDF, but am wondering if there is a way to do this without needing a UDF. The only other option I could find is to SELECT UNION hardcoded values, but I don't like that. Any suggestions or should I just leave it as it is? I am using MS SQL Server 2008 R2, so anything available there is free game. CREATE FUNCTION GetN(@N int) RETURNS @numbers TABLE (N int PRIMARY KEY NOT NULL) AS BEGIN DECLARE @i int SET @i = 0 WHILE (@i < @N) BEGIN INSERT @numbers SELECT @i SET @i = @i + 1 END RETURN END GO CREATE VIEW Last10Weeks AS SELECT DATEPART(wk, GETDATE())-N as WeekNumber , DATEADD(day, (N*-7) - 1 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()) AS StartDate , DATEADD(day, (N*-7) + 5 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()) AS EndDate FROM GetN(10) A: Here's a way using a recursive CTE: WITH TestData as ( SELECT 1 as N UNION ALL SELECT N + 1 FROM TestData WHERE N < 10 ) SELECT N, DATEPART(wk, GETDATE())-N as WeekNumber, DATEADD(day, (N*-7) - 1 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()) AS StartDate, DATEADD(day, (N*-7) + 5 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()) AS EndDate FROM TestData The "count" is specified by the "N < 10" part at the end of the second SELECT. Prints out: N WeekNumber StartDate EndDate 1 39 2011-09-18 15:24:40.800 2011-09-24 15:24:40.800 2 38 2011-09-11 15:24:40.800 2011-09-17 15:24:40.800 3 37 2011-09-04 15:24:40.800 2011-09-10 15:24:40.800 4 36 2011-08-28 15:24:40.800 2011-09-03 15:24:40.800 5 35 2011-08-21 15:24:40.800 2011-08-27 15:24:40.800 6 34 2011-08-14 15:24:40.800 2011-08-20 15:24:40.800 7 33 2011-08-07 15:24:40.800 2011-08-13 15:24:40.800 8 32 2011-07-31 15:24:40.800 2011-08-06 15:24:40.800 9 31 2011-07-24 15:24:40.800 2011-07-30 15:24:40.800 10 30 2011-07-17 15:24:40.800 2011-07-23 15:24:40.800
{ "language": "en", "url": "https://stackoverflow.com/questions/7603931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Implementing a c# interface that has an event through COM to VB6 I have a VB6 class that needs to implement an interface which I created in C#. I have been able to succesfully implement all of the properties of the interface in my vb6 class over COM, but have not been able to implement the event that it has. If I understand correctly, I will need to have the equivalent of the add and remove accessors defined to register consumers of the event, but I cannot get VB6 to accept the interface with the event defined. I am setting the InterfaceType of the class to InterfaceIsIDispatch, but still get the error "Bad interface for Implements: method has underscore in name" when I try to compile. The interface does not define any methods, and neither the properties nor the event have any underscores. Here is the interface definition namespace AV8B.Overlay { [ComVisible(true)] [Guid("89519DCE-86D6-4962-8CEA-450F2AB31B4E")] public delegate void OverlaySymbolPropertyChangedEventHandler(object sender, OverlaySymbolPropertyChangedEventArgs e); [ComVisible(true)] [Guid("9A59EF10-B688-4af9-8C21-FB95C7ED699A")] public class OverlaySymbolPropertyChangedEventArgs : PropertyChangedEventArgs { OverlaySymbolPropertyChangedEventArgs(string propertyName) : base(propertyName) { } } [ComVisible(true)] [Guid("379B179C-85FA-4efb-8198-D1A4C80D645A")] public interface IOverlaySymbol : INotifyPropertyChanged { bool SelectedForProcessing { get; set; } int SymbolNumber { get; } string SymbolType { get; } double Latitude { get; } double Longitude { get; } string Color { get; } int Size { get; } /// <summary> /// This method fires the PropertyChanged event. /// </summary> void NotifyPropertyChanged(); /// <summary> /// The event that fires when a property changes. /// </summary> new event OverlaySymbolPropertyChangedEventHandler PropertyChanged; } } The goal behind this is to place existing VB objects that implement this interface into a binding list which will be attached to a list grid view. The list grid view needs to know when the properties of its items change so it can update accordingly. A: INotifyPropertyChanged is mostly used with property bindings just as you described. Specifically VB6 controls (and ActiveX controls in general) have this mostly already built-in, but its a different interface. You could perhaps work it the other way round: Your grid accepts .Net Controls with INotifyPropertyChanged and ActiveX controls with INotifyPropertySink. Some relevant helpers may be: * *How to fire property changed notifications from C# to COM using IPropertyNotifySink? *Connect to COM events in C# - support both managed and unmanaged servers Thumbs up! A: it sound very complex. Maybe one better approach will be 1)Create one implementation of your interface it on .net and use one pattern how "Active Record" para behavior 2)After create one wrapper for that with methods simples how entityChange(parameters) saveChange(parameters) SaveAll CancellAll from .net you can throw events to vb6 (for update grid or do something) here examples list http://www.elguille.info/NET/servidorNETparaCOM/servidorNETparaCOM.htm mix all and do test A: There is no way to implement events in VB6, even when using native VB6 class that has events declared. What you can do to handle this impedance is to pass a callback interface to VB6 objects and implement a proxy in .Net that raises your events in callback methods implementation. The proxy will obviously need to forward properties/methods too. A: An option is to use standard COM events which handle the interface, subscribe, unsubscrie, etc for you. If you just have a single object, then normal event/delegate pairs will be exposed as COM events, but for more complex interfaces and events, you need to create your event sink interface and asociate it with the each class itself using: [System.Runtime.InteropServices.ComSourceInterfaces(typeof(ISystem_COMEventSink))]
{ "language": "en", "url": "https://stackoverflow.com/questions/7603932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to change Spark BorderContainer default height? How to create horizontal layout container like HGroup but with border and border radius? In this example there is some default height: <s:BorderContainer width="100%" borderWeight="2" cornerRadius="5"> <s:layout> <s:HorizontalLayout/> </s:layout> <s:Image source="image.png" /> <mx:Text text="text example" /> </s:BorderContainer> I want it to have height of the heighest element in container. Like in HGroup. Add: Why is height for above example BorderContainer equal to 112 ? A: @Nemi Just set the minHeight property of the BorderContainer to 0. A: It is hard to get height of the heighest element in container. better my suggestion is to use like this <s:BorderContainer width="100%" height="{hGroup.height}" borderWeight="2" cornerRadius="5"> <s:HGroup width="100%" id="hGroup"> <s:Image source="image.png" /> <mx:Text text="text example" /> </s:HGroup> </s:BorderContainer> This might set the highest child height to the borderContainer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Load xml data from an url like this : /index.php/site/projects/ as a php variable I need to read xml data generated by a php file(of Expression Engine) on passing url like /index.php/site/projects/ into a php object. (note that it is not a physical file). How can I do that ? Since I am not quite aware of php stuff please pardon me in case I have asked something silly & let me know in case I can add more information. A: Perhaps you could use SimpleXML, the DOMDocument class, or cURL. Edit: An example taken from the documentation of simplexml_load_file <?php // The file test.xml contains an XML document with a root element // and at least an element /[root]/title. if (file_exists('http://domain.com/index.php/site/projects/')) { $xml = simplexml_load_file('http://domain.com/index.php/site/projects/'); print_r($xml); } else { exit('Failed to open the xml file.'); } ?> I'm not an expert on this, but there are lots of good hints, examples, and notes on the page I linked to. A: You can use simplexml_load_file(string $filename) to this end. Just pass into this function the full URL such as: $myXMLContent = simplexml_load_file('http://myserver.com/index.php/site/projects/'); Then if you need to use this information, note that all nodes that are not repetitive will be accessible directly using: $myXMLContent->nodename Then all attributes are part of an array of the node, so: <nodename id="6" name="blabla"><subnode>Content</subnode></nodename> Can be fetched as: echo $myXMLContent['id']; echo $myXMLContent['name']; echo $myXMLContent->subnode; And if you have many subnodes at once, you can use: echo $myXMLContent->subnode[2] To get the 3rd subnode. This is the best i can do to help you, the rest can be found at: http://www.php.net/manual/fr/book.simplexml.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7603937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: eglQuerySurface gives wrong size When I rotate my device and my app recieves APP_CMD_CONFIG_CHANGED, I attempt to update my OpenGL viewport with the following: EGLint width; EGLint height; eglQuerySurface(display,surface,EGL_WIDTH,&width); eglQuerySurface(display,surface,EGL_HEIGHT,&height); glViewport(0,0,width,height); MY_LOG_MACRO2("New window size: %d x %d",width,height); This works about 20% of the time. The other 80% of the time the width and height are the previous values. In other words, most of the time when I turn my device to landscape mode, the portrait size is logged. And when I go back to portrait, the landscape size is logged. I haven't had much luck with getting the size from the ANativeWindow either. What should I be doing to get correct window size after rotation? Update: By waiting a few frames after APP_CMD_CONFIG_CHANGED, the size is always correct. Querying the size every frame, without regard for APP_CMD_CONFIG_CHANGED, and checking if it has changed seems to work as well but feels wrong. A: For detecting screen orientation changing I've decided do not catch APP_CMD_CONFIG_CHANGED, but call eglQuerySurface() every frame. If screen size values mismatch saved values, screen orientation has been changed. Two calls of eglQuerySurface() for getting width and height take about 10 microseconds (100 milliseconds when called 10000 times) so it doesn't reduce performance and it give 100% guarantee that screen rotation will be handled. I think this solution is better than waiting several frames after APP_CMD_CONFIG_CHANGED. By the way, rotating device to 180 degree (upside down) cause getting APP_CMD_CONFIG_CHANGED event but actually no screen orientation has been changed and no resize-depended actions should be performed. A: It might not work because for example surface size might be set when creating context, and you querying for 'previous' size (when context was created). Edit: I've tested it on SGS2(2.3.5) and I get correct results immediatelly, so it might be a device 'vendor' problem (or Android version problem). Edit2: It looks that I've made some mistake while testing, I'm getting weird results too as @IronMensan. Sometimes it works correctly, but mostly not. Sorry for my mistake. So I would stay at recreation of EGL context as in my initial answer (below). When I get APP_CMD_CONFIG_CHANGED I just simply destroy and recreate EGL context (with shaders, textures, etc.), similar when I get APP_CMD_TERM_WINDOW -> APP_CMD_INIT_WINDOW.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Extern variable in header file not linked properly to source file where it is defined Problem: A variable 'VarOriginal' is defined in source C file under pragma say 'parameterX' and declared as an extern variable in a header file under the same pragma 'parameterX'. There is a process using it in which it is known that the variable is shown declared in some other header file where this variable is not present at all. As a Workaround:I declared one more different variable 'VarNew' before the pragma 'parameterX' in the header file and similarly defined the variable 'VarNew' before the line where 'VarOriginal' was defined. And it all worked. Header file: header_file_with_problem.h #ifndef HEADER_FILE_WITH_PROBLEM_H #define HEADER_FILE_WITH_PROBLEM_H #include "ABC.h" declare variable 'VarNew' here <------ #pragma BSS(".parameterX") extern int VarOriginal; #pragma BSS(DEFAULT_SECTION_BSS) Source C File: #define HEADER_FILE_WITH_PROBLEM_C #include "XYZ.h" #include "header_file_with_problem.h" declare variable 'VarNew' here <------ #pragma BSS(".parameterX") int VarOriginal; #pragma BSS(DEFAULT_SECTION_BSS) But I am not able to understand why the problem was coming earlier. Why was the linker not able to find the definition of 'VarOriginal' in the source file and now it is able to do so, after declaring another variable before 'VarOriginal' itself? Also, this problem is not with all source and header files present in the folder, but only a few of them. A: I don't see anything defined in your source file. The extern int VarOriginal; is still a non-defining declaration, regardless of where you put it (source file or header file). There's not a single variable definition in your code sample, so no wonder the linker is complaining about missing definitions. In order to define a variable in your C file you need to do either int VarOriginal; /* no `extern` !!! */ or add an explicit initializer extern int VarOriginal = 0; /* definition */ A mere extern int VarOriginal; /* not a definition!!! */ that you seem to have there now (according to what you posted) is not a definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone - Animate 2 subviews at the same time I have 2 subviews that take the whole screen (excepted the status bar). Let's call this size "screen size". I want to animated both : * *the first to zoom from a little bit larger than the screen size to the screen size, from alpha 0 to alpha 1. *The second from screen size to a little bit smaller than screen size, from alpha 1 to alpha 0. The second view is visible and on screen at start. I wrote this : - (void) switchViews { if (self.view2Controller == nil) { self.view2Controller = [[View2Controller alloc] initWithNibName:@"View2XIB" bundle:nil]; self.view2Controller.view.hidden = YES; [self.view addSubview:self.view2Controller.view]; } CGRect bigFrame = CGRectInset(self.view.frame, -50, -50); CGRect normalFrame = self.view.frame; CGRect smallFrame = CGRectInset(self.view.frame, 50, 50); self.view2Controller.view.frame = bigFrame; self.view2Controller.view.alpha = 0.0; [UIView beginAnimations:@"Anim1" context:nil]; [UIView setAnimationDuration:5]; [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; self.view2Controller.view.hidden = NO; self.view2Controller.view.frame = normalFrame; self.view2Controller.view.alpha = 1.0; [UIView commitAnimations]; // ------------------------------ [UIView beginAnimations:@"Anim2" context:nil]; [UIView setAnimationDuration:5]; [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)]; self.view1Controller.view.frame = smallFrame; self.view1Controller.view.alpha = 0.0; [UIView commitAnimations]; } Of course, I've tried first to put both animations into an unique one. That does not change anything, that's why I tried to separate them. When launched, view1 goes immediatly to black, then the view2 starts animating as expected. But I can't achieve to run both animations at the same time. How would I do that ? A: Try taking a look at block-based animations. It's the iOS 4.0+ recommended method. Take a look at the answer here: What are block-based animation methods in iPhone OS 4.0? EDIT Try something like this //You can do the same thing with a frame CGPoint newCenter = CGPointMake(100, 100); [UIView animateWithDuration:2.0 animations:^{ firstView.center = newCenter; secondView.center = newCenter; firstView.alpha = 0.2; } completion:^(BOOL finished){ NSLog(@"All done animating"); }]; Anything you put inside of animations: ^{ } will be the destination settings of your view. Above I showed you how to change the position as well as the alpha. A: I think what you want to use is a CAAnimationGroup (Core Animation Group). CAAnimationGroup allows multiple animations to be grouped and run concurrently. The grouped animations run in the time space specified by the CAAnimationGroup instance. It has an animations property which you set as the array of animations you want it to do with setAnimations:. Here is a usage example A: i cannot see anything wrong in your code. so i tried your code in my project and it work well: it does exactly what you wanted. View1 move down-right and fade-out WHILE view2 come from top left and fade-in... so i guess you have to look for an error somewhere else... ciao, luca EDIT: here's the code: test-switch.zip
{ "language": "en", "url": "https://stackoverflow.com/questions/7603948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding facet titles and changing legend title in ggplot2 I wonder how to add facet titles in ggplot2 ggplot(diamonds, aes(cut)) + geom_bar() + facet_grid(color ~ clarity) and change the legend title ggplot(diamonds, aes(cut, fill=cut)) + geom_bar() + facet_grid(. ~ clarity) Thanks for your help. A: The facets are labeled using the levels of the factor used. So if you simply change the levels , such as levels(diamonds$clarity) <- letters[1:8] those facets will now be labeled using those letters. The legend title matches the label for that aesthetic mapping, which you can set via: + labs(fill = "Fill legend label") As an extra tidbit, I've noticed that I can set the x and y axis labels to NULL in labs but not the legend titles; for those you use an empty character if you want no title. Edit Given your clarifications, you can add text outside the plotting area using grid.text: print(qplot(1,1),vp = viewport(width = 0.9)) grid.text(unit(0.95,"npc"),0.5,label = "Right label", rot = 270)
{ "language": "en", "url": "https://stackoverflow.com/questions/7603949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Summing integers the instructions are: Enter an integer (32 bit) and sum its digits, you may be given a negative or positive integer. When reading in a negative integer, sum the digits but ignore the - sign. this is what I have. Somehow I can't get it to ignore the negative signs when the integer is negative. import java.util.Scanner; public class Exercise2_6M { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Enter amount System.out.print("Enter an integer:"); int integer = input.nextInt(); if (integer < 0) integer = -integer; // Calculations int rinteger = Math. abs (integer); int lastinteger = integer % 10; int X = integer / 10; int secondinteger= X % 10; int firstinteger = X /10; int finalinteger = firstinteger + secondinteger + lastinteger; // Display results System.out.println("Sum all digits in " + rinteger + " is " + finalinteger); } } A: When I run it, it ignores the negatives just like it's supposed to. There are two problems I see. * *When you print out for a negative number, it prints positive instead. Consider storing the original value for printing. *It doesn't work for large numbers because you hard code for 3 digits. Consider putting this in a loop to get all the digits. Here's my test outputs: The first is good, second is good, third should say "Sum all digits in -4 is 4", and last should say "Sum all digits in 12345 is 15". C:\Documents and Settings\glowcoder\My Documents>java Exercise2_6M Enter an integer:5 Sum all digits in 5 is 5 C:\Documents and Settings\glowcoder\My Documents>java Exercise2_6M Enter an integer:100 Sum all digits in 100 is 1 C:\Documents and Settings\glowcoder\My Documents>java Exercise2_6M Enter an integer:-4 Sum all digits in 4 is 4 C:\Documents and Settings\glowcoder\My Documents>java Exercise2_6M Enter an integer:12345 Sum all digits in 12345 is 132 A: To ignore the negative sign: int integer = Math.abs(input.nextInt()); Edit: I didn't notice that your code already did this. To make the code show the negative sign at the end, get rid of the following lines: if (integer < 0) integer = -integer; since you're already doing int rinteger = Math. abs (integer); Then, replace all instances other than the fist of integer in the calculations sections with rinteger, like this // Calculations int rinteger = Math. abs (integer); int lastinteger = rinteger % 10; int X = rinteger / 10; int secondinteger= X % 10; int firstinteger = X /10; int finalinteger = firstinteger + secondinteger + lastinteger; Finally, when displaying the results, use integer instead of rinteger to restore the minus sign, or just put in a minus sign manually if integer<0. Your code is also flawed if integer is more than 3 digits, as others have pointed out, but that's a separate issue. To add more than 3 digits, you'll need a loop. Try this: import java.util.Scanner; public class Exercise2_6M { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Enter amount System.out.print("Enter an integer: "); int integer = input.nextInt(); // Calculations int rinteger = Math. abs (integer); int sum = 0; int i=0; //loop through each digit (starting from the least significant) until the end of the number while(rinteger / Math.pow(10,i) > 0) { sum+=getDigit(rinteger,i); i++; } // Display results System.out.println("Sum all digits in " + integer + " is " + sum); } public static int getDigit(int num, int power) { return (num % (int)Math.pow(10,power+1)) / (int)Math.pow(10,power); } } A: I can't recall specifically, but integer might be a reserved java keyword, so you might want to change that variable name (i.e. inputInt or something). The thought behind your code looks sounds... but instead of: integer = -integer; try: inputInt = (-1)*inputInt; That should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.Net MVC Html Helper Extension What is the best way to extend Html Helper TextboxFor? Is there a way to reuse the defautl implementation? A: You can create your extension methods (in a static class), for example: public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { // call original method MvcHtmlString result = InputExtensions.TextBoxFor(helper, expression); // do modification to result return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Flex - how to make a tabbed panel My app has 3 categories of buttons, I want to have a tabbed panel I can use to switch between the 3 categories like in this example: My app is a mobile app though so I can't use mx components. When I try searching for mobile tabbed navigation etc., I come up with only viewnavigator examples. A: For a mobile tabbed application, you simply use the TabbedViewNavigatorApplication class: FIRST METHOD Your views are simply MXML components that use <s:View> as the root note. Reading your comments, I see that you want a tabbed bar within your view. In normal Flex, you would use a TabBar and attach it to a ViewStack but ViewStack is not available in mobile... so you can improvise using states, binding a TabBar to the names of the states and hide/show panels based on state. Here is an example: SECOND METHOD* <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView"> <s:layout> <s:VerticalLayout /> </s:layout> <s:states> <s:State name="One" /> <s:State name="Two" /> <s:State name="Three" /> </s:states> <s:TabBar id="tabBar" width="100%" change="currentState = tabBar.dataProvider[event.newIndex]"> <s:ArrayCollection> {states.map(function(x) { return x.name; }) } </s:ArrayCollection> </s:TabBar> <s:Group includeIn="One" width="100%" height="100%"> <s:Label text="Tab One" /> </s:Group> <s:Group includeIn="Two" width="100%" height="100%"> <s:Label text="Tab Two" /> </s:Group> <s:Group includeIn="Three" width="100%" height="100%"> <s:Label text="Tab Three" /> </s:Group> </s:View> BUT, you might still want to keep the mobile tab navigation functionality but only for one particular view. You can include a TabbedViewNavigator inside of your view instead of using a TabbedViewNavigatorApplication. THIRD METHOD <s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView"> <s:TabbedViewNavigator width="100%" height="100%"> <s:ViewNavigator label="1st Tab" width="100%" height="100%" firstView="views.FirstTabView"/> <s:ViewNavigator label="2nd Tab" width="100%" height="100%" firstView="views.SecondTabView"/> <s:ViewNavigator label="3rd Tab" width="100%" height="100%" firstView="views.ThirdTabView"/> </s:TabbedViewNavigator> </s:View> You will get a nested "Action Bar" so you can disable the nested one in each of the tab views by setting actionBarVisible="false" Hope this helps!!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7603957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: qTip: prevent hiding the tip two times successively First of all sorry guys for posting the question here. The support forum seems to be almost dead. So I've run into a bug in the qtip plugin or my code. When I call .qtip('hide') twice or more times consecutively, the tooltip will hide and never show again when calling .qtip('show'). The way to reproduce: el.qtip('hide');el.qtip('hide');el.qtip('show'); \\ -> bug, the tip is not shown el.qtip('hide');el.qtip('hide');el.qtip('hide');el.qtip('show'); \\ -> bug, same Consecutive show works good... el.qtip('show');el.qtip('show');el.qtip('hide');el.qtip('show'); \\ -> pass Non - consecutive hide also works good: el.qtip('hide');el.qtip('show');el.qtip('hide');el.qtip('show'); \\ -> pass The question is: How to make things work? The qTip api does not give me a way to find if the tip is hidden or shown. How can I know that? I can check if the qTip is hidden not to hide it twice. Possible source of problem: The qtip causing errors is constructed in a rather tricky way: qtip({ content: text, position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' } }, style: { tip: { corner: 'leftMiddle', }, border: { radius: 11, width: 4 }, name: 'red' }, show: { delay:0, ready: true, fixed:true, when: { target: false, event:false }, effect: function() {//.stop(true, true) $(this).effect("drop", { direction: "down", mode: "show" }, 240) } }, hide: { delay:0, fixed:true, when: { target: false, event:false }, effect: function() {//.stop(true, true) $(this).effect("drop", { direction: "down", mode: "hide" }, 240) } } }) To test this, you can go to www.buxdial.com/oldo/register.php, type anything in the captcha field, go to debugger and run the tests, replacing el with code.TIP A: If you have just one instance of a qtip on your page you can check to see if the qtip is currently showing by searching for the qtip-active class. Here is an example using jquery on how to check: if($('div.qtip-active').length) { alert("qtip is currently showing"); } else { alert("qtip is hidden"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7603959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure: Using PHP as WebRole and using c# as WorkRole? How to package the service pack? I'm trying to use PHP as the web role and use C# as the work role. But how to package them together into a service package? I use PHPAzure SDK for php development, which contains a package tool named "package". But it is used for PHP codes. I don't know how to add C# codes and PHP codes together. Also, is it possible using "cspack" command? Thanks! A: I'll look into this over the next week. For now, what yo ucan do is create 2 hosted services, for example: * *myphpapp.cloudapp.net just running your PHP code *myworker.cloudapp.net which will be a regular C# worker role project
{ "language": "en", "url": "https://stackoverflow.com/questions/7603963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: problems with memcpy of strings I am trying to * *take two strings (message1, message2), *assign str1 to message1 if message1 and message2 are empty, *assign str2 to message2 if it is empty and message1 is full, *and save message 2 over message 1 and put message2 == message3 if both message1 and message2 were full. I get weird results as shown. But memcpy is not working. (I know it's my fault somehow.) input message1: ffW message 2: a message 3 (2 writes over 1, 3 writes over 2): bbb MESSAGE 1a: ffW MESSAGE 2a: a_W MESSAGE 1ab: a_W MESSAGE 2ab: a_W MESSAGE 1b: a_W MESSAGE 2b: bbb next one: INPUT: message1: a message2: abcde message3: abcdefg MESSAGE 1a: a�� MESSAGE 2a: abcde MESSAGE 1ab: abcd MESSAGE 2ab: abcde MESSAGE 1b: abcd MESSAGE 2b: abcdefg . if (message1[0] == '\0') { memcpy(message1, echoBuffer, sizeof echoBuffer); fprintf(stderr, "MESSAGE 1: %s \n", message1); } else if (message1[0] != '\0' && message2[0] == '\0') { memcpy(message2, echoBuffer, sizeof echoBuffer); fprintf(stderr, "MESSAGE 2: %s \n", message2); } else if (message1[0] != '\0' && message2[0] != '\0') { fprintf(stderr, "MESSAGE 1a: %s \n", message1); fprintf(stderr, "MESSAGE 2a: %s \n", message2); memcpy(message1, message2, sizeof message2); fprintf(stderr, "MESSAGE 1ab: %s \n", message1); fprintf(stderr, "MESSAGE 2ab: %s \n", message2); memcpy(message2, echoBuffer, sizeof echoBuffer); fprintf(stderr, "MESSAGE 1b: %s \n", message1); fprintf(stderr, "MESSAGE 2b: %s \n", message2); } } Does anybody know what is wrong? This problem has been plaguing me. I think the messages and echoBuffer are all 100 characters in size. A: Is there a particular reason for using memcpy? I believe that strcpy(char* dest, char* source) would be easier to use. Maybe it could fix your problem You must include string.h in order to use it A: You sure about sizeof? As I remember sizeof show size of datatype not real length of char arrays/strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cross-Domain issues on mobile Safari on iPhone, iPod & iPad I have a chat built with node. This chat is running on port 3000 of example.com. I am using this chat within the page of the same domain by calling it with jQuery's ajax call. So I have chat running on example.com:3000 and website that is including this chat running on example.com:80. Because different ports (even on the same domain) are already violation of the same-origin policy, I included in my node server headers "Access-Control-Allow-Origin" : "*" to allow cross calls to my chat. Because ajax loaded chat was looking for it's js/css files on example.com:80 I had to set paths to my js/css files on example.com:3000 to absolute paths. So chat is looking for it's js/css files with "http://example.com:3000/css/style.css" and "http://example.com:3000/js/client.js". This is working all well using regular browsers (Safari, Firefox, Chrome, etc.) for both, chat at it's own example.com:3000 and included within the example.com:80. However, and this is the issue, it doesn't work on any mobile Safari (iPhone,iPod,Ipad). Main page of chat will load just fine with ajax call, but the subsequent js/css files are not loaded. I can't use relative paths as client.js and style.css files are sitting on example.com:3000 which is cross-domain. Is there any other place I need to place "Access-Control-Allow-Origin" setting? Or is there anything I need to do about paths? Or is there some setup within jQuery I need to do to make this work? I am out of ideas as there are no debugging tools on mobile Safari other than reporting errors. Which I am getting none. A: Actually I should have used iframe if I wanted embeded chat to be able to pull it's own internal files. That's what I ended up doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TextMate: Bundle to wrap selected text with php commenting I am new to TextMate, and so far I am loving it! Prior to TextMate, I was using Dreamweaver. Dreamweaver has a nice feature where you select your text, and wrap it with php commenting. <?php /* */?>. This was especially useful for temporarily wrapping large blocks of code which already contained html commenting. E.g. > <?php /* <div class="container"> <p>My Paragraph</p> </div><!--End container--> [...] <div class="container"> <p>My Paragraph</p> </div><!--End container--> */ ?> Is there already a bundle for this? I think this would be a good and maybe even standard bundle! A: If you haven't already figured this out, there is. Command+/ will comment selected text in any language you are programming in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert a list item with html I have an unordered list, and I am trying to insert an element at the end jQuery("<li>").text(" | Billed (14)").appendTo('.subsubsub') However, I would like it to be formated with the following | <a href=''>Billed <span class='count'>(14)</span></a> But when I do: jQuery("<li>").text(" | <a href=''>Billed <span class='count'>(14)</span></a>").appendTo('.subsubsub') It just prints the entities instead of parsing them. A: You must use .html() to inject html. jQuery("<li>").html(" | <a href=''>Billed <span class='count'>(14)</span></a>") .appendTo('.subsubsub') A: text() is not for HTML, it escapes any HTML characters, use html()
{ "language": "en", "url": "https://stackoverflow.com/questions/7603976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java client build error: apache.cassandra not found I am trying to build a java client to talk with cassandra, when i ant release, i got error that module not found org.apache.cassandra#apacke.cassandra;0.85 I have installed cassandra 0.85 and put dependeny in ivy.xml file as below I have even tried to tell javac in build.xml the path of the jar such as <target name="compile" depends="clean"> <mkdir dir="${build.dir.classes}"/> <javac srcdir="${src.java.dir}" destdir="${build.dir.classes}" debug="${javac.debug}" includeantruntime="false"> <classpath refid="test.classpath"> <pathelement path="/usr/share/cassandra/lib/apache-cassandra-0.8.5.jar /> </classpath> </javac></target> any help will be appreciated A: "module not found org.apache.cassandra#apacke.cassandra;0.85" did you mean, org.apache.cassandra#apache.cassandra;0.85
{ "language": "en", "url": "https://stackoverflow.com/questions/7603980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ initialization lists for multiple variables I'm trying to learn how to initialize lists. I have a simple class below and trying to initialize the list of variables. The first Month(int m): month(m) works. I'm trying to do something similar below that line with more than one variable. Is this possible in that format? would I have to break away from the one liner? class Month { public: Month(int m) : month(m) {} //this works Month(char first, char second, char third) : first(first){} : second(second){} : third(third){} //DOES NOT WORK Month(); void outputMonthNumber(); //void function that takes no parameters void outputMonthLetters(); //void function that takes no parameters private: int month; char first; char second; char third; }; Obviously I don't have much clue how to do this, any guidance would be appreciated, thanks A: Month(char first, char second, char third) : first(first) , second(second) , third(third) {} //DOES WORK :) A: As others have pointed out, it's just a comma seperated list of items. The variable(value) syntax is just a default way of constructing primative datatypes, you can use this method outside of initialization lists for example. In addition, if a member of your class is also a class with a constructor, you'd call it in the exact same way. You are not only bound to putting the list in the declaration of the class, just for future reference. This code is perfectly fine for example class Calender{ public: Calender(int month, int day, int year); private: int currentYear; Time time; }; Calender::Calender(int month, int day, int year) : currentYear(year), time(month, day) { // do constructor stuff, or leave empty }; A: Try this: Month(char first, char second, char third) : first(first), second(second), third(third) {} [You can do this as a single line. I've split it merely for presentation.] The empty braces {} are the single body of the constructor, which in this case is empty. A: Initializers are comma-separated, and your constructor should have only one body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Firebird + JDBC: Getting the generated key from an insert It looks like Firebird does NOT support getGeneratedKeys() after you perform an insert with an auto_increment column. So I would like to understand how I can get my hands on the generated key after an insert. 1) Do I have to use "insert into users(...) values(...) returning id" and call this through a CallableStatement in order to get the generated ID? How exactly? Do I need to wrap my insert around a "call { ... }" 2) Is there some other way of getting the generated id under Firebird, some kind of "select last_id_generated()". "select max(id) from users" does not count. 3) Is it really true that getGeneratedKeys() is not supported by Firebird JDBC driver? (optional) Thanks! A: It turns out that all you have to do is call the "insert ... returning" with executeQuery (from PreparedStatement) instead of executeUpdate. That will return your ResultSet from where you can get the generated id. I never thought that you could call an INSERT with executeQuery. I thought you had to do executeUpdate. A: I am using construction to get primary key value: String buf = "SELECT GEN_ID ( <YOUR_ID_NAME*>, 0 ) " + //see description below "FROM RDB$DATABASE"; try { Statement stm = conn.createStatement (); ResultSet RS = stm.executeQuery ( buf ); buf = null; if ( RS != null ) { RS.next (); buf = RS.getString ( 1 ).trim (); //That is it RS.close (); } } catch ( SQLException e ) {} Now buf contains id < *>- You can see it with help IBExpert. A: Support for getGeneratedKeys was added in Jaybird 2.2. There are some caveats, the default RETURN_GENERATED_KEYS method will return all columns of the table, so you should retrieve columns from the result set by column name, or use one of the methods to explicitly specify the column index or column name, see the Jaybird (2.2.7) release notes for more details. To answer your original questions: * *When you execute INSERT ... RETURNING ..., you need to use executeQuery (or execute), and process the result set as if you are executing a normal SELECT. With Jaybird 2.2 you can also use executeUpdate if you are using RETURN_GENERATED_KEYS and obtain the result set from getGeneratedKeys() *Using INSERT ... RETURNING ... or getGeneratedKeys is the only way to get the generated value for that statement, all other methods (like SELECT GEN_ID(GEN_NAME,0) FROM RDB$DATABASE) cannot be trusted as sequences are outside of transaction control and the returned value might have been generated for a different concurrent transaction. *At the time you asked this question it was indeed not supported by Jaybird (2.1.6). Disclosure: I am one of the developers of Jaybird. A: this will get the current generation SELECT GEN_ID(GEN_NAME,0) FROM RDB$DATABASE with GEN_NAME being what you called that generation when you create a auto increment field a trigger and a generation is created the trigger looks like this usually SET TERM ^^ ; CREATE TRIGGER TABLE_BEFOREINSERT FOR TABLE ACTIVE BEFORE INSERT POSITION 0 AS BEGIN if ( new.ID is null ) then new.ID = gen_id(GEN_TABLE, 1); END ^^ SET TERM ; ^^ and the creation for the generation looks like this CREATE GENERATOR GEN_TABLE; SET GENERATOR GEN_TABLE TO 32; these two together make is so that BEFORE a new row is inserted, it checks to see if you specified the value of ID, if not it increases the generation by one and gets its current value and puts it as the ID column
{ "language": "en", "url": "https://stackoverflow.com/questions/7603985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery UI resizable: elem is undefined error in jQuery's acceptData function I'm using jQuery UI Resizable to resize a div. I'm getting "elem is undefined" error in console and I can't figure out what is wrong. I've tried different jQuery versions. You can see my app at: http://klip.dev.xhtml.si The arrows in the middle of content is the handler for resizable. A: I also have this problem. I updated JQuery, so it checks if the element is undefined: acceptData: function( elem ) { /* Add this line to the code */ if(elem === undefined) return false; And by the way, I am using jQuery v1.8.3
{ "language": "en", "url": "https://stackoverflow.com/questions/7603988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to connect to a database with Oracle SQL Developer I need to connect to a database with Oracle SQL-Developer. What I know from the DB is the Instance name and a Database Role. How do I connect to the database or what more information do I need? A: Oracle has excellent documentation on creating connections in SQL Developer both within the application help, but also on their technology network website: OTN Getting Started with SQL Developer. This viewlet found on that page nicely walks you through the process Connect to Database. You will need a username and password, the hostname and port, and a SID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ordering by grouped dates in database hi got a similar problem to this question Tricky "grouped" ordering in SQL but cant seem to make it work with dates my table sort of Car_ID Car_Brand Car_Model Car_launch_date 1 Ford Fiesta 12-12-2011 2 Ford Mustang 09-04-2008 3 Ford Focus 10-02-2012 4 Honda Civic 11-05-2012 6 Honda Jazz 02-05-2011 7 Toyota Prius 11-10-2011 i want my results ordered by future dates closest to now, then followed by past dates closest to now (and grouped by brand) I want my output to be this: Car_ID Car_Brand Car_Model Car_launch_date 7 Toyota Prius 11-10-2011 1 Ford Fiesta 12-12-2011 3 Ford Focus 10-02-2012 2 Ford Mustang 09-04-2008 4 Honda Civic 11-05-2012 6 Honda Jazz 02-05-2011 A: Are your dates in the database as DATE objects or strings? Because if you try to order them as strings, that won't work! If the dates are DATEs, try: SELECT * from my_table ORDER BY Car_Brand DESC, Car_launch_date < NOW(), ABS(DATEDIFF(Car_launch_date, NOW())) If they're strings, try: SELECT * from my_table ORDER BY Car_Brand DESC, DATE(Car_launch_date) < NOW(), ABS(DATEDIFF(DATE(Car_launch_date), NOW())) When you specify more than one column in an order by, it orders by the first column, and then by the next if the values in the first column are the same. This orders by - Car Brand, then - Whether the date is in the past. Falses are ordered first. (So future first), then - Absolute difference in dates (smallest number first) Note: I put Car_Brand DESC (reverse alpha order) because that's how you had it above. Thanks to the OP for spotting that you wanted a more complicated order. But I'd argue this way is better : ) A: Using previous post as a supplement, the better answer would be: GROUP BY Car_Brand ORDER BY CASE WHEN Car_launch_date >= NOW() THEN 0 ELSE 1 END, CASE WHEN Car_launch_date >= NOW() THEN DATEDIFF(Car_launch_date, NOW()) ELSE DATEDIFF(NOW(), Car_launch_date) END The query uses conditionnal statements to determine first if it's a future or past date. If it's future, it outputs 0 and past it outputs 1 so the future dates will sort first and past dates sort second. Next another case statement to detect how to compute the difference of days between now and the launch date.
{ "language": "en", "url": "https://stackoverflow.com/questions/7603998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Basic Scala hashmap - return types are ignored I'm trying out Scala, in particular the Hashmap - I've tried something along these lines (both with and without explicitly specifying types): scala> var x = HashMap("a" -> 1, "b" -> 2) x: scala.collection.immutable.HashMap[java.lang.String,Int] = Map(a -> 1, b -> 2) scala> x.get("a") res0: Option[Int] = Some(1) scala> x.get("a") + x.get("b") <console>:10: error: type mismatch; found : Option[Int] required: String x.get("a") + x.get("b") Oddly enough, even though the Int is correctly inferred, I'm unable retain these as Int - so for instance, I cant sum them following the get Am I missing something? A: Notice that .get("a") returns Option[Int]. You can't add Option[Int] even explicitly. I suspect the String part is a red herring due to some implicit option conversion that's in scope. You can add them if you unwrap them from Option: scala> var y = x.get("a").get + x.get("b").get y: Int = 3 A: Take a look at the return type of the get method. It returns Option[Int], not Int: def get (key: A): Option[B] An Option[Int] can either be a Some containing an integer, or a None (which you'd get if the key wasn't present in the map). If you just want an Int, and possibly have a NoSuchElementException thrown if the given key doesn't exist in the map, just use the apply method, or its shorter syntactic sugar: x("a") + x("b") Or, if you want to add the values inside the Option[Int]s, returning another Option[Int]: for (a <- x.get("a"); b <- x.get("b")) yield a + b This will get you a Some if both keys are present, and a None if one or both are missing. Alternatively, if you don't care about missing keys and want to use a default value when a key is missing, use getOrElse: x.getOrElse("a", 0) + x.getOrElse("b", 0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set Size of JComboBox PopupMenu i am programming a custom component which extends a JComboBox. My problem is, the PopupMenu won't actualise its size if i am adding or removing an item. So there are e.g. 2 items in the list, but if there were 4 before i had 2 "empty" items in the PopupMenu as well. The only workaround i found was to do (in JIntelligentComboBox.java line 213) this.setPopupVisible(false); this.setPopupVisible(true); but the result will be a flickering PopupMenu :-( So what else could i do to refresh/repaint the PopupMenu without flickering? For testing: the component and a little test programmTo generate my problem you could e.g.: * *type "e" *press "return" *type "m" Thanks in advance Edit: My goal is a ComboBox that acts like e.g. the adressbar in Firefox or Chrome, i want to show all items of the PopupMenu that contain the typed chars. cboxtester.java: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.plaf.basic.BasicComboBoxRenderer; public class cboxtester extends JFrame { private DefaultComboBoxModel dcm = new DefaultComboBoxModel(new Object[][] {new Object[] {"Mittagessen", "", 0}, new Object[] {"Essen", "", 0}, new Object[] {"Frühstück", "", 0}, new Object[] {"Abendessen", "", 0}}); private JIntelligentComboBox icb = new JIntelligentComboBox(dcm); private cboxtester(){ this.add(icb, BorderLayout.CENTER); this.add(new JButton("bla"), BorderLayout.EAST); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub cboxtester cbt = new cboxtester(); } } JIntelligentComboBox.java: import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.ComboBoxEditor; import javax.swing.ComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultRowSorter; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.MutableComboBoxModel; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.plaf.basic.BasicComboBoxEditor; import javax.swing.plaf.basic.BasicComboBoxRenderer; import javax.swing.plaf.metal.MetalComboBoxEditor; public class JIntelligentComboBox extends JComboBox { private ArrayList<Object> itemBackup = new ArrayList<Object>(); /** Initisiert die JIntelligentComboBox */ private void init(){ class searchComboBoxEditor extends BasicComboBoxEditor { public searchComboBoxEditor(){ super(); } @Override public void setItem(Object anObject){ if (anObject == null) { super.setItem(anObject); } else { Object[] o = (Object[]) anObject; super.setItem(o[0]); } } @Override public Object getItem(){ return new Object[]{super.getItem(), super.getItem(), 0}; } } this.setEditor(new searchComboBoxEditor()); this.setEditable(true); class searchRenderer extends BasicComboBoxRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){ if (index == 0) { setText(""); this.setPreferredSize(new Dimension(1, 1)); return this; } this.setPreferredSize(new Dimension(160, 17)); if (index == list.getModel().getSize() - 1) { this.setBorder(new EmptyBorder(0, 3, 1, 3)); } else { this.setBorder(new EmptyBorder(0, 3, 0, 3)); } Object[] v = (Object[]) value; //System.out.println(v[0]); this.setFont(new Font("Arial", Font.PLAIN, 12)); this.setBackground(Color.white); String s = (String) v[0]; String lowerS = s.toLowerCase(); String sf = (String) v[1]; String lowerSf = sf.toLowerCase(); ArrayList<String> notMatching = new ArrayList<String>(); if (!sf.equals("")){ int fs = -1; int lastFs = 0; while ((fs = lowerS.indexOf((String) lowerSf, (lastFs == 0) ? -1 : lastFs)) > -1) { notMatching.add(s.substring(lastFs, fs)); lastFs = fs + sf.length(); //System.out.println(fs+sf.length()); } notMatching.add(s.substring(lastFs)); //System.out.println(notMatching); } String html = ""; if (notMatching.size() > 1) { html = notMatching.get(0); int start = html.length(); int sfl = sf.length(); for (int i = 1; i < notMatching.size(); i++) { String t = notMatching.get(i); html += "<b style=\"color: black;\">" + s.substring(start, start + sfl) + "</b>" + t; start += sfl + t.length(); } } System.out.println(index + html); this.setText("<html><head></head><body style=\"color: gray;\">" + html + "</body></head>"); return this; } } this.setRenderer(new searchRenderer()); // leeres Element oben einfügen int size = this.getModel().getSize(); Object[] tmp = new Object[this.getModel().getSize()]; for (int i = 0; i < size; i++) { tmp[i] = this.getModel().getElementAt(i); itemBackup.add(tmp[i]); } this.removeAllItems(); this.getModel().addElement(new Object[]{"", "", 0}); for (int i = 0; i < tmp.length; i++) { this.getModel().addElement(tmp[i]); } // keylistener hinzufügen this.getEditor().getEditorComponent().addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub searchAndListEntries(((JTextField)JIntelligentComboBox.this.getEditor().getEditorComponent()).getText()); //System.out.println(((JTextField)JIntelligentComboBox.this.getEditor().getEditorComponent()).getText()); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }); } public JIntelligentComboBox(){ super(); } public JIntelligentComboBox(MutableComboBoxModel aModel){ super(aModel); init(); } public JIntelligentComboBox(Object[] items){ super(items); init(); } public JIntelligentComboBox(Vector<?> items){ super(items); init(); } @Override public MutableComboBoxModel getModel(){ return (MutableComboBoxModel) super.getModel(); } private void searchAndListEntries(Object searchFor){ ArrayList<Object> found = new ArrayList<Object>(); //System.out.println("sf: "+searchFor); for (int i = 0; i < this.itemBackup.size(); i++) { Object tmp = this.itemBackup.get(i); if (tmp == null || searchFor == null) continue; Object[] o = (Object[]) tmp; String s = (String) o[0]; if (s.matches("(?i).*" + searchFor + ".*")){ found.add(new Object[]{((Object[])tmp)[0], searchFor, ((Object[])tmp)[2]}); } } this.removeAllItems(); this.getModel().addElement(new Object[] {searchFor, searchFor, 0}); for (int i = 0; i < found.size(); i++) { this.getModel().addElement(found.get(i)); } this.setPopupVisible(true); } } A: I have revised your sscce below, and I noticed a few things: * *The anomaly you observe is not apparent when using apple.laf.AquaComboBoxUI. In particular, entering and deleting text grows and shrinks the list as expected. You might try the revised code on your platform. *I switched from KeyListener to KeyAdapter for expedience, but that's not a solution. You should probably use a DocumentListener. It can't be mutated while in use, as you are doing now, so I didn't pursue this further. *Always build the GUI on the event dispatch thread. *Hard-coded dimensions and novel fonts rarely look right on other look & feel implementations. I simply removed yours to get the appearance shown. *Your constructor modifies the model after constructing the parent, so the result depends on the order of instantiation. A separate model might be easier to manage. Update: Added code to verify @camickr's solution. import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Window; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JTextField; import javax.swing.MutableComboBoxModel; import javax.swing.SwingUtilities; import javax.swing.plaf.basic.BasicComboBoxEditor; import javax.swing.plaf.basic.BasicComboBoxRenderer; import javax.swing.plaf.basic.BasicComboPopup; public class CBoxTest extends JFrame { private CBoxTest() { DefaultComboBoxModel dcm = new DefaultComboBoxModel(); StringBuilder s = new StringBuilder(); for (char i = 'a'; i < 'm'; i++) { s.append(i); dcm.addElement(new Object[]{s.toString(), "", 0}); } JIntelligentComboBox icb = new JIntelligentComboBox(dcm); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.add(icb, BorderLayout.CENTER); this.add(new JButton("Button"), BorderLayout.EAST); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { CBoxTest cbt = new CBoxTest(); } }); } class JIntelligentComboBox extends JComboBox { private List<Object> itemBackup = new ArrayList<Object>(); public JIntelligentComboBox(MutableComboBoxModel aModel) { super(aModel); init(); } private void init() { this.setRenderer(new searchRenderer()); this.setEditor(new searchComboBoxEditor()); this.setEditable(true); int size = this.getModel().getSize(); Object[] tmp = new Object[this.getModel().getSize()]; for (int i = 0; i < size; i++) { tmp[i] = this.getModel().getElementAt(i); itemBackup.add(tmp[i]); } this.removeAllItems(); this.getModel().addElement(new Object[]{"", "", 0}); for (int i = 0; i < tmp.length; i++) { this.getModel().addElement(tmp[i]); } final JTextField jtf = (JTextField) this.getEditor().getEditorComponent(); jtf.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { searchAndListEntries(jtf.getText()); } }); } @Override public MutableComboBoxModel getModel() { return (MutableComboBoxModel) super.getModel(); } private void searchAndListEntries(Object searchFor) { List<Object> found = new ArrayList<Object>(); for (int i = 0; i < this.itemBackup.size(); i++) { Object tmp = this.itemBackup.get(i); if (tmp == null || searchFor == null) { continue; } Object[] o = (Object[]) tmp; String s = (String) o[0]; if (s.matches("(?i).*" + searchFor + ".*")) { found.add(new Object[]{ ((Object[]) tmp)[0], searchFor, ((Object[]) tmp)[2] }); } } this.removeAllItems(); this.getModel().addElement(new Object[]{searchFor, searchFor, 0}); for (int i = 0; i < found.size(); i++) { this.getModel().addElement(found.get(i)); } this.setPopupVisible(true); // https://stackoverflow.com/questions/7605995 BasicComboPopup popup = (BasicComboPopup) this.getAccessibleContext().getAccessibleChild(0); Window popupWindow = SwingUtilities.windowForComponent(popup); Window comboWindow = SwingUtilities.windowForComponent(this); if (comboWindow.equals(popupWindow)) { Component c = popup.getParent(); Dimension d = c.getPreferredSize(); c.setSize(d); } else { popupWindow.pack(); } } class searchRenderer extends BasicComboBoxRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (index == 0) { setText(""); return this; } Object[] v = (Object[]) value; String s = (String) v[0]; String lowerS = s.toLowerCase(); String sf = (String) v[1]; String lowerSf = sf.toLowerCase(); List<String> notMatching = new ArrayList<String>(); if (!sf.equals("")) { int fs = -1; int lastFs = 0; while ((fs = lowerS.indexOf(lowerSf, (lastFs == 0) ? -1 : lastFs)) > -1) { notMatching.add(s.substring(lastFs, fs)); lastFs = fs + sf.length(); } notMatching.add(s.substring(lastFs)); } String html = ""; if (notMatching.size() > 1) { html = notMatching.get(0); int start = html.length(); int sfl = sf.length(); for (int i = 1; i < notMatching.size(); i++) { String t = notMatching.get(i); html += "<b style=\"color: black;\">" + s.substring(start, start + sfl) + "</b>" + t; start += sfl + t.length(); } } this.setText("<html><head></head><body style=\"color: gray;\">" + html + "</body></head>"); return this; } } class searchComboBoxEditor extends BasicComboBoxEditor { public searchComboBoxEditor() { super(); } @Override public void setItem(Object anObject) { if (anObject == null) { super.setItem(anObject); } else { Object[] o = (Object[]) anObject; super.setItem(o[0]); } } @Override public Object getItem() { return new Object[]{super.getItem(), super.getItem(), 0}; } } } } A: The basis of the solution below is to resize the popup every time you invoke the searchAndListRoutine. You need to take into account that the popup can be displayed in its own Window when the popup displays outside the bounds of the parent frame or it can be displayed on the layered pane of the parent frame: import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Vector; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.plaf.basic.*; import javax.swing.plaf.metal.*; import javax.swing.plaf.basic.*; public class JIntelligentComboBox extends JComboBox { private ArrayList<Object> itemBackup = new ArrayList<Object>(); /** Initisiert die JIntelligentComboBox */ private void init(){ class searchComboBoxEditor extends BasicComboBoxEditor { public searchComboBoxEditor(){ super(); } @Override public void setItem(Object anObject){ if (anObject == null) { super.setItem(anObject); } else { Object[] o = (Object[]) anObject; super.setItem(o[0]); } } @Override public Object getItem(){ return new Object[]{super.getItem(), super.getItem(), 0}; } } this.setEditor(new searchComboBoxEditor()); this.setEditable(true); class searchRenderer extends BasicComboBoxRenderer { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){ if (index == 0) { setText(""); this.setPreferredSize(new Dimension(1, 1)); return this; } this.setPreferredSize(new Dimension(160, 17)); if (index == list.getModel().getSize() - 1) { this.setBorder(new EmptyBorder(0, 3, 1, 3)); } else { this.setBorder(new EmptyBorder(0, 3, 0, 3)); } Object[] v = (Object[]) value; //System.out.println(v[0]); this.setFont(new Font("Arial", Font.PLAIN, 12)); this.setBackground(Color.white); String s = (String) v[0]; String lowerS = s.toLowerCase(); String sf = (String) v[1]; String lowerSf = sf.toLowerCase(); ArrayList<String> notMatching = new ArrayList<String>(); if (!sf.equals("")){ int fs = -1; int lastFs = 0; while ((fs = lowerS.indexOf((String) lowerSf, (lastFs == 0) ? -1 : lastFs)) > -1) { notMatching.add(s.substring(lastFs, fs)); lastFs = fs + sf.length(); //System.out.println(fs+sf.length()); } notMatching.add(s.substring(lastFs)); //System.out.println(notMatching); } String html = ""; if (notMatching.size() > 1) { html = notMatching.get(0); int start = html.length(); int sfl = sf.length(); for (int i = 1; i < notMatching.size(); i++) { String t = notMatching.get(i); html += "<b style=\"color: black;\">" + s.substring(start, start + sfl) + "</b>" + t; start += sfl + t.length(); } } this.setText("<html><head></head><body style=\"color: gray;\">" + html + "</body></head>"); return this; } } this.setRenderer(new searchRenderer()); // int size = this.getModel().getSize(); Object[] tmp = new Object[this.getModel().getSize()]; for (int i = 0; i < size; i++) { tmp[i] = this.getModel().getElementAt(i); itemBackup.add(tmp[i]); } this.removeAllItems(); this.getModel().addElement(new Object[]{"", "", 0}); for (int i = 0; i < tmp.length; i++) { this.getModel().addElement(tmp[i]); } // this.getEditor().getEditorComponent().addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub searchAndListEntries(((JTextField)JIntelligentComboBox.this.getEditor().getEditorComponent()).getText()); //System.out.println(((JTextField)JIntelligentComboBox.this.getEditor().getEditorComponent()).getText()); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }); } public JIntelligentComboBox(){ super(); } public JIntelligentComboBox(MutableComboBoxModel aModel){ super(aModel); init(); } public JIntelligentComboBox(Object[] items){ super(items); init(); } public JIntelligentComboBox(Vector<?> items){ super(items); init(); } @Override public MutableComboBoxModel getModel(){ return (MutableComboBoxModel) super.getModel(); } private void searchAndListEntries(Object searchFor){ ArrayList<Object> found = new ArrayList<Object>(); //System.out.println("sf: "+searchFor); for (int i = 0; i < this.itemBackup.size(); i++) { Object tmp = this.itemBackup.get(i); if (tmp == null || searchFor == null) continue; Object[] o = (Object[]) tmp; String s = (String) o[0]; if (s.matches("(?i).*" + searchFor + ".*")){ found.add(new Object[]{((Object[])tmp)[0], searchFor, ((Object[])tmp)[2]}); } } this.removeAllItems(); this.getModel().addElement(new Object[] {searchFor, searchFor, 0}); for (int i = 0; i < found.size(); i++) { this.getModel().addElement(found.get(i)); } //this.setPopupVisible(true); int size = this.getModel().getSize() - 1; System.out.println("Elements: " + size); if (size == 0) { this.setPopupVisible( false ); return; } this.setPopupVisible(true); BasicComboPopup popup = (BasicComboPopup)this.getAccessibleContext().getAccessibleChild(0); Window popupWindow = SwingUtilities.windowForComponent(popup); Window comboWindow = SwingUtilities.windowForComponent(this); if (comboWindow.equals(popupWindow)) { Component c = popup.getParent(); Dimension d = c.getPreferredSize(); c.setSize(d); } else { popupWindow.pack(); } } } The one issue is that when the combo box field is empty the model contains 4 entries. I would guess that is a problem with your matching logic. A: not tested your code, please advice for content of Renderer here and for AutoComplete JComboBox here A: Faced the same problem using Vector array in ComboboxModel that extends AbstractListModel & implements MutableComboBoxModel. Solved using setMaximumRowCount: * *iterate over database values and save them into public ArrayList listInCombobox = new ArrayList(); *myComboBox.setMaximumRowCount(listInCombobox.size()); *do the above inside myComboBox MouseListener (mousePressed). A: Did you tried this? http://download.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html#updateUI()
{ "language": "en", "url": "https://stackoverflow.com/questions/7604005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mobile and desktop web app with codeigniter I want to build two versions of my project for mobile and desktop. Am working codeigniter 2.0.2, am looking for a way for the mobile and desktop versions of the project to share the same model, controllers, libraries, and helpers. Also i have set up a sub-domain,m.xyz.com to point to folder called "m" on public_html folder, i want the the mobile to be in the "m" folder and share resources with the desktop app residing in root so i dont create duplicate models, controllers etc. A: CodeIgniter allows you to specify the folder that you are loading your views from. Since you want to reuse all of your application code, simply set up CodeIgniter so that it is loading mobile optimized views rather than the default (desktop) views. * *Copy the root index.php file into the /m/ folder that you created. *Update the $system_path and $application_folder variables in /m/index.php with the correct paths. *Update the $view_folder variable in /m/index.php with the path to your view folder containing your mobile optimized views. You mobile site will now mirror your desktop site - it will just be pulling in different views. Note that the structure of your mobile views folder will need to mirror the structure of your default views folder. EDIT: The $view_folder option will not be available until version 2.1. Here is the code if you wish to make the change yourself: https://github.com/EllisLab/CodeIgniter/commit/8eef9c77512d4fad5357d3cbda83b89f844d7d16
{ "language": "en", "url": "https://stackoverflow.com/questions/7604008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I get frequency data from PCM using FFT I have an array of audio data I am passing to a reader: recorder.read(audioData,0,bufferSize); The instantiation is as follows: AudioRecord recorder; short[] audioData; int bufferSize; int samplerate = 8000; //get the buffer size to use with this audio record bufferSize = AudioRecord.getMinBufferSize(samplerate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT)*3; //instantiate the AudioRecorder recorder = new AudioRecord(AudioSource.MIC,samplerate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,bufferSize); recording = true; //variable to use start or stop recording audioData = new short [bufferSize]; //short array that pcm data is put into. I have a FFT class I have found online and a complex class to go with it. I have tried for two days looking online everywhere but cant work out how to loop through the values stored in audioData and pass it to the FFT. This is the FFT class I am using: http://www.cs.princeton.edu/introcs/97data/FFT.java and this is the complex class to go with it: http://introcs.cs.princeton.edu/java/97data/Complex.java.html A: Assuming the audioData array contains the raw audio data, you need to create a Complex[] object from the audioData array as such: Complex[] complexData = new Complex[audioData.length]; for (int i = 0; i < complexData.length; i++) { complextData[i] = new Complex(audioData[i], 0); } Now you can pass your complexData object as a parameter to your FFT function: Complex[] fftResult = FFT.fft(complexData); A: Some of the details will depend on the purpose of your FFT. The length of the FFT required depends on the frequency resolution and time accuracy (which are inversely related), that you wish in your analysis, which may or may not be anywhere near the length of an audio input buffer. Given those differences in length, you may have to combine multiple buffers, segment a single buffer, or some combination of the two, to get the FFT window length that meets your analysis requirements. A: PCM is the technique of encoding data. It's not relevant to getting frequency analysis of audio data using FFT. If you use Java to decode PCM encoded data you will get raw audio data which can then be passed to your FFT library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using a global_work_offset in clEnqueueNDRangeKernel I have a global work size of 1000 but i want only to execute the kernel from 200 to 1000. size_t global_work_size = 1000; size_t global_work_offset = 200; clEnqueueNDRangeKernel(cpu_queue, kernel [0], 1, &global_work_offset, &global_work_size, NULL, 0, NULL, NULL); The problem is it does compute the whole 0-1000 range even if I specify an offset. I tried using: size_t global_work_offset [1] = {200}; but still no luck. A: You should notice the difference between that parameter in CL 1.0 and 1.1: CL 1.0: global_work_offset Must currently be a NULL value. In a future revision of OpenCL, global_work_offset can be used to specify an array of work_dim unsigned values that describe the offset used to calculate the global ID of a work-item instead of having the global IDs always start at offset (0, 0,... 0). CL 1.1: global_work_offset global_work_offset can be used to specify an array of work_dim unsigned values that describe the offset used to calculate the global ID of a work-item. If global_work_offset is NULL, the global IDs start at offset (0, 0, ... 0). So, check that you have a CL 1.1 device and drivers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delayed fade on hide of a jquery dialog box Clicking a button on my site opens a modal dialog box (that shows the word "Saving") and starts an Ajax command. When the command is finished, I want to change the text in the dialog box (to "Saved!"), wait 500 milliseconds, and have the dialog box fade out. Opening and modifying the contents of the dialog box are no problem. I'm having trouble though with fading the dialog box after a delay. Here's the code for the dialog box: $("#save_filters_dialog").dialog({ autoOpen:false, draggable:false, resizable:false, modal:true, height:54, width:70, hide:"fade", create: function(event,ui){ $(this).siblings(".ui-dialog-titlebar").hide(); } }); I also created this code to test closing the dialog (without using an Ajax command): $("#save_filters_dialog").click(function(){ $(this).dialog("close"); }); The fade out and closing works fine. I just can't seem to find where to put the .delay(500) that delays the fade out on close. A: this is how I close my dialog message: $("#save_filters_dialog").dialog( { autoOpen:false, draggable:false, resizable:false, modal:true, height:54, width:70, hide: {effect: "fadeOut", duration: 1000} }, setTimeout(function(){$("#save_filters_dialog").dialog("close");},2000)); A: You could use the setTimeout() function for that. $("#save_filters_dialog").click(function(){ setTimeout('closeDialog('+this+')',500); }); function closeDialog(object){ $(object).dialog("close"); } A: Use setTimeout and an anonymous function to wrap what you want to do after it: setTimeout(function(){ console.log('Executed after 500ms'); }, 500);
{ "language": "en", "url": "https://stackoverflow.com/questions/7604013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to access the dynamically created HTML control from code behind in asp.net i have a webpage, wherein i am using a simple foreach loop and creating table structure, wherein i am displaying an image in td, the requirement is i want to access the image created in td, from code-behind on page load. but i am unable to find the control, i have made the control as runat='server' and also setted the id. foreach (DataRow r in dtLogic.TopStories(Convert.ToInt32(ConfigurationManager.AppSettings["TopArticles"]), Convert.ToInt32(ConfigurationManager.AppSettings["PortalId"])).Rows) { i++; str.Append("<table cellpadding='0' cellspacing='0' class='newsItem'>"); str.Append("<tr>"); str.Append("<td><img runat='server' id='img"+i+"' class='thumb' src='" + GetAppSettingValue("MainSiteUrl") + "" + r["image"].ToString() + "' width='128' height='73'></td>"); str.Append("<td><p class='newsTitle'><a href='" + r["URL"].ToString() + "'>" + r["title"].ToString() + "</a></p></td>"); str.Append("<td><img class='arrow' src='/images/arrow.png'></td>"); str.Append("</tr>"); str.Append("</table>"); } now when i access this image from code behind like below.. HtmlImage img = (HtmlImage)this.FindControl("img1"); i gets the NullReference for the img object.. can anyone tell me why its not getting the image, which is runat='server' and rendering on the page.. A: You can't access it as it won't exist on postback. An image control isn't posted back to the server. If you have to bind events to it (for when its clicked on) you generally want to create the control in page_init and rebind its events to get the dynamic control to work. A: Adam Tuliper is spot on. Either store the value in a hidden textbox which gets posted back. or A way to do this is create using web server controls. (This is much harder work) Image img = new image().... HtmlTable tabl = new HtmlTable() HtmlTr ... HtmlTd ... td.Controls.Add(img); THen with dynamic controls, they must be created before viewstete is restored, so recreate these controls in overriden OnLoad event. (BTW, you cant just add runat='server' as a string to anything. Check for yourself. View source on your webpage and you will see runat='server' in the source. Any other server control will not have the attribute in the view source).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VsFTPd/LDAP - automatically create a directory for a new user I am trying to setup a FTP server. I am using VsFTPd on an Ubuntu server that will authenticate against an LDAP server. My users should have access to their personal directory (read/write), to their public directory (read/write), to the public directory of other users (read) and to a general public directory (read). Admin users have read/write access on all directories. My problem is the following: when a user is created on the LDAP server, he should be able to connect to the FTP server. But his directories will not be created on the FTP server. Another part of the problem is the modification of the status of an user: if an user becomes admin, how do I change his configuration to give him access to all the directories? One solution would be to execute a script when an user tries to connect to the FTP server. This script would check if the directories are created and if not, create them. But how can I configure VsFTPd to execute a script when an user logs in? Thank you for your help. A: You should use the pam module pam_mkhomedir. Use it globally for all the system or only for VsFTP if your installation was compiled against libpam.so. Check this using ldd in the vsftpd binary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: broadcast receivers Issues In my app I listen for bootup receiver and once I receive it, I do some stuff The problem I see is even when my broadcast receiver is done, app stays in the running processes. This happens every time when the phone is started and I have customer complaining why my app stays in background even when they have not started it. What is the best way to make sure my app does not keep running in background once I am done with rec A: Do whatever needs to be done after bootup in a service and call stopSelf() once it is done. But even when your app is listed in the running processes tab doesn't mean that its hurting anyone. The resources used by it will be made available by the managed runtime when needed either way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upload a PPT file and see it like a presentation The upload part is OK! My problem is open that PPT file and show like a presentation. I have no idea how can I do that. My server side language is PHP. Thanks A: * *Your client needs to have MS-Powerpoint, or at least MS Powerpoint Viewer, installed *Your browser needs to be capable of ActiveX *Ideally, you can also configure your server to send the file as MIME-type: "application/vnd.ms-powerpoint":
{ "language": "en", "url": "https://stackoverflow.com/questions/7604025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can an interface include a method that references the concrete implementation type of the interface in its signature or return type? Suppose I am designing something like the following interface: public interface MyInterface{ public MyInterface method1(); public void method2(MyInterface mi); } However, there is the caveat that the return type for method1 and the parameter for method2 match the concrete implementation and not just MyInterface. That is, if I have MyInterfaceImpl that implements MyInterface, it needs to have the following: public class MyInterfaceImpl implements MyInterface{ @Override public MyInterfaceImpl method1(){...} @Override public void method2(MyInterfaceImpl mi){...} } As written above, method1 won't cause any compile errors, but there is nothing guaranteeing that the return type matches in all implementations. Of course method2 won't even compile because the signature does not match the interface. One candidate solution is to use self-referential or recursive bounds in generics: public interface MyInterface<T extends MyInterface<T>>{ public T method1(); public void method2(T mi); } public class MyInterfaceImpl implements MyInterface<MyInterfaceImpl>{ @Override public MyInterfaceImpl method1(); @Override public void method2(MyInterfaceImpl mi); } This would get me what I want with one exception: other implementations might pass the wrong generic type (nothing forces T to match the concrete type). So potentially someone else could implement the following: public class NotMyInterfaceImpl implements MyInterface<MyInterfaceImpl>{ @Override public MyInterfaceImpl method1(); @Override public void method2(MyInterfaceImpl mi); } That would compile just fine even though NotMyInterfaceImpl should implement MyInterface<NotMyInterfaceImpl>.* That makes me think I need something else. *Note that I don't think I'm trying to violate LSP; I'm OK with the return type/parameter being subclasses of NotMyInterfaceImpl. So I don't know of a clean way to do this. That leads me to believe that I might be focusing too much on implementation details in the interface, but it doesn't seem that way to me. Is there any way to do the type of thing I described, or is this some kind of smell that I'm putting something in an interface that doesn't belong there? A: I believe that this cannot be done. There is simply no way to refer to an object's implementation class in the framework of generics, nor, as far as i know, any way to construct a cage out of pure generics which is capable of constraining the implementation class to match a type parameter. The most useful thing i can suggest is using a self-referential parameter, and then always acquiring instances of implementations from factory methods which look like: public <T extends MyInterface<T>> T newInstance(); It is easier for a camel to pass through the eye of a needle than for an instance of NotMyInterfaceImpl to pass through that return type. So, although troublemakers could write classes which do not conform to your masterplan, they couldn't return them from factories. Unless NotMyInterfaceImpl extended MyInterfaceImpl; but then, in a sense, it would also be a MyInterfaceImpl, so perhaps that would be kosher? EDIT: A slightly more useful version of that idea is to always pass instances of implementations of the interface around in a suitably restrictive holder, like: class Holder<T extends MyInterface<T>> { public final T value; } If someone gives you a Holder<Q>, then you know that Q must be a version of MyInterface bound to itself, which is what you're after. A: This is the exact situation faced by the Comparable interface (its compareTo method wants to take an argument the same type as the object it is called on). So what does it do? It's simply defined as Comparable<T>. The idea is that an implementing class "should" implement Comparable with itself as the parameter (allowing it to "compare to" itself); but this is not enforced (since there is no way to do it). Yes, as you noted, this will allow any class to implement Comparable with a parameter of any other class: class Foo implements Comparable<Bar> where Foo and Bar have no relation to each other. However, this is not really a problem. All the methods and classes (sorting, maximum, etc.) that require Comparable objects have the following generic type constraint <T extends Comparable<? super T>>. This ensures that objects of type T are comparable with themselves. That way, it is completely type-safe. So the enforcement is not made in the declaration of the Comparable interface, but in the places that use it. (I notice that you use <T extends MyInterface<T>> while Comparable uses simply <T>. Although <T extends MyInterface<T>> will exclude cases where the type parameter does not implement MyInterface, it will not exclude cases where the type parameter does implement MyInterface, but is different than the class. So what's the point of half-excluding some cases? If you adopt Comparable's way of restricting it where they are used, it's type-safe anyway, so there is no point in adding more restrictions.) A: What you are trying to do is not legal because you are trying to narrow the parameter of the implemented type, and this "does not make sense". You are tryint to use "covariant" parameters, and only covariant return types are allowed (and even logic, and only supported from Java 5). I mean, if it was possible to use covariant parameter types, you could do things like: MyInterface instance = new MyInterfaceImpl(); And then, invoke on "instance" the method with another implementation supported by the interface but not supported by the MyInterfaceImpl class this way: instance.method2(new MyInterfaceImpl_2()); Java cannot convert MyInterfaceImpl_2 to MyInterfaceImpl, so it prevents you from doing so at compilation time. What you could do is to widen the parameter, using "contravariant" parameter, which would be logic. For more detail on this, check this anser: Demonstrate covariance and contravariance in Java? The only workaround that I can think of, is to solve the problem at runtime, I mean, doing something like this: public class MyInterfaceImpl implements MyInterface{ @Override public void method2(MyInterface mi){ realMethod((MyInterfaceImpl) mi); } public void realMethod(MyInterfaceImpl) {...} } But you could get ClassCast exception, of course. A: The point of returning the interface is such that the method does not care the actual implementation of the returned object. In your case you actually want to mandate the type to be a particular sub-implementation of that interface. To apply the constraints that you described above, IMHO the design should probably be a base class instead of an interface. This allows you to control the implementation, for example a top-level flow, and leave low-level strategy to sub-classes to implement: class MyBaseImpl { public final void fixedFlow() { MyBaseImpl obj = method1(); obj.method2(this); } protected abstract MyBaseImpl method1(); .... } There has to be other methods to make it interesting...; perhaps you have good reasons to want to do this... Hope this helps! A: Is this what you are looking for? public interface MyInterface { static abstract class MyInterfaceImpl implements MyInterface { @Override public abstract MyInterfaceImpl method1(); @Override public abstract void method2(MyInterfaceImpl mi); } MyInterfaceImpl method1(); void method2(MyInterfaceImpl mi); } And you could even implement method 1 or 2 instead of making them abstract.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Save Data Between Screens I have an iPhone app with a form that has terms and conditions. When the user taps on the terms and conditions link, it brings them to another screen within the application that shows them. Now, when they tap away and come back they lose all of the information they placed into the fields. Is there any way of saving this data in the forms short of storing everything in a dictionary when they leave and when the view reloads filling it back? A: Can you use a UIAlertView for the terms and conditions? I've used this in a few apps. Longer text automatically creates a scroll in the alert. This will keep you from needing to leave the screen at all. A: You will need to have some way of saving that data when the user leaves the screen using a dictionary or some other means. So the short answer is no. A longer answer is that you could change how you are navigating to the new screens and prevent this screen from getting dumped when you move on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facade Pattern, is this ok? I have two servers that I will be connecting to from one client. For each server, I will be doing an ftp "put" and a "rm". Should I build one facade, and have an interface like this: void putFileOnServer1(String file) void putFileOnServer2(String file) void removeFromServer1(String file) void removeFromServer2(String file) And, should the facade handle all the establishing of the connections and disconnecting? If so, should it use a factory to do so? A: You have two methods, PutFileOnServer and RemoveFromServer. Which server you are putting or removing from should be part of the abstraction. A: Do the ftp servers have different interfaces? Or do they all understand the same set of commands you want to utilize already? * *If so, then simply create one FtpServer class that accepts connection info. And create a FtpClient class that accepts multiple servers, that you can select by some key for instance. (At least this, to some extent, would probably be something I would do). class FtpClient { public function addServer( FtpServer $server, $key ); public function selectServer( $key ); public function putFileOnServer( $file ); public function removeFileFromServer( $file ); } *If not, and you have a class for each individual implementation already, that differ by their interfaces, for instance like: class FtpServerFoo { public function selectFile( $file ); public function removeSelectedFile(); } class FtpServerBar { public function removeFile( $file ); } ... you should look into the Adapter Pattern: abstract class FtpServer { abstract public function putFile( $file ); abstract public function removeFile( $file ); } class FtpServerAdapterFoo extends FtpServer { public function __construct( FtpServerFoo $server ) { } public function removeFile( $file ) { $this->server->selectFile( $file ); $this->server->removeSelectedFile(); } } class FtpServerAdapterBar extends FtpServer { public function __construct( FtpServerBar $server ) { } public function removeFile( $file ) { $this->server->removeFile( $file ); } } $cilent = new FtpClient(); $client->addServer( new FtpServerAdapterFoo( new FtpServerFoo() ), 0 ); $client->addServer( new FtpServerAdapterBar( new FtpServerBar() ), 1 ); $client->selectServer( 0 ); $client->putFileOnServer( $file ); $client->selectServer( 1 ); $client->removeFileFromServer( $someOtherfile ); *If you don't have individual classes for differing FTP servers yet, then you can just implement the same interface (or inherit an abstract class) for each ftp server implementation and use the same type of FtpClient class as the one above again. Not really a facade pattern involved here though. A: You typically use facades to decrease complexity among multiple object types. In this case, though, it appears you want to use only one functional "type", a "FTPServer". For the most part, then, you should just have two instances of this type, and this type will have a "put" and "remove" method. When you add needless function points, you actually increase the complexity of maintenance. For instance, if you need to add a new parameter to your functions (maybe access restrictions or whatever), you not only have to change for each place of use, but now have to add in each facade method. Abstraction should reduce this type of coupling, not increase it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sanitize input with PHP and the sqlsrv driver? I'm working on a PHP MSSQL project that is using the sqlsrv driver. What's the best way to stop SQL injection attacks? I need something like mysql_real_escape_string() but for sqlsrv driver. A: If you use it like this, quoting is automatic: $sql = "exec usp_cis_upd @key = ?, @value = ?"; $params = array( $key, trim($_POST["value"])); $stmt = sqlsrv_query($dbh, $sql, $params); A: The best way is not to write your SQL so that you need to use an analogue of mysql_real_escape_string(), which you would do by using placeholders for the values and then passing the variables (that would otherwise have been handled by mysql_real_escape_string()) when you execute the statement or open the cursor or whatever. Failing that, look at the output of mysql_real_escape_string(); it might be appropriate for MS SQL Server too. It depends on how it does the escaping (and what escaping it does).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to populate textbox value real time upon date start and end entry on a razor view? Q: How can I populate a text box value (number of days) realtime based on a user entering start and stop dates within an mvc3/razor view? Thx! A: Either you would onblur, postback with Ajax and use server logic to fill the textbox value with number of days. Or, ideally, you would use jquery to do this so it is most responsive and realtime. A: $("#textbox1, #textbox2").change(function() { $.ajax( {url: '/controller/action', data: { date1: $("#textbox1").val(),date2: ("#textbox1").val()}, success: function(data){ $("#days_textbox").val(data); }}) });
{ "language": "en", "url": "https://stackoverflow.com/questions/7604038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Checking if a SoundCloud song is embeddable I'm trying to use the SoundCloud API to check if a song is embeddable, is this the same as streamable? My code looks like this: $trackid = $track['id']; $username = mysql_real_escape_string($track['user']['username']); $title = mysql_real_escape_string($track['title']); $downloadable = $track['downloadable']; $streamable = $track['streamable']; // Check if streamable if(!$streamable) { header( 'Location: error.php' ); } else { ... I can get the trackid, username, title & downloadable easily, but is streamable the correct property to look for? I'm talking about when you go to embed a song and it says "Oops this track can't be played outside of SoundCloud." I want to make sure this doesn't happen and unallow a song if it's one of those songs. A: Referring to the documentation the streamable proprety exists. And yes it's the right one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quoting a Python function in order to apply it later Given an object Foo, which has a set of methods Bar, Baz, Quux, and Close. I want to wrap calls into Foo as follows def wrapper(method_symbol, *args): object = Foo() apply(object.method_symbol, args) object.Close() So later on, I can call wrapper(Bar, MySweetArgs) and have wrapper correctly dispatch. Obviously in Lisp this would be simple, simply QUOTE method_symbol and away you go. The goal is to properly allocate/deallocate resources in a text-efficient fashion. I would prefer not wrap all of Foo with a SafeFoo class. A: If you want to call the method by its name, the wrapper function could look like this: def wrapper(method_symbol, *args): obj = Foo() getattr(obj, method_symbol)(*args) obj.Close() wrapper('Bar', 1, 2, 3) You could also use the method directly, instead of its name: def wrapper(method, *args): obj = Foo() method(obj, *args) obj.Close() wrapper(Foo.Bar, 1, 2, 3) A: If method_symbol is the string name then: Foo.__dict__[method_symbol](*args) would probably do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: no such file to load -- sqlite3/sqlite3_native I am having trouble trying to run the following ruby script on OSX (Leopard). require 'sqlite3' database = SQLite3::Database.new( "new.database" ) database.execute( "create table sample_table (id INTEGER PRIMARY KEY, sample_text TEXT, sample_number NUMERIC);" ) database.execute( "insert into sample_table (sample_text,sample_number) values ('Sample Text1', 123)") database.execute( "insert into sample_table (sample_text,sample_number) values ('Sample Text2', 456)") rows = database.execute( "select * from sample_table" ) p rows but I get the following error: /Users/Ted/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- sqlite3/sqlite3_native (LoadError) from /Users/Ted/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require' from /Users/Ted/.rvm/gems/ruby-1.9.2-p180/gems/sqlite3-1.3.4/lib/sqlite3.rb:6:in `rescue in <top (required)>' from /Users/Ted/.rvm/gems/ruby-1.9.2-p180/gems/sqlite3-1.3.4/lib/sqlite3.rb:2:in `<top (required)>' from <internal:lib/rubygems/custom_require>:33:in `require' from <internal:lib/rubygems/custom_require>:33:in `rescue in require' from <internal:lib/rubygems/custom_require>:29:in `require' from sequelsample.rb:1:in `<main>' How can I fix this issue? I have installed the following gems with the commands using ruby 1.9.2p180 (2011-02-18 revision 30909) [i386-darwin9.8.0]: sudo gem install sqlite3-ruby -- --with-sqlite3-dir=/sw sudo gem install sqlite3 -- --with-sqlite3-dir=/sw sqlite3 (1.3.4) sqlite3-ruby (1.3.3) A: Fixed it with this commands: gem uninstall sqlite3 gem uninstall sqlite3-ruby sudo gem install sqlite3 -- --with-sqlite3-dir=/sw Ted
{ "language": "en", "url": "https://stackoverflow.com/questions/7604049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Specifying directory with Japanese characters in build.xml for ant in windows I have a build.xml file that specify a directory with Japanese characters as an argument to a command. <exec executable="${amxmlc_cmd}"> <arg line="${amxmlc_opt}" /> ... <arg line="-source-path+=Work/システム/_config_as" /> ... </exec> Where <condition property="amxmlc_cmd" value="cmd.exe"> <os family="windows" /> </condition> <condition property="amxmlc_opt" value='/c "${flex_sdk}bin/amxmlc"'> <os family="windows" /> </condition> I get the error "Error: unable to open 'Work/????/_config_as" I changed to <condition property="amxmlc_opt" value='/u/c "${flex_sdk}bin/amxmlc"'> <os family="windows" /> </condition> But I get the same error. When I changed the windows non-unicode program default to Japanese I got the error "Error: unable to open 'Work/システム/_config_as'" Any help is greatly appreciated. Thanks for advance. A: That is ant, who is not passing properly the Unicode parameters. It will only work if you set the system locale to Japanese and reboot. http://mihai-nita.net/2005/06/11/setting-the-user-and-system-locales/ === Correction: did some testing, and it is not ant's fault, it is Java itself. I have tried both Runtime.exec and ProcessBuilder.start, and both of them seem to convert the parameters to ANSI before passing it to the child application. (the child app was C, Unicode, and called from a C parent, Unicode, worked fine) Pretty lame, for 2011 (Java build 1.6.0_26-b03, it would be interesting to try in 7)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get text from the title attribute when is clicked? If I have the following HTML: <th title="Title Description">Blah</th> How do I select text from the title attribute when I click on <th>? A: $(function() { $('th').click(function() { var title = $(this).attr('title'); }); }); A: $(function () { $('th').click(function () { var title = $(this).attr('title'); // do something useful with title }); }); A: Try this $(document).ready(function() { $('th').click(function() { var title = $(this).attr('title'); alert(title); }); }); A: $('th').click(function(){alert($(this).attr('title'));}); A: $('tr').click(function() { var title = $(this).children('th').attr('title'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7604051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connect to Mongo DB on a remote server behind LDAP using perl So I intend to connect to mongoDB which is on a remote server behind LDAP. The mongoDB by itself has no username/password setup, but the server on which mongoDB is running is behind LDAP. My question is how do I setup the server tunneling username/password configuration to connect to MongoDB I am using the mongoDB module from cpan. lets assume - LDAP credentials are username - ldapuser password - ldappassword I do know how to setup if the mongoDB has a username and password my $connection = MongoDB::Connection->new(host => 'mongodb://perlnewbi3.remoteserver.com:27107', username => 'dbuser', password => 'dbpass', db_name => 'testdb'); my $database = $connection->testdb; As always any help will be much appreciated A: This whole thing is really a question of permissions rather than a question of how to use MongoDB. There are two basic methods: * *Ensure that the Perl app in running in the correct user context so that it can see port 27017 on remoteserver.com. *Create a secured tunnel on the local machine, typically with something like SSH. Then update your connection in PERL to point to the correct port on the local machine. (mongodb://localhost:27017) Option #1 is probably the ideal solution, however, Option #2 is probably simplest option to setup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot bypass validation error 'You need to supply at least one attribute' in ActiveRecord? I've been following the Michael Hartl Tutorial, but took a shortcut to try and 'improve' on its example, and have create a tough bug... Basically, this app revolves around a User model coupled with a sign-up feature using a lot of validations around an encrypted password feature; kind of non-trivial for a rails newbie. Instead of strictly following Hartl's example, I modified the approach to use a scaffold to set up my Users. But somewhere towards the end of his project I started getting this error when attempting to create a User: ArgumentError in UsersController#new You need to supply at least one attribute. This is baffling to me, since I've attempted to turn off all validation except with saving. Below are some code fragments: my users_controller.rb#new: class UsersController < ApplicationController # GET /users # GET /users.xml def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end ..... def new @title = "Sign up" @user = User.new #(unnecessary?) respond_to do |format| format.html # new.html.erb format.xml { render :xml => @user } end end from my user.rb: class User < ActiveRecord::Base attr_accessor :password attr_accessor :username, :firstname, :lastname, :email, :password, :password_confirmation email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i # here I am attempting to only validate when saving validates :allow_nil => true, :presence => true, :on => :save validates :firstname, :presence => true, :length => { :maximum => 50 } validates :lastname, :presence => true, :length => { :maximum => 50 } validates :username, :presence => true, :length => { :maximum => 20 } validates :email, :presence => false, :format => { :with => email_regex }, :uniqueness => { :case_sensitive => false } # Automatically create the virtual attribute 'password_confirmation'. validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 } before_save :encrypt_password # Return true if the user's password matches the submitted password. def has_password?(submitted_password) encrypted_password == encrypt(submitted_password) end def self.authenticate(email, submitted_password) user = find_by_email(email) return nil if user.nil? return user if user.has_password?(submitted_password) end def self.authenticate_with_salt(id, cookie_salt) user = find_by_id(id) (user && user.salt == cookie_salt) ? user : nil end def initialize(attributes = {}) @username = attributes[:username] @firstname = attributes[:firstname] @lastname = attributes[:lastname] @email = attributes[:email] end def formatted_email "#{@firstname} #{@lastname}<#{@email}>" end private def encrypt_password self.salt = make_salt unless has_password?(password) self.encrypted_password = encrypt(password) end def encrypt(string) secure_hash("#{salt}--#{string}") end def make_salt secure_hash("#{Time.now.utc}--#{password}") end def secure_hash(string) Digest::SHA2.hexdigest(string) end end Any suggestions much appreciated! --rick PS -- per request. here is the create method: def create @user = User.new(params[:user]) respond_to do |format| if @user.save format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user } else format.html { render :action => "new" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end I was able to get the error message to go away by commenting out all validations in my model, but I will be adding them back one by one; so I still need to solve this bug.... A: This line in your User model: validates :allow_nil => true, :presence => true, :on => :save did not supply an attribute for validation. You may have meant to include those options on every validation listed below, but it's not how validates works. A: I concur with jimworm. Validation doesn't run on new. It only runs before you attempt to save or call valid?. You need to just remove the line jimworm outlines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to modify external process using Python Beginner here. I am trying to figure out how to modify a running process on a linux system using Python. Example: I have a python program that takes in as an argument a PID. My goal is to use this PID and get info about the running process with that PID. (1) Find where it is located in memory (2) Where is the instruction pointer (3) Modify the program such that the next executed instruction is something else (4) Return the pointer back to the next legitimate instruction (5) Let the original process execute as it should have I am trying to develop a POC to show how a small piece of code can be injected into a running process to just print 'hello' to stdout and not disturb the rest of the process. I looked up trace and some other modules but they all seem to do with following the currently executing python process. Also looked at pyhook, but its mainly to trap signals from keyboards etc.. additionally, I looked up pygdb a bit. Can anyone please point me to some modules that might be useful, or some code samples. I tried googling for "python inspect process PID" etc.. did not get anything very useful. Any help is very appreciated. Thanks! A: Also a newer python user. Can you do all these things with just the command line? If so then you could use os.system('[command]') or the subprocess module. For example you could use the pmap command to get the memory mappings. As for 2-5 I have no experience there. Good Luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi-Coloured bars in matplotlib I have a graph in matplotlib (that displays correctly), but I was hoping to have a different colour for each bar (still the same bar graph though). Is this possible? Thanks A: If you color at graph creation time: In [15]: x= range(5) In [16]: y = [10, 23, 12, 45, 32] In [17]: color = ['r', 'b', 'y', 'g', 'c'] In [18]: lines = bar(x, y, color=color) If you want to change color of first bar after graph creation, then note that you got a list of your bars in lines: In [19]: lines Out[19]: [<matplotlib.patches.Rectangle object at 0x02 <matplotlib.patches.Rectangle object at 0x02 <matplotlib.patches.Rectangle object at 0x02 <matplotlib.patches.Rectangle object at 0x02 <matplotlib.patches.Rectangle object at 0x02 Then, just simply set its color: In [20]: lines[0].set_color('c') #changes from original red to cyan
{ "language": "en", "url": "https://stackoverflow.com/questions/7604071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Itextsharp seems to be corrupting a pdf form after filling it out; problems opening in Adobe Reader for WP7 I'm trying to dynamically generate a pdf form from an asp.net C# application. The form is generated and emailed to some users. People have been able to open it on Adobe Reader for months now. Recently, there has been a request that users be able to read these pdf attachments on their mobile phones. Unfortunately, when these people try to open the pdfs on their phones, it says "There was an error opening the document." I tried opening the original form on my wp7 phone and it works. I sent a copy of one of the pdfs that is not working to the a free pdf/a validator service. The service came back with the following message: Failed to load file: incorrect 'startxref' reference This makes me think that the issue is that Adobe Reader is rebuilding some of the metadata/indices in the document when it opens. Because most people have fast machines, the time spent rebuilding these indices is negligible. But from what I understand the phone version does not have this capability, so it is reading the xstartref and failing. Here is the code in my application that appears to be producing the corrupt file: File.Copy(original, newpath); FileStream fs = new FileStream(newpath, FileMode.Open); PdfReader r = new PdfReader(fs); PdfStamper stamper = new PdfStamper(r, fs); AcroFields af = stamper.AcroFields; af.SetField("Event", ef.eName); af.SetField("EventType", ef.EventType); af.SetField("eStartDate", ef.eStartDate); af.SetField("eStartTime",ef.eStartTime); stamper.FormFlattening = true; stamper.FreeTextFlattening = true; stamper.Close(); r.Close(); fs.Close(); What am I doing wrong? I've read where not closing the stream, stamper and pdfreader properly can create trouble. But I think I am closing it properly. What am I overlooking? A: You should be binding the PdfReader to your source document and your PdfStamper to your destination document. //Get rid of the below line completely //File.Copy(original, newpath); FileStream fs = new FileStream(newpath, FileMode.Open); PdfReader r = new PdfReader(original); PdfStamper stamper = new PdfStamper(r, fs); Otherwise you're reading from a document while you write to it which isn't a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TouchesMoved With 2 Fingers I am trying to make a simple landscape "split screen" app where two players can play at once (each player gets one half of the screen), but I am having trouble tracking both touches at the same time. This is the code I am trying to use: - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { CGPoint point = [touch locationInView:self.view]; if (point.x < 240) { [player1 updatePoint:point]; } else { [player2 updatePoint:point]; } } } But I am obviously doing something wrong. Although this code works fine, it will only track one finger and move the player on the side of the screen the finger is on. What is my code lacking? Is this task more difficult to pull off then I think it is? A: Did you set UIView's multipleTouchEnabled to YES? A: multipleTouchEnabled should be set to YES for the UIView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mysql: exact match? I'm pulling some data from mysql and counting occurrences of matches (seemingly equivalent to WHERE foo='bar'). However, as I loop thru the data in PHP, my count is much lower than the count in mysql. MYSQL> SELECT COUNT(foo) FROM database.table WHERE foo='bar'; # PHP while ($response = mysql_fetch_assoc($surveydata)){ if ($response==='bar') { $bar++; } } The data might contain one or more &, so I want to match only bar and not bar & foobar. I suspect mysql is counting bar and bar & foobar whereas php is only counting bar and not bar & foobar. Php is returning 1210, and mysql is returning 1783, so it's exactly practical to manually count to see who is right… I googled around, but was surprised nothing relevant came up for "mysql exact match" or "mysql exactly equal" x,x EDIT here's the actual sql SELECT COUNT(`race`) FROM `database`.`table` WHERE `completion status`='complete'; and the actual php mysql_query("SELECT `race`,`etcetera` FROM `database`.`table` WHERE `completion status`='complete';"); $demographics=array( "race"=>array( "White"=>array('consented'=>0,'partial'=>0,'completed'=>0), "Black"=>array('consented'=>0,'partial'=>0,'completed'=>0), "Hispanic"=>array('consented'=>0,'partial'=>0,'completed'=>0), "Asian"=>array('consented'=>0,'partial'=>0,'completed'=>0), "Pacific Islander"=>array('consented'=>0,'partial'=>0,'completed'=>0), "Multiracial"=>array('consented'=>0,'partial'=>0,'completed'=>0), "Other"=>array('consented'=>0,'partial'=>0,'completed'=>0) ) //more ); while ($dbrecord = mysql_fetch_assoc($surveydata)) { foreach ( $dbrecord as $dbfield=>$dbcellval ) { foreach ( $demographics as $demographic=>&$options ) { foreach ( $options as $option=>&$counter ) { if ( $option==="Multiracial" && strpos($dbcellval,'&') >0 && strpos($dbcellval,'&')!==false ) { if ($dbrecord['consent']==="1"){ $demographics["race"]["Multiracial"]['consented']++; if ($dbrecord['completion status']==="partial") { $demographics["race"]["Multiracial"]['partial']++; } // if else if ($dbrecord['completion status']==="complete") { $demographics["race"]["Multiracial"]['completed']++; } // else if } // if } else if ($option===$dbcellval){ if ($dbrecord['consent']==="1"){ $counter['consented']++; if ($dbrecord['completion status']==="partial") { $counter['partial']++; } // if else if ($dbrecord['completion status']==="complete") { $counter['completed']++; } // else if } // if } // else if $option==$item } // foreach $options } // foreach $demographics } // foreach $dbrecord } // while the data from SELECT race FROM database.table looks like: White & Black White White & Asian White & Asian & Black Asian Asian & Black // etc A: You can do this: MYSQL> SELECT COUNT(foo) FROM database.table WHERE BINARY foo='bar'; BINARY does the magic!!! A: If you want to count the records where foo is exactly bar, your SQL query is correct. There's something wrong with your PHP code and the code you posted shouldn't work at all (should count 0 records). A: MYSQL> SELECT COUNT(foo) AS rows FROM database.table WHERE foo='bar'; $response = mysql_fetch_assoc($surveydata); echo $response['rows'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7604082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing WordPress's TinyMCE iFrame Using jQuery I'm trying to manipulate the WordPress content editor, which uses TinyMCE inside of an iframe. I can't seem to get the following code to work as intended: jQuery(document).ready(function($) { $('#content_ifr').ready(function() { $('#content_ifr').contents().find('body').css('background-color', '#f33'); }); Regardless of whether I use ".ready()" or ".load()", the event will fire before the TinyMCE editor (the body of the iframe) is completely finished loading. However, the following code will work if I wait for the iframe to load before manually clicking the title textbox to fire the click event: jQuery(document).ready(function($) { $('#title').click(function() { $('#content_ifr').contents().find('body').css('background-color', '#f33'); }); I've searched exhaustively on the subject of jQuery and iFrames, and it seems it's a hit or miss depending on the situation. Some code works for some people and not for others. Does anyone know of a way to get the first code snippet to fire after the TinyMCE iframe body is completely finished loading? Because it's just the WordPress content editor, the iframe content is on the same domain. What I really want to do is add a class to the body element in the iframe via .addClass() jQuery(document).ready(function($) { $('#content_ifr').ready(function() { $('#content_ifr').contents().find('body').addClass('ui-droppable'); }); so that I can apply the drag n' drop code in the following tutorial: http://skfox.com/2008/11/26/jquery-example-inserting-text-with-drag-n-drop/ A: You can use the tiny_mce_before_init hook to add a class to the body before tinymce.init function my_tiny_mce_before_init( $init_array ) { $init_array['body_class'] = 'some-class some-other-class'; return $init_array; } add_filter('tiny_mce_before_init', 'my_tiny_mce_before_init'); A: I use this function to access or style iframe (inside tinymce) in Wordpess: this script is added to wordpress dashboard scripts, and detects while TINYMCE iframe is loaded, then actions to it. add_action('admin_head', 'my_tinymce_styler',99,99); function my_tinymce_styler() { ?> <script> function myExec() { var theFrame = document.getElementsByTagName("iframe")[0]; if (!theFrame) { window.setTimeout(myExec, 1000); } else { var theFrameDocument = theFrame.contentDocument || theFrame.contentWindow.document; theFrameDocument.body.innerHTML += '<?php echo json_encode(' <style> .parentt{ border:5px solid red !important; } </style>');?>'; } }; window.onload = myExec; </script> <?php } A: Have a look at your tinymce configuration. All you need to so is to use the "setup"-setting and set the onInit-Handler there. Here is an example: tinyMCE.init({ ... setup : function(ed) { ed.onInit.add(function(ed, evt) { window.console && window.console.log('Tinymce Iframe loaded!'); // do whatever you like here }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7604083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delay Touch Response I have a variable called touchStatus that tracks the touch status in the program. The variable gets set to B in the touchesBegan method, E in touchesEnded and to M in touchesMoved. However, my requirements are a little different. I was requested to program in a way so that there is one second of delay between the finger being lift off from the screen and touchStatus getting set to E. If the user touches the screen before the one second elapses, touchStatus should continue to be M or B (whatever it was before the one second). How can I accomplish this? A: You can use [self performSelector:@selector(setEndedValue:) withObject:self afterDelay:1.0]; Create a BOOL to monitor whether the value should be set such as: BOOL hasTouchRestarted = NO; If the screen is touched again before the value is set, change the value to YES and return from the setEndedValue method. -(void)setEndedValue { if ( hasTouchRestarted ) { return; } // set value self.touchStatus = E; } A: In the touchEnded routine set up an NSTimer task to invoke a selector in one second. If there is another touch before then, cancel the timer task. A: Use a NSTimer *timer ivar to initiate a delayed call, and cancel the call if the user lifts the finger before one second. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self.myvar = @"B"; [self.timer invalidate]; self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleOneSecondPress) userInfo:nil repeats:NO]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event { [self.timer invalidate]; self.timer = nil; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { self.myvar = @"M"; } - (void)handleOneSecondPress { self.timer = nil; self.myvar = @"E"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery loading only first class dropdown menu when using .load Ok, here's my issue. I am loading dropdown data from a .txt file to an ID. This particular ID sits in 4 classes, broken by divs for layout purposes $("#dropdown").load("ddData/data.txt"); <div class="Class1"> Dropdown: <select id="SHCC" value="Dropdown"></select></div><br/> <div class="Class2"> Dropdown: <select id="SHCC" value="Dropdown"></select></div><br/> <div class="Class3"> Dropdown: <select id="SHCC" value="Dropdown"></select></div><br/> <div class="Class4"> Dropdown: <select id="SHCC" value="Dropdown"></select></div><br/> This is just a generic example, and I have a reason for doing it this way, but for some reason, only class1 gets loaded with dropdown data, the other classes do not get loaded. Is there an alternative way to load data into drop down menus to keep all data static in each class instead of hardcoding it all in HTML? Thanks. A: Id's are supposed to be unique. Change the ID to a class and you should get the expected behavior, $(".dropdown").load("ddData/data.txt"); <div class="Class1"> Dropdown: <select class="SHCC" value="Dropdown"></select></div><br/> <div class="Class2"> Dropdown: <select class="SHCC" value="Dropdown"></select></div><br/> <div class="Class3"> Dropdown: <select class="SHCC" value="Dropdown"></select></div><br/> <div class="Class4"> Dropdown: <select class="SHCC" value="Dropdown"></select></div><br/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making a DIV hide once FancyBox is opened I'm trying to make an Div disappear when you click the open FancyBox button. My code is: $(document).ready(function() { $('#tag_100_not').fancybox({ 'transitionIn' : 'elastic' , 'transitionOut' : 'elastic' , 'hideOnOverlayClick' : false , 'hideOnContentClick' : false , 'showCloseButton' : false , 'overlayOpacity' : 0.6 , 'onStart' : function() { $('#tag_100_not').css('display', 'none'); }, 'onComplete' : function() { $('#tag_100_not').css('display', 'none'); } }); }); EDIT: MarkUp: <th class="num" style="position:relative;"><a id="tag_100_not" href="#tag_100_box" style="width:100%;height:100%;top:0;left:0;position:absolute;display:block;"></a>100</th`> The div is not disappearing. I tried, onStart and onComplete, none work. A: not sure if it works for one rule, but as far as i know, the css method always accepts a hash $('#tag_100_not').css({'display':'none'}) Though you can always save typing and just use the hide function: $('#tag_100_not').hide()
{ "language": "en", "url": "https://stackoverflow.com/questions/7604090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple form_tag in rails application This is the code in my logins_form.html.erb <%= form_for(@login) do |f| %> // code here <%end%> <%= form_tag(:controller=>'posts', :action=>'index') %> // code here <%end> --1 <%= form_tag(:controller=>'logins', :action=>'create') %> // code here <%end%> --2 It is only accepting one of the 1 or 2 not both. Why so? Even if I remove one of the two, both the forms are redirecting to logins. What am I doing wrong? Thanks. A: Did you copy/paste your exact code? If so look at your first form's end and you will notice your missing the % in the closing %>, which will cause the code to improperly compile the erb template. You should be able to use two forms fine, as long as you are not trying to nest them within each other. A: Would be interesting to see HTML output because you can't have nested forms on your page check question
{ "language": "en", "url": "https://stackoverflow.com/questions/7604094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why won't My App Load in https on Facebook? My app https://apps.facebook.com/acroblast won't load past the loader bar on facebook. It plays just fine in https on a browser though. https://carboncopygames.com/acroblast_flash/acroblast.html So I guess my question is, since I have installed SSL certificate on my server, Do I need to do anything else to make it work. Say put stuff in my code? And yes I updated my secure URLs A: You are using SSL but loading your SWF over HTTP. This is probably what causes the app to never complete loading. SecurityError: Error #2121: Security sandbox violation: Loader.content: http://carboncopygames.com/acroblast_flash/acroblast.swf cannot access https://carboncopygames.com/acroblast_flash/resources.swf. This may be worked around by calling Security.allowDomain. at flash.display::Loader/get content() at com.CopycatGames::CLoading/onComplete()
{ "language": "en", "url": "https://stackoverflow.com/questions/7604095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular expression not returning the .group() value I'm new with java and using regular expressions. The method seems to be OK, and it's finding results on the subject string, but when I try to get the actual string using .group(), it's empty. here's the code: public String TestRegularExpression(){ try{ Pattern regex = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher regexMatcher = regex.matcher(sourceCode); while (regexMatcher.find()) { results += "<li>" + regexMatcher.group() + "</li>"; matches ++; } } catch (PatternSyntaxException ex) { results = "<li><strong class='ibm-important'>Syntax error in the regular expression</strong></li>"; } if(results == null){results = "<li><strong class='ibm-important'>No meta tags found</strong></li>";} return "<h3>" + h3Title + " (" + matches + " found)</h3><ul>" + results + "</ul>"; } Any help will be much appreciated!!! A: Couldn't it be that you're just not seeing the output? If you output the match directly to HTML without quoting it, that'll just insert the META tag in the HTML code, and the web browser won't render it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to SAVE data using proxy in ExtJS Proxy update on ExtJS is not loading my update API instead it loads URL which I use to display data on GRID. <script type="text/javascript"> Ext.onReady(function () { var CoventryItemListStore = new Ext.data.Store({ storeId: CoventryItemListStore, autoSave: true, writer: new Ext.data.JsonWriter(), reader: new Ext.data.JsonReader({ idProperty: 'id', root: 'variables' }, [{ name: 'id' }, { name: 'itemid' }, { name: 'triggerQuantity' }, { name: 'lastUpdatedBy' }, { name: 'lastUpdatedOn' }]), proxy: new Ext.data.HttpProxy({ method: 'POST', prettyUrls: false, url: '/admin/loadCoventryItemApprovalList.epm', api: { update: '/admin/updateCoventryItemApprovalList.epm' } }), listners: { 'write': function (store, action, result, res, rs) { if (action == 'update') { var newId = res.raw.newId; var oldId = res.raw.oldId; if (newId != oldId) { CoventryItemListStore.reload(); } } } } }); CoventryItemListStore.load(); var fm = Ext.form; var CoventryItemListGridUi = Ext.extend(Ext.grid.EditorGridPanel, { title: 'Coventry Item List', store: CoventryItemListStore, width: 980, height: 650, renderTo: 'coventryDiv', defaults: { width: 280 }, defaultType: 'textfield', stripeRows: true, // reader: CoventryItemListReader, autoExpandColumn: 'coventryListCol', align: 'center', clicksToEdit: 1, initComponent: function () { this.columns = [{ xtype: 'gridcolumn', header: 'ID', sortable: true, dataIndex: 'id' }, { xtype: 'gridcolumn', header: 'ITEM ID', sortable: true, width: 250, align: 'center', dataIndex: 'itemid' }, { xtype: 'gridcolumn', header: 'TRIGGER QUANTITY', sortable: true, // id: 'ftpCol', width: 200, align: 'center', dataIndex: 'triggerQuantity', editor: { xtype: 'numberfield' } }, { xtype: 'gridcolumn', header: 'LAST UPDATED BY', sortable: true, width: 80, align: 'center', dataIndex: 'lastUpdatedBy', id: 'coventryListCol' }, { xtype: 'gridcolumn', header: 'LAST UPDATED ON', sortable: false, width: 100, align: 'center', dataIndex: 'lastUpdatedOn', }]; this.listeners = { 'afteredit': function (e) { params: { var oldVal = e.originalValue; var newVal = e.value; var fieldName = e.field; var itemID = e.record.get("itemid"); } alert('Field \'' + fieldName + '\' changed from \'' + oldVal + '\' to \'' + newVal + '\'.(itemID: ' + itemID + ')'); } } var itemsPerPage = 100; this.bbar = new Ext.PagingToolbar({ pageSize: itemsPerPage, autoLoad: true, store: CoventryItemListStore, displayInfo: true, displayMsg: 'Displaying categories {0} - {1} of {2}', emptyMsg: "No categories to display" }); this.tbar = new Ext.Toolbar({ xtype: 'toolbar', items: [{ xtype: 'textfield', id: 'searchValue' }, { xtype: 'button', text: 'Search', style: 'marginLeft: 5px', enableToggle: true, handler: function () { vms.reload({ params: { searchValue: Ext.getCmp('searchValue').getValue() } }); } }] }); CoventryItemListGridUi.superclass.initComponent.call(this); } }); new CoventryItemListGridUi(); }); </script> A: well re posting the answer for better visibility proxy: new Ext.data.HttpProxy({ method: 'POST', prettyUrls: false, url: '/admin/updateCoventryItemApprovalList.epm', api: { read: '/admin/loadCoventryItemApprovalList.epm' } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7604098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a best practice to manage the tombstone state in a Windows Phone 7 application When A WP7 app goes into tombstone state, it is my responsibility to save all the application and page state. That way when the page gets reloaded it can recover and reload the previous data without the user realizes that the application process got terminated and reloaded. Coming from the Android world, I am a new WP7 programmer and don't want to have to reinvent the wheel. Is there a standard way to handle the tombstone state? A: Some of the application frameworks like Caliburn Micro have built in tombstone support to help you along. If you're not using a framework like this then I have heard good things (but not personally used) a library named Tombstone Helper that could help you out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery number counter with jquery mobile I have a peice of code that counts from 0 to a specified number and displays it while it is counting. The problem is that I want to use the code in a web app that is made using jQuery mobile. When the code is used with normal html i works fine, but when I use it with jQuery mobile it wont work. I dont want the number to start counting until a certain mobile page is loaded, is there a way to do this?? I think the problem is because in jquery mobile all of the pages are contained within one html document and the number sarts counting when the html page is open and I want it to start when the '#about' section is displayed? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { $('#foo').counter({ start: 1000, end: 400000, time: 1, step: 50, callback: function() { $("#foo").html("400000"); } }); }); ;(function($) { $.fn.counter = function(options) { var options = $.extend(defaults, options); var counterFunc = function(el, increment, end, step) { var value = parseInt(el.html(), 10) + increment; if(value >= end) { el.html(Math.round(end)); options.callback(); } else { el.html(Math.round(value)); setTimeout(counterFunc, step, el, increment, end, step); } } $(this).html(Math.round(options.start)); var increment = (options.end - options.start) / ((1000 / options.step) * options.time); (function(e, i, o, s) { setTimeout(counterFunc, s, e, i, o, s); })($(this), increment, options.end, options.step); } })(jQuery); </script> <style type="text/css"> </style> </head> <body> <span id="foo"></span> </body> </html> A: Check-out the events documentation for jQuery Mobile: http://jquerymobile.com/demos/1.0rc1/docs/api/events.html. Rather than running your code on document.ready you want to run it on pageshow. Change: $(function() { $('#foo').counter({ start: 1000, end: 400000, time: 1, step: 50, callback: function() { $("#foo").html("400000"); } }); }); To: $(document).delegate('#about', 'pageshow', function() { $('#foo').counter({ start: 1000, end: 400000, time: 1, step: 50, callback: function() { $("#foo").html("400000"); } }); }); I have not used the "counter" plugin so I'm not sure how to do it but you may want to stop the counter when the user navigates to another page, to do so just bind whatever code stops the counter to the pagehide event: $(document).delegate('#about', 'pagehide', function () { //code to stop counter goes here }); A NOTE: I use the .delegate() function in the examples above which when used on the $(document) object acts like the .live() function: $(document).delegate('#about', 'event-name', function () {}); is similar to $(#about).live('event-name', function () {}); however .delegate() performs more efficiently. Documentation for delegate is here: http://api.jquery.com/delegate/
{ "language": "en", "url": "https://stackoverflow.com/questions/7604103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simplexml_load_string() removing a lot of content Simplexml_load_string is removing a lot of content that is passing into it. var_dump($cleaned); <item> <title><![CDATA[Honda Motor Company: Motorcycles to the Civic and Accord]]></title> <link>http://www.link.com/index.php?id=9987</link> <description><![CDATA[Though this company is famous for its cars, it actually started as a motorcycle manufacturer. http://www.link.com takes a look at the history of the Honda Motor Company, from its popular motorcycles to the Civic and the Accord.]]> </description> <pubDate>Fri, 23 Sep 2011 10:55:50 -0400</pubDate> <guid>https://link.cloudfront.net/581575d3053ac1a578065c10f2bac1be.mp4</guid> <media:title><![CDATA[Honda Motor Company: Motorcycles to the Civic and Accord]]> </media:title> <media:description><![CDATA[Though this company is famous for its cars, it actually started as a motorcycle manufacturer. http://www.link.com takes a look at the history of the Honda Motor Company, from its popular motorcycles to the Civic and the Accord.]]></media:description> <media:keywords><![CDATA[Honda Motor Company, Honda, motorcycles, Japan, Civic, Accord, Formula 1, F1, Acura, fuel efficiency, hybrid, ASIMO, robot, aviation, Dream D, Isle of Man races, Super Cub, auto, automotive, automobile, automaker, cars, driving, history, Soichiro Honda]]></media:keywords> <media:tags><![CDATA[Asian History, Automakers, Company Profiles, Honda Motor Company, Honda, motorcycles, Japan, Civic, Accord, Formula 1, F1, Acura, fuel efficiency, hybrid, robot, aviation, auto, automotive, automobile, automaker, cars, driving, history, Soichiro Honda]]></media:tags> <media:category><![CDATA[/Video/Auto/Reviews and Profiles]]></media:category> <media:thumbnail url="http://link.cloudfront.net/images/linkthumbs/A-RP-Honda-480i60_100x57.jpg"/> <media:content url="https://link.cloudfront.net/581575d3053ac1a578065c10f2bac1be.mp4" type="video/mp4" > <media:thumbnail url="http://link.cloudfront.net/images/linkthumbs/A-RP-Honda-480i60_100x57.jpg"/> <media:player url="http://www.link.com/index.php?id=9987"><![CDATA[<embed src="https://link.cloudfront.net/581575d3053ac1a578065c10f2bac1be.mp4" type="application/x-shockwave-flash" wmode="transparent" width="480" height="270"></embed>]]></media:player> <media:text_content><![CDATA[Long description.]]></media:text_content> <media:filename><![CDATA[]]></media:filename> <media:author><![CDATA[Rebecca Brayton]]></media:author> <media:bliptv_thumbnail><![CDATA[A-RP-Honda-480i60_480x270.jpg]]></media:bliptv_thumbnail> <media:preference_rate><![CDATA[4]]></media:preference_rate> </media:content> After running the code below $xml = simplexml_load_string(utf8_encode($cleaned), 'SimpleXMLElement', LIBXML_NOCDATA); It returns ["item"]=> array(100) { [0]=> object(SimpleXMLElement)#4 (5) { ["title"]=> string(56) "Honda Motor Company: Motorcycles to the Civic and Accord" ["link"]=> string(42) "http://www.link.com/index.php?id=9987" ["description"]=> string(232) "long description." ["pubDate"]=> string(31) "Fri, 23 Sep 2011 10:55:50 -0400" ["guid"]=> string(74) "https://link.cloudfront.net/581575d3053ac1a578065c10f2bac1be.mp4" } No other code is being ran before this and I just can't seem to figure out why on earth this is happening. Anyone know the reason behind this, is it due to the utf-8 encode? A: You need to call SimpleXMLElement->children() with the "media" namespace to get the portions which are of the <media:xxx> kind of format, or pass the $ns argument to simplexml_load_string() to specify the namespace you want to load: $xml = simplexml_load_string(utf8_encode($cleaned), 'SimpleXMLElement', LIBXML_NOCDATA, 'media'); http://www.php.net/manual/en/function.simplexml-load-string.php http://www.php.net/manual/en/simplexmlelement.children.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7604105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linux, convert errno to name I am looking for an API to convert an errno integer to its name. For example: int fd; if((fd = open(path, O_RDONLY)) == -1) printf("error: %d %s %s\n", errno, strerror(errno), ERRNONAME(errno)); So, ERRNONAME would yield a name, such as "EINVAL", "EPERM", etc. Is this possible? A: Those names exist as macros in the Errno.h file. There's no standard call to convert the error number to the short code. You could build your own table ... A: I recently wrote the errnoname library that has an errnoname function which lets you do this. There is unfortunately still no standard API to do this. I try to keep it portable to all systems while covering all errno names on that system. So far that includes Linux, Darwin (macOS, iOS, etc), BSD (FreeBSD, NetBSD, OpenBSD, etc), several closed-source Unixes, Windows, and a few others. The only "hard" part is getting the list of errno names and values to do the lookups, knowing which errno are even defined on the target system, and exhaustively handling all cases where multiple errno names might map to the same number. (For example, EWOULDBLOCK is equal to EAGAIN on some systems.) So in my errnoname library you don't have to deal with any of that. I collect the errno names for many operating systems into a list as a separate step, then I generate the actual released C code from that. The C code uses #ifdef for each name, so it can compile on any system regardless of which errno names and values that system has. The compiled result is just simple and efficient code that doesn't have to call any programs or search for errno in library headers. I also give you the option to compile it as either an array lookup or as a switch, since errno value are not guaranteed to be even close to contiguous, but on many system are contiguous enough to make an array lookup far better. (Although good modern compilers can automatically notice when it would be better to turn a switch into an array lookup.) Anyway, since it is released under the "Zero-Clause BSD license" (0BSD), which is a permissive license, or more accurately a public-domain-equivalent license, you can do whatever you want with it. Below is an old copy-paste of the function from my library, so that this answer is useful even if my repo link ever goes dead, but beware: * *The copy here only covers all errno names I could find as of start of August 2019 - I have found many others since then. *I will keep updating the library to include errno names as I find them and as systems add them, add other improvements, and add duplicate protections as possible duplicates are discovered. But I will not (and last I checked, cannot, due to size limits on the answer) keep this answer's copy updated. #include <errno.h> char const * errnoname(int errno_) { switch(errno_) { #ifdef E2BIG case E2BIG: return "E2BIG"; #endif #ifdef EACCES case EACCES: return "EACCES"; #endif #ifdef EADDRINUSE case EADDRINUSE: return "EADDRINUSE"; #endif #ifdef EADDRNOTAVAIL case EADDRNOTAVAIL: return "EADDRNOTAVAIL"; #endif #ifdef EADI case EADI: return "EADI"; #endif #ifdef EADV case EADV: return "EADV"; #endif #ifdef EAFNOSUPPORT case EAFNOSUPPORT: return "EAFNOSUPPORT"; #endif #ifdef EAGAIN case EAGAIN: return "EAGAIN"; #endif #ifdef EAIO case EAIO: return "EAIO"; #endif #ifdef EALIGN case EALIGN: return "EALIGN"; #endif #ifdef EALREADY case EALREADY: return "EALREADY"; #endif #ifdef EASYNC case EASYNC: return "EASYNC"; #endif #ifdef EAUTH case EAUTH: return "EAUTH"; #endif #ifdef EBADARCH case EBADARCH: return "EBADARCH"; #endif #ifdef EBADE case EBADE: return "EBADE"; #endif #ifdef EBADEXEC case EBADEXEC: return "EBADEXEC"; #endif #ifdef EBADF case EBADF: return "EBADF"; #endif #ifdef EBADFD case EBADFD: return "EBADFD"; #endif #ifdef EBADMACHO case EBADMACHO: return "EBADMACHO"; #endif #ifdef EBADMSG case EBADMSG: return "EBADMSG"; #endif #ifdef EBADR case EBADR: return "EBADR"; #endif #ifdef EBADRPC case EBADRPC: return "EBADRPC"; #endif #ifdef EBADRQC case EBADRQC: return "EBADRQC"; #endif #ifdef EBADSLT case EBADSLT: return "EBADSLT"; #endif #ifdef EBADVER case EBADVER: return "EBADVER"; #endif #ifdef EBFONT case EBFONT: return "EBFONT"; #endif #ifdef EBUSY case EBUSY: return "EBUSY"; #endif #ifdef ECANCELED case ECANCELED: return "ECANCELED"; #endif #if defined(ECANCELLED) && (!defined(ECANCELED) || ECANCELLED != ECANCELED) case ECANCELLED: return "ECANCELLED"; #endif #ifdef ECAPMODE case ECAPMODE: return "ECAPMODE"; #endif #ifdef ECHILD case ECHILD: return "ECHILD"; #endif #ifdef ECHRNG case ECHRNG: return "ECHRNG"; #endif #ifdef ECKPT case ECKPT: return "ECKPT"; #endif #ifdef ECLONEME case ECLONEME: return "ECLONEME"; #endif #ifdef ECOMM case ECOMM: return "ECOMM"; #endif #ifdef ECONFIG case ECONFIG: return "ECONFIG"; #endif #ifdef ECONNABORTED case ECONNABORTED: return "ECONNABORTED"; #endif #ifdef ECONNREFUSED case ECONNREFUSED: return "ECONNREFUSED"; #endif #ifdef ECONNRESET case ECONNRESET: return "ECONNRESET"; #endif #ifdef ECORRUPT case ECORRUPT: return "ECORRUPT"; #endif #ifdef ECVCERORR case ECVCERORR: return "ECVCERORR"; #endif #ifdef ECVPERORR case ECVPERORR: return "ECVPERORR"; #endif #ifdef EDEADLK case EDEADLK: return "EDEADLK"; #endif #if defined(EDEADLOCK) && (!defined(EDEADLK) || EDEADLOCK != EDEADLK) case EDEADLOCK: return "EDEADLOCK"; #endif #ifdef EDESTADDREQ case EDESTADDREQ: return "EDESTADDREQ"; #endif #ifdef EDESTADDRREQ case EDESTADDRREQ: return "EDESTADDRREQ"; #endif #ifdef EDEVERR case EDEVERR: return "EDEVERR"; #endif #ifdef EDIRIOCTL case EDIRIOCTL: return "EDIRIOCTL"; #endif #ifdef EDIRTY case EDIRTY: return "EDIRTY"; #endif #ifdef EDIST case EDIST: return "EDIST"; #endif #ifdef EDOM case EDOM: return "EDOM"; #endif #ifdef EDOOFUS case EDOOFUS: return "EDOOFUS"; #endif #ifdef EDOTDOT case EDOTDOT: return "EDOTDOT"; #endif #ifdef EDQUOT case EDQUOT: return "EDQUOT"; #endif #ifdef EDUPFD case EDUPFD: return "EDUPFD"; #endif #ifdef EDUPPKG case EDUPPKG: return "EDUPPKG"; #endif #ifdef EEXIST case EEXIST: return "EEXIST"; #endif #ifdef EFAIL case EFAIL: return "EFAIL"; #endif #ifdef EFAULT case EFAULT: return "EFAULT"; #endif #ifdef EFBIG case EFBIG: return "EFBIG"; #endif #ifdef EFORMAT case EFORMAT: return "EFORMAT"; #endif #ifdef EFSCORRUPTED case EFSCORRUPTED: return "EFSCORRUPTED"; #endif #ifdef EFTYPE case EFTYPE: return "EFTYPE"; #endif #ifdef EHOSTDOWN case EHOSTDOWN: return "EHOSTDOWN"; #endif #ifdef EHOSTUNREACH case EHOSTUNREACH: return "EHOSTUNREACH"; #endif #ifdef EHWPOISON case EHWPOISON: return "EHWPOISON"; #endif #ifdef EIDRM case EIDRM: return "EIDRM"; #endif #ifdef EILSEQ case EILSEQ: return "EILSEQ"; #endif #ifdef EINIT case EINIT: return "EINIT"; #endif #ifdef EINPROG case EINPROG: return "EINPROG"; #endif #ifdef EINPROGRESS case EINPROGRESS: return "EINPROGRESS"; #endif #ifdef EINTEGRITY case EINTEGRITY: return "EINTEGRITY"; #endif #ifdef EINTR case EINTR: return "EINTR"; #endif #ifdef EINVAL case EINVAL: return "EINVAL"; #endif #ifdef EIO case EIO: return "EIO"; #endif #ifdef EIPSEC case EIPSEC: return "EIPSEC"; #endif #ifdef EISCONN case EISCONN: return "EISCONN"; #endif #ifdef EISDIR case EISDIR: return "EISDIR"; #endif #ifdef EISNAM case EISNAM: return "EISNAM"; #endif #ifdef EJUSTRETURN case EJUSTRETURN: return "EJUSTRETURN"; #endif #ifdef EKEEPLOOKING case EKEEPLOOKING: return "EKEEPLOOKING"; #endif #ifdef EKEYEXPIRED case EKEYEXPIRED: return "EKEYEXPIRED"; #endif #ifdef EKEYREJECTED case EKEYREJECTED: return "EKEYREJECTED"; #endif #ifdef EKEYREVOKED case EKEYREVOKED: return "EKEYREVOKED"; #endif #ifdef EL2HLT case EL2HLT: return "EL2HLT"; #endif #ifdef EL2NSYNC case EL2NSYNC: return "EL2NSYNC"; #endif #ifdef EL3HLT case EL3HLT: return "EL3HLT"; #endif #ifdef EL3RST case EL3RST: return "EL3RST"; #endif #ifdef ELIBACC case ELIBACC: return "ELIBACC"; #endif #ifdef ELIBBAD case ELIBBAD: return "ELIBBAD"; #endif #ifdef ELIBEXEC case ELIBEXEC: return "ELIBEXEC"; #endif #ifdef ELIBMAX case ELIBMAX: return "ELIBMAX"; #endif #ifdef ELIBSCN case ELIBSCN: return "ELIBSCN"; #endif #ifdef ELNRNG case ELNRNG: return "ELNRNG"; #endif #ifdef ELOCKUNMAPPED case ELOCKUNMAPPED: return "ELOCKUNMAPPED"; #endif #ifdef ELOOP case ELOOP: return "ELOOP"; #endif #ifdef EMEDIA case EMEDIA: return "EMEDIA"; #endif #ifdef EMEDIUMTYPE case EMEDIUMTYPE: return "EMEDIUMTYPE"; #endif #ifdef EMFILE case EMFILE: return "EMFILE"; #endif #ifdef EMLINK case EMLINK: return "EMLINK"; #endif #ifdef EMOUNTEXIT case EMOUNTEXIT: return "EMOUNTEXIT"; #endif #ifdef EMOVEFD case EMOVEFD: return "EMOVEFD"; #endif #ifdef EMSGSIZE case EMSGSIZE: return "EMSGSIZE"; #endif #ifdef EMTIMERS case EMTIMERS: return "EMTIMERS"; #endif #ifdef EMULTIHOP case EMULTIHOP: return "EMULTIHOP"; #endif #ifdef ENAMETOOLONG case ENAMETOOLONG: return "ENAMETOOLONG"; #endif #ifdef ENAVAIL case ENAVAIL: return "ENAVAIL"; #endif #ifdef ENEEDAUTH case ENEEDAUTH: return "ENEEDAUTH"; #endif #ifdef ENETDOWN case ENETDOWN: return "ENETDOWN"; #endif #ifdef ENETRESET case ENETRESET: return "ENETRESET"; #endif #ifdef ENETUNREACH case ENETUNREACH: return "ENETUNREACH"; #endif #ifdef ENFILE case ENFILE: return "ENFILE"; #endif #ifdef ENFSREMOTE case ENFSREMOTE: return "ENFSREMOTE"; #endif #ifdef ENOANO case ENOANO: return "ENOANO"; #endif #ifdef ENOATTR case ENOATTR: return "ENOATTR"; #endif #ifdef ENOBUFS case ENOBUFS: return "ENOBUFS"; #endif #ifdef ENOCONNECT case ENOCONNECT: return "ENOCONNECT"; #endif #ifdef ENOCSI case ENOCSI: return "ENOCSI"; #endif #ifdef ENODATA case ENODATA: return "ENODATA"; #endif #ifdef ENODEV case ENODEV: return "ENODEV"; #endif #ifdef ENOENT case ENOENT: return "ENOENT"; #endif #ifdef ENOEXEC case ENOEXEC: return "ENOEXEC"; #endif #ifdef ENOIOCTL case ENOIOCTL: return "ENOIOCTL"; #endif #ifdef ENOKEY case ENOKEY: return "ENOKEY"; #endif #ifdef ENOLCK case ENOLCK: return "ENOLCK"; #endif #ifdef ENOLINK case ENOLINK: return "ENOLINK"; #endif #ifdef ENOLOAD case ENOLOAD: return "ENOLOAD"; #endif #ifdef ENOMATCH case ENOMATCH: return "ENOMATCH"; #endif #ifdef ENOMEDIUM case ENOMEDIUM: return "ENOMEDIUM"; #endif #ifdef ENOMEM case ENOMEM: return "ENOMEM"; #endif #ifdef ENOMSG case ENOMSG: return "ENOMSG"; #endif #ifdef ENONET case ENONET: return "ENONET"; #endif #ifdef ENOPKG case ENOPKG: return "ENOPKG"; #endif #ifdef ENOPOLICY case ENOPOLICY: return "ENOPOLICY"; #endif #ifdef ENOPROTOOPT case ENOPROTOOPT: return "ENOPROTOOPT"; #endif #ifdef ENOREG case ENOREG: return "ENOREG"; #endif #ifdef ENOSPC case ENOSPC: return "ENOSPC"; #endif #ifdef ENOSR case ENOSR: return "ENOSR"; #endif #ifdef ENOSTR case ENOSTR: return "ENOSTR"; #endif #ifdef ENOSYM case ENOSYM: return "ENOSYM"; #endif #ifdef ENOSYS case ENOSYS: return "ENOSYS"; #endif #ifdef ENOTACTIVE case ENOTACTIVE: return "ENOTACTIVE"; #endif #ifdef ENOTBLK case ENOTBLK: return "ENOTBLK"; #endif #ifdef ENOTCAPABLE case ENOTCAPABLE: return "ENOTCAPABLE"; #endif #ifdef ENOTCONN case ENOTCONN: return "ENOTCONN"; #endif #ifdef ENOTDIR case ENOTDIR: return "ENOTDIR"; #endif #ifdef ENOTEMPTY case ENOTEMPTY: return "ENOTEMPTY"; #endif #ifdef ENOTNAM case ENOTNAM: return "ENOTNAM"; #endif #ifdef ENOTREADY case ENOTREADY: return "ENOTREADY"; #endif #ifdef ENOTRECOVERABLE case ENOTRECOVERABLE: return "ENOTRECOVERABLE"; #endif #ifdef ENOTRUST case ENOTRUST: return "ENOTRUST"; #endif #ifdef ENOTSOCK case ENOTSOCK: return "ENOTSOCK"; #endif #ifdef ENOTSUP case ENOTSUP: return "ENOTSUP"; #endif #ifdef ENOTTY case ENOTTY: return "ENOTTY"; #endif #ifdef ENOTUNIQ case ENOTUNIQ: return "ENOTUNIQ"; #endif #ifdef ENOUNLD case ENOUNLD: return "ENOUNLD"; #endif #ifdef ENOUNREG case ENOUNREG: return "ENOUNREG"; #endif #ifdef ENXIO case ENXIO: return "ENXIO"; #endif #ifdef EOPCOMPLETE case EOPCOMPLETE: return "EOPCOMPLETE"; #endif #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || EOPNOTSUPP != ENOTSUP) case EOPNOTSUPP: return "EOPNOTSUPP"; #endif #ifdef EOVERFLOW case EOVERFLOW: return "EOVERFLOW"; #endif #ifdef EOWNERDEAD case EOWNERDEAD: return "EOWNERDEAD"; #endif #ifdef EPASSTHROUGH case EPASSTHROUGH: return "EPASSTHROUGH"; #endif #ifdef EPATHREMOTE case EPATHREMOTE: return "EPATHREMOTE"; #endif #ifdef EPERM case EPERM: return "EPERM"; #endif #ifdef EPFNOSUPPORT case EPFNOSUPPORT: return "EPFNOSUPPORT"; #endif #ifdef EPIPE case EPIPE: return "EPIPE"; #endif #ifdef EPOWERF case EPOWERF: return "EPOWERF"; #endif #ifdef EPROCLIM case EPROCLIM: return "EPROCLIM"; #endif #ifdef EPROCUNAVAIL case EPROCUNAVAIL: return "EPROCUNAVAIL"; #endif #ifdef EPROGMISMATCH case EPROGMISMATCH: return "EPROGMISMATCH"; #endif #ifdef EPROGUNAVAIL case EPROGUNAVAIL: return "EPROGUNAVAIL"; #endif #ifdef EPROTO case EPROTO: return "EPROTO"; #endif #ifdef EPROTONOSUPPORT case EPROTONOSUPPORT: return "EPROTONOSUPPORT"; #endif #ifdef EPROTOTYPE case EPROTOTYPE: return "EPROTOTYPE"; #endif #ifdef EPWROFF case EPWROFF: return "EPWROFF"; #endif #ifdef EQFULL case EQFULL: return "EQFULL"; #endif #ifdef EQSUSPENDED case EQSUSPENDED: return "EQSUSPENDED"; #endif #ifdef ERANGE case ERANGE: return "ERANGE"; #endif #ifdef ERECYCLE case ERECYCLE: return "ERECYCLE"; #endif #ifdef EREDRIVEOPEN case EREDRIVEOPEN: return "EREDRIVEOPEN"; #endif #ifdef EREFUSED case EREFUSED: return "EREFUSED"; #endif #ifdef ERELOC case ERELOC: return "ERELOC"; #endif #ifdef ERELOCATED case ERELOCATED: return "ERELOCATED"; #endif #ifdef ERELOOKUP case ERELOOKUP: return "ERELOOKUP"; #endif #ifdef EREMCHG case EREMCHG: return "EREMCHG"; #endif #ifdef EREMDEV case EREMDEV: return "EREMDEV"; #endif #ifdef EREMOTE case EREMOTE: return "EREMOTE"; #endif #ifdef EREMOTEIO case EREMOTEIO: return "EREMOTEIO"; #endif #ifdef EREMOTERELEASE case EREMOTERELEASE: return "EREMOTERELEASE"; #endif #ifdef ERESTART case ERESTART: return "ERESTART"; #endif #ifdef ERFKILL case ERFKILL: return "ERFKILL"; #endif #ifdef EROFS case EROFS: return "EROFS"; #endif #ifdef ERPCMISMATCH case ERPCMISMATCH: return "ERPCMISMATCH"; #endif #ifdef ESAD case ESAD: return "ESAD"; #endif #ifdef ESHLIBVERS case ESHLIBVERS: return "ESHLIBVERS"; #endif #ifdef ESHUTDOWN case ESHUTDOWN: return "ESHUTDOWN"; #endif #ifdef ESOCKTNOSUPPORT case ESOCKTNOSUPPORT: return "ESOCKTNOSUPPORT"; #endif #ifdef ESOFT case ESOFT: return "ESOFT"; #endif #ifdef ESPIPE case ESPIPE: return "ESPIPE"; #endif #ifdef ESRCH case ESRCH: return "ESRCH"; #endif #ifdef ESRMNT case ESRMNT: return "ESRMNT"; #endif #ifdef ESTALE case ESTALE: return "ESTALE"; #endif #ifdef ESTART case ESTART: return "ESTART"; #endif #ifdef ESTRPIPE case ESTRPIPE: return "ESTRPIPE"; #endif #ifdef ESYSERROR case ESYSERROR: return "ESYSERROR"; #endif #ifdef ETIME case ETIME: return "ETIME"; #endif #ifdef ETIMEDOUT case ETIMEDOUT: return "ETIMEDOUT"; #endif #ifdef ETOOMANYREFS case ETOOMANYREFS: return "ETOOMANYREFS"; #endif #ifdef ETXTBSY case ETXTBSY: return "ETXTBSY"; #endif #ifdef EUCLEAN case EUCLEAN: return "EUCLEAN"; #endif #ifdef EUNATCH case EUNATCH: return "EUNATCH"; #endif #ifdef EUSERS case EUSERS: return "EUSERS"; #endif #ifdef EVERSION case EVERSION: return "EVERSION"; #endif #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || EWOULDBLOCK != EAGAIN) case EWOULDBLOCK: return "EWOULDBLOCK"; #endif #ifdef EWRONGFS case EWRONGFS: return "EWRONGFS"; #endif #ifdef EWRPROTECT case EWRPROTECT: return "EWRPROTECT"; #endif #ifdef EXDEV case EXDEV: return "EXDEV"; #endif #ifdef EXFULL case EXFULL: return "EXFULL"; #endif } return 0; } A: You can use strerror libc function #include <string.h> ... printf("err = %s \n", strerror(errno)); It does not return exact error string, but description. For example instead of EINVAL, it returns Invalid Argument
{ "language": "en", "url": "https://stackoverflow.com/questions/7604107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why does Application.Idle never fire when my form is hosted in a MFC application? I'm building a .net plugin for a MFC application. I created a form using WinForms and .net4. The form is shown after user clicks a button in the MFC application. One of my controls uses Application.Idle to do some task. The problem is, it seems Application.Idle is never fired. * *What exactly does "Application" refer to in this scenario? Is it the whole MFC application, or the .net form? *Why doesn't Application.Idle fire? UPDATE I managed to get it work, here are the two possible solutions: * *show the form using Form.ShowDialog() (thus the form runs its own .net message pump) *create a STA thread, create the form on the STA thread and call Application.Run(). Then you can use Form.Show() (the form uses the .net message pump in the thread it was created, in this case: .net STA thread) A: The only way that Winforms can figure out that the application is idle is when it doesn't find any other messages on the message queue. Your problem is that it is not Winforms that pumps the message loop, it is MFC. Which doesn't know anything about the Winforms bells and whistles. Other things go wrong, note that tabbing and short-cut keystrokes no longer work, also handled by the Winforms message loop. There is no clean solution for this, there can be only one master. Very imperfect fixes are using Form.ShowDialog() and starting a new STA thread so that you can call Application.Run(). A: The .net form is not a .net application, and neither is the MFC application. MFC has its own code that it calls in the application when it's idle; it has no knowledge of Application.Idle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Self-referential tables with polymorphism in SQLAlchemy So I'm having issues with my model right now. I came across these two (1) (2) questions which helped me a lot, but now I'm stuck. Here's my current code: class Post(Base): __tablename__ = 'post' id = Column(Integer, primary_key=True) type = Column('type', String(10)) created = Column(TIMESTAMP(), default=datetime.now()) updated = Column(TIMESTAMP(), default=datetime.now()) poster_id = Column(Integer, ForeignKey('person.id')) poster = relationship('Person', backref=backref('posts')) __mapper_args__ = {'polymorphic_on': type} class Comment(Post): __tablename__ = 'comment' __mapper_args__ = {'polymorphic_identity': 'comment', 'inherit_condition': (id == Post.id)} id = Column(Integer, ForeignKey('post.id'), primary_key=True) post_id = Column(Integer, ForeignKey('post.id')) post = relationship('Post', primaryjoin=('Comment.post_id == Post.id'), backref=backref('comments'), remote_side='Post.id') text = Column(Text) The current error I'm getting is: TypeError: Incompatible collection type: int is not list-like What am I doing wrong? Thanks. A: id is a really unfortunate name for a column; id is a built-in function, and so it's always defined. If you had chosen a less mainstream name for your primary keys, you would be seeing a different error and it would be obvious; class Comment(Post): __tablename__ = 'comment' __mapper_args__ = {'polymorphic_identity': 'comment', 'inherit_condition': (id == Post.id)} # ^^ That id refers to __builtins__.id, which is a function that returns the address of a python object. Probably not what you meant. Easy solution: move __mapper_args__ below the line where you alias id to mean your actual table Column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do properties of attributes have to be readable? Consider the following attribute. internal class NiceAttribute : Attribute { private string _stuff; public string Stuff { set { _stuff = value; } } } When I try to use the attribute [Nice(Stuff = "test")] the compiler gives the following error. 'Stuff' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static, or const, or read-write properties which are public and not static. What is the rational behind the requirement for the property to be readable? Update I will try to sketch my use case for having write-only properties on attributes. interface ISettingsBuilder { Settings GetSettings(); } class SettingsAttribute : Attribute, ISettingsBuilder { private readonly IDictionary<string, object> _settings = new Dictionary<string, object>(); public Settings GetSettings() { // Use _settings to create an immutable instance of Settings } public string Stuff { set { _settings["Stuff"] = value; } } // More properties ... } There may be other implementations of ISettingsBuilder. For example one that offers a nice API to build settings through code. I ended up with implementing my getters by throwing a NotImplementedException. public string Stuff { get { throw new NotImplementedException(); } set { _settings["Stuff"] = value; } } Can you think of a nicer way to do something like this? A: I suspect the compiler is using a slightly misguided check to see whether you are accessing a private property here Edit "we" have now located the actual source. For informational purposes, here is the full breakdown, but feel free to skip to the bottom. (note how bug should be filed against the Mono compiler. I'll think that one over for a while) Compiler Error CS0617 * *http://msdn.microsoft.com/en-us/library/978b3z1b(v=vs.71).aspx 'reference' is not a valid named attribute argument. Named attribute arguments must be fields which are not readonly, static or const, or read-write properties which are not static. An attempt was made to access a private member of an attribute class. It could seem that it is using some kind of lookup (akin to reflection) to make sure that the getter is accessible and if it isn't, concludes that it must be private. Which, of course, it doesn't need to be :) Mono Compatibility: For fun, observe that the mono compiler has no problem whatsoever accepting this attribute: https://ideone.com/45fCX Because of Reflection: Of course it could be that the compiler requires attribute parameters to have reflectable values. If the property wasn't publicly readable, you could only use reflection to 'observe' that the attribute is present, not with what parameter it was initialized. I don't know exactly, why such a design choicde would have been made, but it does make sense if you factor in reflection usage. Update @Arun posted the relevant quote that confirms this conjecture (thanks!): Accessing Attributes Through Reflection Once attributes have been associated with program elements, reflection can be used to query their existence and values. The main reflection methods to query attributes are contained in the System.Reflection.MemberInfo class (GetCustomAttributes family of methods). So the reason must be: Attribute parameters must have reflectible values Prize question: How does that work with positional parameters? How would one reflect those? A: This link is a reference from Visual Studio 2003, but I guess it hardly changed. Relevant portion from that link: Accessing Attributes Through Reflection Once attributes have been associated with program elements, reflection can be used to query their existence and values. The main reflection methods to query attributes are contained in the System.Reflection.MemberInfo class (GetCustomAttributes family of methods).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Is it okay to store session id in localStorage? Is it secure to store user's session id in localStorage? On w3.org site, they say User agents must raise a SECURITY_ERR exception whenever any of the members of a Storage object originally returned by the localStorage attribute are accessed by scripts whose effective script origin is not the same as the origin of the Document of the Window object on which the localStorage attribute was accessed. So does this mean localStorage could be used for sensitive data? A: httpOnly cookies provide a layer of XSS defence that localStorage does not provide: * *httpOnly cookies are not accessible from [potentially malicious] JS. *localStorage is accessible from JS. Session IDs should be stored in httpOnly secure cookies. A: It depends upon what you mean by "is it secure"? localStorage is about as secure as a non-path restricted cookie. From web pages, it can only be accessed by pages from the same domain. Zillions of sites store session ids in cookies which have about the same security restrictions as localStorage. Outside of web pages, neither localStorage nor cookies are secure at all from access by other programs or even web debugging tools running on the same computer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: delayed_job Won't Process My Queue? I am using the delayed_jobs gem but using it against 2 queues. I have mapped my models against the correct queues (dbs) to establish correct connections. The jobs get entered in fine - however, delayed_jobs will process one queue fine but not the other. I am trying to manually force it to process the email queue but it simply won't. Is there a way to config/force it to? Or pass it the correct backend to process? See below I am counting jobs - getting a correct count. However, if I try to 'work_off' the queue its showing 0 success/fails. Pretty sure because its hitting the wrong queue. Any ideas? Delayed::Worker::Email::Job.count => 12032 Delayed::Worker.new(:backend => Email::Job).work_off => [0, 0] A: I ended up just going with one queue. This seemed to work best and save the headache of juggling two. Would be cool if DJ would eventually support multi-backends/queues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery update div the moment a table is updated I'm trying to figure out a way to have jQuery update a div the moment a table in mysql is updated. I've spent a vigorous amount of hours searching online for an answer, and so far, nothing. Can anyone help me out with this problem? A: Well the steps you should probably take are: Have a piece of AJAX code that queries the server for a change (like row count changing or something along those lines). Using jQuery you can do that: function checkUpdates() { $.ajax({ type: "POST", url: 'hasDataChanged.php', // a webservice or other URL that queries the database data: {}, contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { // return a JSON string like { "hasChanged" : "true" } or something if (data.hasChanged) { // data has changed, do something } } }); } Then you can use the Javascript method setInterval to call the code every few seconds. It is unrealistic to do it instantly. $(document).ready(function() { setInterval("checkUpdates()", 3000); // Calls the function every 3 seconds }); A: You'll have to poll the database via ajax and php every (couple of) second(s) and check if the data has changed. if so, update the div. i don't think there's a way of detecting the exact moment the db is updated. A: Useful links on polling. It attempts to make server send data to browser: * *http://onepixelahead.com/2010/04/30/html5-web-sockets-example/ *http://en.wikipedia.org/wiki/Comet_(programming))
{ "language": "en", "url": "https://stackoverflow.com/questions/7604129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ARM binary and hexedit I have an ARM binary file and want to change some text. I remove couple of text-symbols from comment. But the binary won't start, with log: link_image[1710]: 3013 missing essential tables CANNOT LINK EXECUTABLE Does anybody have an idea how to edit ARM binary files? A: I remove couple of text-symbols Stop right there. If I am reading what you wrote correctly, you removed some characters, instead of replacing them with other characters. This would shift the whole rest of the file. But binary files often have tables or offsets which point to other parts of the file. Shifting the contents of the file, even by a single byte, means these tables or offsets no longer point where they should. The code trying to read the file was rightly confused after that. When editing binary files, you must never move the contents, unless you know what you are doing. If you are editing the text, your changes must not change the size of the text. If the new text is smaller, you must pad it so it keeps the same size; if the new text is larger, it will not fit and you must find a shorter text. Of course, this assumes that the file format does not have checksums which would notice the change, or that you know how to recompute them. Also, make sure you are using a proper editor. Normal text editors can silently add, remove, or replace characters, which could break the file, possibly in a hard-to-detect way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: <%= link_to_function "Back", "history.back()" %> does not work in new and edit.html.erb <%= link_to_function "Back", "history.back()" %> The above does not work in new and edit.html.erb. The back link points to itself (/new# or /edit#) so it does not really go anywhere back. However the back button works in index.html.erb. See another stackoverflow post on back button: 'Back' browser action in Ruby on Rails Any thoughts? Thanks. PS: Category controller: class CategoriesController < ApplicationController before_filter :require_signin before_filter :require_employee def index if session[:eng_dh] @categories = Category.all else @categories = Category.active_cate.all end end def new @category = Category.new end def create if session[:eng_dh] #dynamic attr_accessible @category = Category.new(params[:category], :as => :roles_new) if @category.save #@categories = Category.all redirect_to categories_path, :notice => 'Category was successfully created.' # send out email #NotifyMailer.new_prod_email(@product).deliver else render :action => "new" end end end def edit @category = Category.find(params[:id]) end def update @category = Category.find(params[:id]) #@category.reload. caused nil.reload error if @category.update_attributes(params[:category], :as => :roles_update) #@category = Category.find(params[:id]) redirect_to categories_path, :notice => 'Category was successfully updated' else @categories = Category.all render 'index' end end def show @category = Category.find[params[:id]] end end A: A 'Back' link that satisfies most Rails applications' needs is to use the link_to helper: <%= link_to "Back", :back %> The :back Symbol option is even noted in the Rails API docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Storing data in arrays I have a data file that contains the following information for radius, density, acceleration, and pressure: 1.464e+22 1.403e-25 1.290e-08 6.325-10 1.539e+22 1.394e-25 1.680e-08 6.309-10 1.616e+22 1.384e-25 2.030e-08 6.289e-10 1.693e+22 1.373e-25 2.344e-08 6.266e-10 1.769e+22 1.362e-25 2.628e-08 6.239e-10 How can I store this data in arrays (e.g., radius[], density[])? The code to read the data file is as follows: #include"stdio.h" #define NDATA 5 int main() { FILE *fo; int i; float r[NDATA]; float rho[NDATA]; float g[NDATA]; float p[NDATA]; fo = fopen("data.txt", "r"); /* Read data */ for (i = 0; i<NDATA; i++) { fscanf(fo, "%f %f %f %f", &r[i], &rho[i], &g[i], &p[i]); printf(" read line %d %e %e %e %e\n", i, r[i], rho[i], g[i], p[i]); } } A: #include"stdio.h" #define NDATA 5 int main() { FILE *fo; int i; float r[NDATA]; float rho[NDATA]; float g[NDATA]; float p[NDATA]; fo = fopen("data.txt", "r"); fscanf(); fscanf(); /* Read data */ for (i = 0; i<NDATA; i++) { fscanf(fo, "%f %f %f %f", &r[i], &rho[i], &g[i], &p[i]); fscanf(fo); printf(" read line %d %e %e %e %e\n", i, r[i], rho[i], g[i], p[i]); } } This should work since you will not be reading in the first two lines and blank lines. A: About the extern: I would try to avoid it. This would of been a comment, but comments are just to limited so a code block follows. It uses a very old C trick to malloc() a structure with variable sized members. This trick gives you a single pointer you can easily pass around to callers. The pointer points to a structure that contains everything in an easy to use format. Best of all it uses just a single malloc() to allocate all arrays, of whatever size is needed. If you ever need to add new members, add them just before the "data" member and you will have fewer chances of bugs if everything is not recompiled as it should be. data.h File #include <stdlib.h> typedef struct data_struct { int ndata; float *r; float *rho; float *g; float *p; float data[1]; } data_t; static struct data_struct *data_malloc( int n ) { data_t *ptr = malloc( sizeof(data_t) + /* base struct size */ n * sizeof(float) - /* actual data */ sizeof(float) ); /* remove extra data[0] */ ptr->ndata = n; /* populate size so users have it */ /* while extending data_struct this way is horrid C++, * it is well used, classic, C, accepted by every compiler */ ptr->r = ptr->data; /* beginning of data array */ ptr->rho = ptr->r + n; /* follows r */ ptr->g = ptr->rho + n; /* follows rho */ ptr->p = ptr->g + n; /* follows g */ return ptr; } static void data_free( struct data_struct *ptr ) { if ( ptr && ptr->ndata ) { /* have data, will free */ ptr->ndata = 0; /* zero the size as fail-safe */ free( ptr ); } return; } Main Program #include #define NDATA 5 int main() { FILE *fo; int i; data_t *ptr = data_malloc( NDATA ); fo = fopen("data.txt", "r"); /* Read data */ for (i = 0; i < NDATA; i++) { fscanf(fo, "%f %f %f %f", ptr->r+i, ptr->rho+i, ptr->g+i, ptr->p+i); printf(" read line %d %e %e %e %e\n", i, ptr->r[i], ptr->rho[i], ptr->g[i], ptr->p[i]); } for (i = 0; i < NDATA; i++) { printf(" read line %d %e %e %e %e\n", i, ptr->r[i], ptr->rho[i], ptr->g[i], ptr->p[i]); } some_function(ptr); /* pass the pointer down as a single pointer */ data_free(ptr); /* always good to free anything you malloc */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BitmapFactory.decodeFileDescriptor returning null with a valid file descriptor I've got a problem where BitmapFactory.decodeFileDescriptor is returning a null bitmap. The file descriptor provided is coming from: AssetManager.openFd("test.png").getFileDescriptor(); The paths are correct, the file exists,no exceptions are being thrown, and FileDescriptor.Valid() returns true. Other code samples that I've looked at do not seem to have this problem. This has me stumped, I don't know how I should proceed from here. Any ideas? A: I had the same problem. First,I put FileInputStream.getFD and BitmapFactory.decodeFileDescriptor in different threads,it returns null. PhotoDecodeTask task = new PhotoDecodeTask(); task.execute(new FileInputStream(filePath).getFD()); private class PhotoDecodeTask extends AsyncTask<FileDescriptor,Integer,Bitmap>{ @Override protected Bitmap doInBackground(FileDescriptor... params) { ... return BitmapFactory.decodeFileDescriptor(params[0],null, opts); } } I try to put them in the same thread,i works.But i don't know why. PhotoDecodeTask task = new PhotoDecodeTask(); task.execute(filePath); private class PhotoDecodeTask extends AsyncTask<String,Integer,Bitmap>{ @Override protected Bitmap doInBackground(String... params) { ... FileDescriptor fd = new FileInputStream(params[0]); return BitmapFactory.decodeFileDescriptor(fd,null, opts); } } A: I had the same problem. I had to change my code as follows: InputStream imgFile = context.getAssets().open(imagePath); BitmapFactory.decodeStream(imgFile); So instead of using BitmapFactory.decodeFileDescriptor, I used decodeStream. A: I have encountered such issue recently. After some search, finally this works for me: FileDescriptor fd = AssetManager.openFd("test.png").createInputStream().getFD(); As a side note, this only works for my new phone (Android 5.0+), but still returns null from decodeFileDescriptor for old phone (Android 4.1.2).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }