text
stringlengths
8
267k
meta
dict
Q: What if I want to dispatch MouseEvent.MOUSE_UP when un-clicking only some objects, not all of them? What if I want to dispatch MouseEvent.MOUSE_UP when un-clicking only some objects, not all of them? I mean, when I add eventListener that listens for MOUSE_UP, it's dispatched (thought with different targets) every time I un-click anywhere, if you understand what I mean. How can I "fix" it? A: I suppose you listen for MOUSE_UP events on the stage, or some other container that holds a lot of different objects that can be clicked. If you want to get only some of those Events, listen only to those objects specifically, so add eventListeners to all of those objects separately. Another option is to check the target of the Event, to find out which object sent the MOUSE_UP Event. And another option is to use mouseEnabled=false on any object you don't want to send MOUSE_UP Events. Post some code and I may post some too...
{ "language": "en", "url": "https://stackoverflow.com/questions/7539345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Anonymous User Log in with ActionMailer and Rails 3 I have seen the RailsCasts video on setting up ActionMailer for Rails 3. However, I have a situation where the mail server (Lotus Notes) I need to use requires an anonymous login (where I do not put in a user name or password). I set up an initializer file, controller, and mailer information settings below. I am not getting any errors when I send the email and I can see the email being created and "sent" from the terminal; however, the email is not being delivered. What am I doing wrong? Initializer File: ActionMailer::Base.smtp_settings = { :address => "smtp.home22.com", :port => 25, :domain => "home22.com", :enable_starttls_auto => true } ActionMailer::Base.default_url_options[:host] = "localhost:3000" Controller: def send_alert() @assessment = Assessment.first AlertMailer.alert_notice(@assessment).deliver respond_to do |format| format.html {redirect_to :action => 'index'} # format.html { render :action => (assessments_url) } format.xml { head :ok } end end Mailer: class AlertMailer < ActionMailer::Base default :from => "Rails Application" def alert_notice(assessment) attachments["alert.csv"] = File.read("#{Rails.root}/public/alert.csv") mail(:to => 'mcmahling@gmail.com', :subject => 'Alert') end end A: There's not really enough information here to know what's really going on. You should check what's been recorded in the log.nsf file on the Domino server, and if that doesn't give you enough information ere are a couple of IBM technotes ( https://www-304.ibm.com/support/docview.wss?uid=swg27003007 https://www-304.ibm.com/support/docview.wss?uid=swg21095102 ) that will help you set up to collect debug data that may help you get further along. A: I found a solution but I'm not entirely sure why it works, but I have a guess. When you set the smtp_settings hash, you replace the existing defaults. This means that any default options you don't include simply don't exist in the hash. If the hash is declared without a default object or block, it should return nil when anyone tries to access a non-present key (As The Docs for Hashes specify). You're not setting the :authentication option, so it should default to nil which is what you want. But, obviously, that's not working so it's not relying on the default value for that hash (or is merging it into another hash with a preset default). This part is the guess: Somewhere, the mailer code is checking for the presence of the key rather then the value it's linked too. Finding it missing, it's using something else as a default. Regardless of whether that's the cause, when was having the same problem, I specifically included :authentication => nil in the smtp_settings hash which resolved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: foreach statement only returning 1 item I'm using sessions to store products viewed, but I'm having a problem printing out all of the items when I query the database. Controller $hello_world = $this->session->all_userdata(); foreach($hello_world as $key=>$product_id) { $query['products'] = $this->Global_products->globalFindProducts($product_id); echo $product_id; // Right here it echos all the items in the session. } Model function globalFindProducts($product_id) { $this->db->join('price','product.modelNumber = price.modelNumber','left')->where('product.modelNumber',$product_id); $this->db->group_by('product.modelNumber'); $query = $this->db->get('by.product'); return $query->result(); } View <?php foreach($products as $product) { ?> <div><?php echo $product->name; ?></div> <?php } ?> In my view I can only see one item, not all of them. Can someone please give me your advice as to how you would approach solving this problem? Thanks in advance A: Try this, I haven't really coded in CodeIgniter, so its a best guess: Controller $hello_world = $this->session->all_userdata(); foreach($hello_world as $key=>$product_id) { $query['products'][] = $this->Global_products->globalFindProducts($product_id); echo $product_id; // Right here it echos all the items in the session. } Note: Here I'm making the $query['products'] an array, so all results from $this->Global_products->globalFindProducts($product_id); are stored A: Where are you sharing your databases results to the view? Normally, you will want to use something like: $data['hello_world'] = $this->session->all_userdata(); Then when calling the view, include that data array: $this->load->view('someview', $data); Thus, inside your view you can run a for loop: <?php foreach($hello_world as $product) { ?> <div><?php echo $product->name; ?></div> <?php } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7539348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to format the date in PHP and SQL? I have a field in one of my tables called "publicationDate" and its data type is date. However, when I make a query that should show today's date, I am having a problem on how to format it. It always shows 0000-00-00. This is my variable: $today = date("F j, Y, g:i a"); This is my query: $query = "INSERT INTO articles (summary, publicationDate) VALUES ('{$content}', '{$today}')"; What am I doing wrong? A: Try this: $today = date("Y-m-d"); // 2011-09-24 Your string returns: $today = date("F j, Y, g:i a"); // September 24, 2011, 6:39 am Edit: To save date and time you can use datetime or timestamp: $today = time(); // timestamp Change your database field to timestamp. or $today = date("Y-m-d H:i:s"); // datetime Change your database field to datetime. To select your data from database you can to this: $result = mysql_query("SELECT date FROM table"); $row = mysql_fetch_array($result); // field is timestamp echo date("F j, Y, g:i a", $row['date']); // or // field is datetime echo date("F j, Y, g:i a", strtotime($row['date'])); More informations here: http://at.php.net/manual/en/function.date.php A: $today = date("Y-m-d"); That is the correct format for inserting into MySQL. A: If the publicationDate column is of type DATE (which it should really be) you need to format the date in one of the formats MySql recognizes, not a human-readable string. Of those, most common are date("Ymd") or date("Y-m-d") if you like hyphens. A: Use this instead $today = date("Y-m-d"); MySQL date only stores the date not the time like YYYY-MM-DD If you want to store the time as well you can use a DATETIME field which is this: YYYY-MM-DD HH:MM:SS or you could store the timestamp as a string. A: The value should be a string, formatted to MySQL's format: Y-m-d.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery 1.6.4 cloning problems in Internet Explorer 7 I am using jQuery v1.6.4. Here is the test case for my problem: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="jquery.js"></script> </head> <body> <div id="container"></div> <div id="clone-tpl">I am a clone template</div> <script type="text/javascript"> $(function(){ var clone = $('#clone-tpl').clone(); clone.attr('id','other'+Math.random()); clone.text('I am a clone'); $('#container').append(clone); alert($('#container').html()); alert($('#clone-tpl').attr('id')); var clone2 = $('#clone-tpl').clone(); clone2.attr('id','other'+Math.random()); clone2.text('I am a clone 2'); $('#container').append(clone2); alert($('#container').html()); alert($('#clone-tpl').attr('id')); }); </script> </body> </html> In Mozilla Firefox and Internet Explorer 9 it works as expected: clones clone-tpl two times, changes id and appends the clones to the container div. The container div stays intact. The alert output log is the following: <div id="other0.7574357943876624">I am a clone</div> clone-tpl <div id="other0.7574357943876624">I am a clone</div><div id="other0.1724491511655708">I am a clone 2</div> clone-tpl But on Internet Explorer 7 it messes things up with the clone2, look what alert says: <DIV id=other0.1851332940530379>I am a clone</DIV> clone-tpl <DIV id=other0.1851332940530379>I am a clone</DIV><DIV id=clone-tpl>I am a clone 2</DIV> other0.6041996510541515 I have no idea, how alert($('#clone-tpl').attr('id')) could suddenly give something else than clone-tpl? After all, if I select element by id attribute clone-tpl, the id attribute MUST be clone-tpl, but it is not! What is wrong? Why does IE7 change id of the cloning source if I create a second clone? By the way, if I revert back to jQuery v1.4.2, IE7 starts cloning normally. Is it a bug in jQuery v1.6.4? Is there any workaround for it? P.S. I really would like to avoid reverting to 1.4.2 because 1.6 has some useful features which help me to overcome some other jQuery bug: http://bugs.jquery.com/ticket/5684?version=10 . A: I had clone issues with IE , too Finally had to write my own simple clone for IE when tired of bugs. It's not universal neither brilliant but in this case it can't be done much, IE sucks. It can be modified according to one's needs. function shimNode(jqObj){ var html = jqObj.html(); var id = jqObj[0].id; var classes = jqObj.attr('class'); var styles = jqObj.attr('style'); var pattern = ['<div id="',id,'" class="',classes,'" style="',styles,'">',html,'</div>'].join(''); return jQuery(pattern); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Annotating templates (ModuleElements) in Acceleo I was wondering if I can easily annotate Acceleo templates and then get these annotations when working with TraceabilityModel. Acceleo is now using an annotation to determine entry points for generation: [comment @main] So I am asking, if I can use this mechanism to annotate my templates for other purposes, for example: [comment @org.project.SimpleStatement] [template public generateSimpleStatement(...)] ... [/template] Then, I could be able to get the annotation programmatically when working with traceability model (probably using the org.eclipse.acceleo.traceability.ModuleElement interface). A: Acceleo's traceability does not support either annotations or comments : we only record traceability information for the actually generated text bits, not for any of the "extra" information (comments of the module, main annotation, metamodels ...). That being answered, and though not possible through the means of an annotation, maybe your use case would be worth an enhancement request? Can you describe what you were expecting to achieve through this? (preferrably through the Eclipse M2T forum since stack overflow does not seem to be appropriate for such discussions ;)). (Note : I am an active developper on Acceleo)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web-browser needs again username and password While a web page -which needs login- is opened in my browser, if I close browser and re-open, I have to write username password again. But, sometimes when I close browser and re-open for the same page, it isn't needed username and password again? Is it about Session, Cookie? If yes, why are there different conditions? What do you think? A: Gokturk Its depend on which they session state management technique are used. basically there are 3 state management can used in asp.net Asp.Net state management i think webpage using Cookies with some Expiry period. if its session then when u close the browser then session will be cleared. (InProc Mode). Cookie will expire for mentioned period, if u able to relogin after browser closed then the cookie is checked for your credentials. for the different condition following the reasons will make point of it * *if u cleared your browser data (sessions, cookies, etc) *u may clicked rememberd password, which would stored in Browser cache. A: So it definitely seems the web site only allows session-based, non-persistant cookies. My guess (as I've seen this on my system as well), the browser is closed, but the process hasn't died off. When you open a "new" browser, it's picking up the existing process with all of the session information still valid. To confirm this, each you close the browser, check Task Manager to ensure iexplore.exe, chrome.exe or firefox.exe are completely missing before starting a new session.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Some Users having issues with App, Resource Loading, I am unable to replicate.. Image/Drawable load I have an App that was working perfectly, then I released an update and now suddenly some users cannot inflate the main view.. it is dying on inflation of the XML on line 28 with a nested exception of Resources$NotFoundException: File From Drawable resource ID #0X10200004 on line 28 of the Binary XML inflate which references @drawable/pl the pl.bmp file is in the res/drawable directory and is not corrupted, so the resource exists. The only thing I can see that seems odd is the R.java file that is generated references this drawable with an id of #0X7F0200009, and there are no files reference id's that start with #0X1.... at all.. so I am not sure how or why these particular users are even getting that ID as the reference for the drawable. There is an #0X7f0200004 in the R.Java drawable class but it is a completely different graphic. This is certainly happening with some folks who have upgraded, and I suspect with some folks who have purchased new. I am unable to replicate this behvior on any device I have access to, or on the emulator, but it is clearly happening for some people. Does anyone have any ideas? Is the upgrade not picking up the right R.java file? How is that even possible? At first I thought it might be a file name collision as earlier releases had p as a bmp and release where this started I changed it to a png, but I made sure to delete pl.bmp before build, and subsequently renamed it to pl, so there is no way even if the old p files both .bmp and .png were somehow on the device it would not possibly collide, but this doesn't seem to be the problem. Any help would be greately appreciated. Thanks in advance. A: Well this amazingly appears to be something related to an OS Drawable reference tied to the android.R.id.empty. Don't ask me why this worked fine, and then suddenly started not working for some users after I change my XML definition, but I have removed the reference to this and am now using my own transparent graphic instead and everything appears to be working fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Actual landscape OpenGL View on iOS I'm porting a C++-based engine from Android to iOS and I have some questions on how landscape mode on iOS devices work. I can successfully start my device on landscape mode but my framebuffer stays on portrait mode no matter how I rotate it (or force its rotation). For instance, I would expect a 960x640 resolution instead of the default 320x480. I've been researching about it and I saw some people doing this but explicitly rotating the scene using OpenGL, which means the actual axis were not in landscape mode, which for me is an ugly workaround. A: Make sure your OpenGL UIView is attached to a UIViewController and not inserted directly into the UIWindow. To do that, create a custom view controller: @interface MyViewController : UIViewController @end @implementation MyViewController - (void)loadView { // Create your EAGL view MyEAGLView *eaglView = [[MyEAGLView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)]; self.view = eaglView; [eaglView release]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; } @end Then add it to your app's window via the AppDelegate: - (void)applicationDidFinishLaunching:(UIApplication *)application { MyViewController *viewController = [[MyViewController alloc] init]; [self.window setRootViewController:viewController]; [viewController release]; [self.window makeKeyAndVisible]; } self.window is just the app's UIWindow, you may have to change that if you store the window somewhere else. After that, the UIViewController takes care of rotations and resizing your view when the device is turned and you can override the layoutSubviews method in your MyEAGLView object to handle resizing the OpenGL context. You may also want to look at Apple's sample code for OpenGL apps since it correctly handles this stuff. A: You can rotate the OpenGL output in the vertex shader as follows: #version 300 es in vec4 position; in mediump vec4 texturecoordinate; in vec4 color; uniform float preferredRotation; out mediump vec2 coordinate; void main() { //const float pi = 4.0 * atan(1.0); //float radians = (( -90.0 ) / 180.0 * pi ); // Preferred rotation of video acquired, for example, by: // AVAssetTrack *videoTrack = [tracks objectAtIndex:0]; // CGAffineTransform preferredTransform = [videoTrack preferredTransform]; // self.glKitView.preferredRotation = -1 * atan2(preferredTransform.b, preferredTransform.a); // Preferred rotation for both portrait and landscape mat4 rotationMatrix = mat4( cos(preferredRotation), -sin(preferredRotation), 0.0, 0.0, sin(preferredRotation), cos(preferredRotation), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); // Mirror vertical (portrait only) mat4 rotationMatrix = mat4( cos(preferredRotation), sin(preferredRotation), 0.0, 0.0, -sin(preferredRotation), cos(preferredRotation), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); // Mirror horizontal (landscape only) mat4 rotationMatrix = mat4( 1.0, 0.0, 0.0, 0.0, 0.0, cos(preferredRotation), -sin(preferredRotation), 0.0, 0.0, sin(preferredRotation), cos(preferredRotation), 0.0, 0.0, 0.0, 0.0, 1.0); // Mirror vertical (landscape only) mat4 rotationMatrix = mat4( cos(preferredRotation), 0.0, sin(preferredRotation), 0.0, 0.0, 1.0, 0.0, 0.0, -sin(preferredRotation), 0.0, cos(preferredRotation), 0.0, 0.0, 0.0, 0.0, 1.0); gl_Position = position * rotationMatrix; coordinate = texturecoordinate.xy; } Obviously, you choose only one matrix4, depending on the orientation of the video, and then its rotation. Each matrix4 flips the video window -- not rotates it. For rotation, you have to first pick the matrix4 based on the orientation, and then substitute the preferredRotation variable with the number of degrees (in radians, the formula for which is also provided). There are a lot of ways to rotate a view, layer, object, etc.; but, if you're rendering an image via OpenGL, then you should choose this method, and only this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript token, category search field like mail A little while ago I came across a Javascript search box that had token input like that in Lions Finder or Mail, where the tokens have a category element that is auto completed as well as the query element. I have spent much of the day so far trying to find it, but I seem to have lost my bookmark and can't find it on Google. Has anyone else used this or know who created it? Hope you can help. Thank you :) A: Found it: http://documentcloud.github.com/visualsearch/ hope it works as well as I hoped
{ "language": "en", "url": "https://stackoverflow.com/questions/7539370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FQL Query not getting a response My javascript solution for pulling in the likes for a set of links on a certain page is no longer working. I can't find anything wrong, and I've tried using the .api() method (below) and the Data.query() method but neither is working. This is the code that I currently have and it's similar to what I was using when it was working. var inlist = [url1, url2, url3..... urln]; FB.api( { method: 'fql.query', query: 'SELECT url, total_count FROM link_stat WHERE url IN('+inlist.substr(0, inlist.length-2)+')' }, function(response) { console.log(response); for( var i = 0 ; i < response.length ; i++ ) { if (response[i]['total_count'] > 0){ $(vids[response[i]['url']]).append("<div class='likes'>"+response[i]['total_count']+"</div>"); } } } ); The console reports nothing, my FB object is initialized correctly (the example queries run with no problem), and the URL's are generated dynamically based on a list of links. Also, it's worth mentioning that I tested the FQL here:http://developers.facebook.com/docs/reference/rest/fql.query/ and it worked fine... A: I'm not sure why you are using substr on an array but this is how I would do it: var inlist = ['www.facebook.com','www.masteringapi.com']; FB.api( { method: 'fql.query', query: 'SELECT url, total_count FROM link_stat WHERE url IN("'+inlist.join('","')+'")' }, function(response) { for( var i = 0 ; i < response.length ; i++ ) { if (response[i]['total_count'] > 0){ console.log(response[i]['url'] + ': ' + response[i]['total_count'] + ' likes'); } } } ); This would return something like: www.facebook.com: 36643537 likes www.masteringapi.com: 26 likes A: Looks like the problem was that I was including too many IN(...) items. Oddly enough though there was no error, just no response. I limited the items in to 10 and everything started working again. for(var i=0 ; i < Math.ceil(inlist.length/10); i++) { FB.api( { method: 'fql.query', query: 'SELECT url, total_count FROM link_stat WHERE url IN('+inlist.slice((10*i), ((i+1)*10)).join(', ')+')' }, function(response){ for( var i = 0 ; i < response.length ; i++ ) { ... } } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7539374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Away 3D tutorials Can anyone recommend some good tutorials for Away3D? In particular to create similar effects to those on their home page. http://away3d.com/ Went to the tutorials page but nothing there... http://away3d.com/tutorials A: These aren't tutorials specifically for the effects you're looking for but these helped me get a better understanding of how to use Away3D when I first started playing with it. http://www.flashmagazine.com/Tutorials/category/away3d/ Unfortunately, I don't recall ever seeing any tutorials specifically for the transition effects you're referencing. A: You would slice up your bitmap into equal squares, and then apply these slices to the front sides of an array of cubes. Then simply tween the cubes with some random depth, and scale factors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: httpErrors errorMode = "Detailed" only for a specific error code I have an asp.net MVC3 application. In my controller I have an ajax action that sets custom response code using Response.StatusCode = 600. I need to pass through the response as is without the IIS trying to look for the custom error page. I tried to use the following code to let IIS not use its custom page for response status of 600. <!-- Pass through Ajax Errors with status code 600 --> <httpErrors errorMode="Detailed" existingResponse="PassThrough"> <error statusCode="600" path="/" /> </httpErrors> <!--End --> The problem with the above snippet is that this applies to all the response codes so even if the Code fails with 500 Internal Server, the response passes through as is without IIS interfering. This exposes my internal Controller and View code to the user (if by chance some exception occurs that I have not handled). So, how do I configure web.config to pass through detailed response only when response.statuscode is 600 (custom) and provide the default IIS custom pages for other errors (for example Internal Server Error 500). A: If you are running in integrated pipeline mode you could try setting the TrySkipIisCustomErrors property to true: Response.StatusCode = 600; Response.TrySkipIisCustomErrors = true; This being said the HTTP specification clearly defines that response HTTP status code are not superior to 5xx. So setting Response.StatusCode = 600; seems like something pretty unusual here. What exactly are you trying to achieve and why the standard HTTP response codes defined in the specification cannot cover your scenario? A: In the web.config I set the custom error section like this: <customErrors mode="On"> <error statusCode="404" redirect="~/Home/NotFound"></error> </customErrors> And then in the controllers, i still set the [HandleError] attribute above my controller. All unhandled exceptions go to the normal Error page in the shared. Any 404 errors go to the NotFound page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Will there be any inconvenience if two objects of different classes add two same-named listeners to the stage? For expample like this: package { class A { public A() { stage.addEventListener(MouseEvent.MOUSE_UP, jump); }}} and package { class B { public B() { stage.addEventListener(MouseEvent.MOUSE_UP, jump); }}} I don't mean exact code, this one may not work, just to clear my question. A: No, because each jump method will be local to the Class instance that added it. Make sure that you include code to remove the event listener when the instance is destroyed, or you'll get a memory leak, since stage always exists. A: You need such methods for both class. package { class A { public function jump(){ trace("this is jump on A"); } public A() { stage.addEventListener(MouseEvent.MOUSE_UP, jump); } } package { class B { public function jump(){ trace("this is jump on B"); } public B() { stage.addEventListener(MouseEvent.MOUSE_UP, jump); } } } Both jump method will be invodek when stage dispatches mouseUp event. if you use somthing like stage.addEventListener(MouseEvent.MOUSE_UP, stage.jump);. This ll me stage jump method called two times. Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I deploy/push only a subdirectory of my git repo to Heroku? I have a project that uses Serve and is version controlled using Git. Serve creates an output folder with static files that I want to deploy to Heroku. I don't want to deploy the Serve project itself since the Heroku Cedar stack doesn't seem too fond of it, but most importantly I want to take advantage of Heroku's great support for static websites. Is there a way to deploy a subfolder to a git remote? Should I create a Git repo in the output folder (that sounds wrong) and push that to Heroku? A: I had a similar issue. In my case it was never a problem to blow away everything in the heroku repository and replace it with whatever is in my subdirectory. If this is your case you can use the following bash script. Just put it in your Rails app directory. #!/bin/bash #change to whichever directory this lives in cd "$( dirname "$0" )" #create new git repository and add everything git init git add . git commit -m"init" git remote add heroku git@heroku.com:young-rain-5086.git #pull heroku but then checkback out our current local master and mark everything as merged git pull heroku master git checkout --ours . git add -u git commit -m"merged" #push back to heroku, open web browser, and remove git repository git push heroku master heroku open rm -fr .git #go back to wherever we started. cd - I'm sure there are plenty of ways to improve upon this - so feel free to tell me how! A: After a long and hard month of trying different things and getting bitten every time I realized, just because Heroku uses a git repository as a deployment mechanism, you should not treat it as a git repository it could have been rsync just as well, they went for git, don't get distracted because of this if you do so, you open up yourself to all kinds of hurt. All of the aforementioned solutions fail miserably somewhere: * *it requires something to be done every time, or periodically, or unexpected things happen (pushing submodules, syncing subtrees, ...) *if you use an engine for example to modularize your code, Bundler will eat you alive, it's impossible to describe the amount of frustration I've had with that project during the quest to find a good solution for this * *you try to add the engine as git repo link + bundle deploy - fail, you need to bundle update every time *you try to add the engine as a :path + bundle deploy - fail, the dev team considers :path option as "you're not using Bundler with this gem option" so it'll not bundle for production *also, every refresh of the engine wants to update your rails stack -_- *only solution I've found is to use the engine as a /vendor symlink in development, and actually copy the files for production The solution The app in question has 4 projects in git root: * *api - depending on the profile will run on 2 different heroku hosts - upload and api *web - the website *web-old - the old website, still in migration *common - the common components extracted in an engine All of the projects have a vendor/common symlink looking at the root of the common engine. When compiling source code for deployment to heroku we need to remove the symlink and rsync it's code to physically be in the vendor folder of each separate host. * *accepts a list of hostnames as arguments *runs a git push in your development repo and then runs a clean git pull in a separate folder, making sure no dirty (uncommited) changes are pushed to the hosts automatically *deploys the hosts in parallel - every heroku git repo is pulled, new code is rsynced into the right places, commited with basic push information in the git commit comment, *in the end, we send a ping with curl to tell the hobby hosts to wake up and tail the logs to see if all went wine *plays nice with jenkins too :D (automatic code push to test servers after successful tests) Works very very nice in the wild with minimal (no?) problems 6 months now Here's the script https://gist.github.com/bbozo/fafa2bbbf8c7b12d923f Update 1 @AdamBuczynski, it's never so straightforward. 1st you will always have a production and test environment at the least - and a bunch of function specific clusters at the worse - suddenly 1 folder needs to map to n heroku projects as a pretty basic requirement and it all needs to be organized somehow so that the script "knows" what source you want to deploy where, 2nd you will want to share code between projects - now comes the sync_common part, the shennanigans with symlinks in development being replaced by actual rsynced code on Heroku because Heroku requires a certain folder structure and bundler and rubygems really really really make things ugly very badly if you want to extract the common threads into a gem 3rd you will want to plug in CI and it will change a bit how subfolders and git repo need to be organized, in the end in the simplest possible use case you end up with the aforementioned gist. In other projects I need to plug in Java builds, when selling software to multiple clients you will need to filter modules that get installed depending on the installation requirements and whatnot, I should really consider exploring bundling things into a Rakefile or something and do everything that way... A: There's an even easier way via git-subtree. Assuming you want to push your folder 'output' as the root to Heroku, you can do: git subtree push --prefix output heroku master It appears currently that git-subtree is being included into git-core, but I don't know if that version of git-core has been released yet. A: I started with what John Berryman put, but actually it can be simpler if you don't care at all about the heroku git history. cd bin git init git add . git commit -m"deploy" git push git@heroku.com:your-project-name.git -f rm -fr .git I guess official git subtree is the best answer, but i had issue getting subtree to work on my mac. A: Alternatively, you can use git subtree to create a heroku branch on GitHub which you can then deploy to Heroku using a Heroku Button: * *Add an app.json to your server directory, as explained here. *Add the following markdown to README.md: [![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy?template=https://github.com/username/repository/tree/heroku) *Push your changes to the heroku branch: git subtree push --prefix server origin heroku
{ "language": "en", "url": "https://stackoverflow.com/questions/7539382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "141" }
Q: what is the best way to bind ViewModel data to master page in asp.net-mvc I want to dynamically create my menu on my master page and i have seen 2 different approaches: * *First approach is have a base controller that loads up all shared view model data in its constructor. This is described here *Second approach is to create a separate controller for this and use this in your master page to inject specific view pieces into the master page without polluting your regular page view generation: @Html.Action("Index", "Settings") Is one better than the other? Is there any best practice here? A: Personally I prefer the second approach as it allows to handle the menu independently from the main logic. By using child actions you could have an entirely separate lifecycle of the menu controller without the need to have a base view model for absolutely all views that use this masterpage. Inheritance just doesn't seem right for this situation but of course this doesn't mean that you should rule it out completely. Every scenario is specific and depending on the exact details (which you haven't provided for yours) there might different approaches. Just don't think that if Html.Action is good for one scenario it will be good for all of them. There might be some project specific constraints which make inappropriate or maybe achieve this by some other approach. There is no universal solution that will work in all situations. Otherwise there wouldn't be a need for programmers :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Last if statement always evaluating to true (overwriting)? I'm trying to display an image based on a change in rank. If the values of the array $rank_change are echoed before my if statements, the correct values are printed, such as: 0, 0, 0, 0, 0, 0, 0, -7, 1, 1, 1, 1, 1, 1, 1 However, if printed after the following if statements, side.gif is always shown: if($rank_change[$i] > 0) { $rank_change[$i] = "<img src=\"up.gif\" width=\"16\" height=\"16\"/>"; } if($rank_change[$i] < 0) { $rank_change[$i] = "<img src=\"down.gif\" width=\"16\" height=\"16\"/>"; } if($rank_change[$i] == 0) { $rank_change[$i] = "<img src=\"side.gif\" width=\"16\" height=\"16\"/>";} In the cases where the value of $rank_change are 7 and 1, why does the last statement still evaluate to true? I realize it would be more efficient to use switch($rank_change[$i]) but, I still don't understand why the final if statement is evaluating true on all values. Any help would be greatly appreciated! A: use an else-if instead of a simple if for the last two conditions. you are actually overwriting the value in $rank_change[$i] in the expression following each test. $rank_change[$i] = "<img src=\"up.gif\" width=\"16\" height=\"16\"/>" will change the value of $rank_change[$i], which will make one of the following test return true as well, resulting in another change of the value of $rank_change[$i]... use an else if construct, and only one test will succeed. A: Adrien is correct, you should use if-else statements. The last condition is evaluating to true because php is doing some type coercion on your values. See http://php.net/manual/en/language.operators.comparison.php (specifically the types comparison table) for more information on when / how it does this. Basically, it's changing 'derp' == 0 to (int)'derp' == 0. (int)'derp' is 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running two queries for each individual thing Sorry about the lame title, but I really don't know how to explain it! Basically, I want to query the game categories from a table, then query games from another table which equal the category of the category queried from the categories table. Got me so far? This is the code I have so far... $get_categories_query = mysql_query(" SELECT * FROM game_categories ORDER BY category_name ASC"); while ($row = mysql_fetch_array($get_categories_query)) { $category_name = $row['category_name']; $get_category_games = mysql_query(" SELECT * FROM games WHERE category = '$category_name' ORDER BY RAND() LIMIT 5"); while ($row = mysql_fetch_array($get_category_games)) { $category_game_id = $row['id']; $category_game_title = $row['game_title']; $category_game_display .= '<li><img class="category_module_img" src="http://www.game.assets.buddyweb.me/' . $category_game_id . '/_thumb_100x100.png"></li>'; } $category_display .= '<div class = "category_module"> <h4>'.$category_name.'</h4> '.$category_game_display.' <div class="play_more_btn">More</div> </div>'; } But what I get from that is every game appearing from the query from the first category in the list. A: I think the problem is the $row variable. Try this: $get_categories_query = mysql_query("SELECT * FROM game_categories ORDER BY category_name ASC"); while($row = mysql_fetch_array($get_categories_query)) { $category_name = $row['category_name']; $get_category_games = mysql_query("SELECT * FROM games WHERE category = '$category_name' ORDER BY RAND() LIMIT 5"); $category_game_display = false; // new!! while($row_cat = mysql_fetch_array($get_category_games)) { $category_game_id = $row_cat['id']; $category_game_title = $row_cat['game_title']; $category_game_display .= '<li><img class = "category_module_img" src = "http://www.game.assets.buddyweb.me/'.$category_game_id.'/_thumb_100x100.png"></li>'; } $category_display .= '<div class = "category_module"><h4>'.$category_name.'</h4>'.$category_game_display.'<div class = "play_more_btn">More</div></div>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery Tooltip and CSS Don't worked tooltip after change in select box $('select[name="tour_name"]').change... and use of id #residence_name, what is causes this problem and how can fix it? Example: http://jsfiddle.net/7Arye/ $('select[name="tour_name"]').change(function () { var val = $(this).attr('value'); $('#residence_name').empty().append('<li id="' + val + '"><a href="" class="tool_tip" title="ok">' + val + '</a><div class="in_tooltip">'+val+'</div></li>'); }); ///// Toltip ////////////////////////////////////////////////////// $('.tool_tip').mouseenter(function () { var tip = $(this).closest('li').find('div').clone(); //alert(tip) $(this).attr('title', ''); $('.tooltip').hide().fadeTo(300, 0.9).children('.tipBody').html(tip); // $('.tooltip', this).stop(true, true).fadeIn('slow'); }).mousemove(function (e) { $('.tooltip').css('top', e.pageY + 10); // mouse follow! $('.tooltip').css('left', e.pageX + 20); }).mouseleave(function () { $('.tooltip').hide(); //$('.tooltip', this).stop(true, true).fadeOut('slow'); }) A: You have to move the event handlers inside the $(..).change function, because .tool_tip doesn't exist yet when you run the code. $('select[name="tour_name"]').change(function () { var val = $(this).attr('value'); $('#residence_name').empty().append('<li id="' + val + '"><a href="" class="tool_tip" title="ok">' + val + '</a><div class="in_tooltip">'+val+'</div></li>'); ///// Tooltip ////////////////////////////////////////////////////// $('.tool_tip').mouseenter(function () { var tip = $(this).closest('li').find('div').clone(); //alert(tip) $(this).attr('title', ''); $('.tooltip').hide().fadeTo(300, 0.9).children('.tipBody').html(tip); // $('.tooltip', this).stop(true, true).fadeIn('slow'); }).mousemove(function (e) { $('.tooltip').css('top', e.pageY + 10); // mouse follow! $('.tooltip').css('left', e.pageX + 20); }).mouseleave(function () { $('.tooltip').hide(); //$('.tooltip', this).stop(true, true).fadeOut('slow'); }) });
{ "language": "ar", "url": "https://stackoverflow.com/questions/7539393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remap Capslock Key in Keymando? Can you remap the CapsLock key in Keymando? CapsLock is listed as an available key but when I try a test like: map "<CapsLock-j>" { alert("CapsLock-j") } ... and hit Reload Config in the Keymando menu, I get an error dialog that says: Error Parsing Keymando Config File undefined method `ctrl' for nil:NilClass Is there perhaps an abbreviation of CapsLock? For example, in the available keys, the Control key is just listed as Control but in the example code it is ctrl. Is there a similar abbreviation for CapsLock? If possible, I would like to use the CapsLock key as a mode key to implement logic like: if <CapsLock> map <j>, <Down> map <k>, <Up> # ...etc end A: Sorry, that's a mistake on our part listing Capslock on the website. Currently it can only be remapped to Control, Option, or Command via the Keyboard.prefPane under "Modifer Keys.." and there's no way for us right now to detect if it's been pressed. We'll keep our eyes open for a solution but as of right now it's not going to do what you're wanting. Sorry. The website has been fixed to avoid any more confusion, as well. A: While you can't remap capslock, you can achieve almost the same functionality by adding some basic state to your keymandorc file. I couldn't figure out how to map something to the option key alone, but apart from that, this should do what you are aiming for: At the top of your keymandorc put: @caps = false Then down wherever you define your bindings put something like the following map "j" do if @caps then send("<Down>") else send("j") end end map "<Option-v>" do @caps = !@caps; alert("Vim Mode: " + @caps.to_s) end You could then also bind escape to exit the mode if @caps is true, and so forth.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: problem in fetching a particular cookie This is the script that i am using to fetch a particular cookie lastvisit : AFTER THE EDIT // This document writes a cookie // called from index.php window.onload = makeLastVisitCookie; function makeLastVisitCookie() { var now = new Date(); var last = new Date(); now.setFullYear(2020); // set the cookie document.cookie = "lastvisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString(); var allCookies = document.cookie.split(";"); for( var i=0 ; i < allCookies.length ; i++ ) { if(allCookies[i].split("=")[0]== "lastvisit") { document.getElementById("last_visit").innerHTML = "You visited this site on" + allCookies[i].split("=")[1]; } else { alert("testing..testing.."); } } } From this script the if part never works though there are 5 cookies stored from my website. (including the cookie that i am saving from this script) What is the mistake that i am making while fetching the cookie named lastvisit ? A: You're splitting the cookie by ; an comparing those tokens with lastvisit. You need to split such a token by = first. allCookies[i] looks like key=val and will never equal lastvisit. Een if allCookies[i] == "lastvisit" is true, the result will still not be as expected since you're showing the value of allCookies[i + 1] which would be this=the_cookie_after_lastvisit. if(allCookies[i].split("=") == "lastvisit") { should be: var pair = allCookies[i].split("=", 2); if (pair[0].replace(/^ +/, "") == "lastvisit") { "You visited this site on" + allCookies[i+1]; should be: "You visited this site on" + pair[1]; The 2 argument of split makes cookies like sum=1+1=2 be read correctly. When splitting cookies by ;, the key may contain a leading space which much be removed before comparing. (/^ +/ is a regular expression where ^ matches the beginning of a string and + one or more spaces.) Alternatively, compare it directly against a RE for matching the optional spaces as well (* matches zero or more occurences of a space character, $ matches the end of a string): if (/^ *lastvisit$/.test(pair[0])) { I've tested several ways to get a cookie including using regular expressions and the below was the most correct one with best performance: function getCookie(name) { var cookie = "; " + document.cookie + ";"; var search = "; " + encodeURIComponent(name) + "="; var value_start = cookie.indexOf(search); if (value_start == -1) return ""; value_start += search.length; var value_end = cookie.indexOf(';', value_start); return decodeURIComponent(cookie.substring(value_start, value_end)) } A: You need to remove possible white space around the cookie key before comparing to the string "lastvisit". This is done conveniently using regular expressions. /^\s+/ matches all white space at the beginning, /\s+$/ matches all white space at the end. The matches are replaced by the empty string, i.e. removed: for( var i = 0 ; i < allCookies.length ; i++ ) { var c = allCookies[i].split("="); // split only once var key = c[0].replace(/^\s+/, '').replace (/\s+$/, ''); // remove blanks around key if (key == "lastvisit") { document.getElementById("last_visit").innerHTML = "You visited on " + c[1]; } //... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How i get the button clicked time with Jquery? I would like to show my customer's the average registration time in seconds on the registration page. The average time will be based on last 15 registrations by using the cookies. Here is sample text that i want use on my registration page: Registration will take about 3.1 seconds. The is the average of last 15 registrations. Any suggestions? A: Are you sure? Cookies are placed on the customers computers and you will not be able to gether last 15 registrations to provide such statistics to the user. You need to check the time in scope of one session from the loading registration page by GET request till the posting the registrations data using the POST request. And it's need to be done on the server side. Something like this: public partial class _Default : System.Web.UI.Page { private static DateTime registrationStart; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { registrationStart = DateTime.Now; } } protected void Register_Click(object sender, EventArgs e) { TimeSpan registrationTimeSpan = DateTime.Now - registrationStart; this.StoreRegistrationTime(registrationTimeSpan); // store registration date to DB } } A: Keeping track of the time on the client side will be more accurate than keeping track of time on the server side for the mere fact that keeping track of time on the server side does not account for bandwidth latency or load times. If a user has a slow connection, a mobile connection or is accessing the site from another country this could seriously affect the outcome of timing if strictly kept track of on the server side. In the click event for the button just set the time of the click as . . . $('button.register').click(function(evt) { window.myApp.startTime = new Date().getTime(); //Milliseconds since midnight Jan 1, 1970 }); If you are submitting your user input to register via ajax on the success of the call you can set another time (window.myApp.endTime) as with the click event then find the difference of the 2 times in Milliseconds to get the precision you are looking for. window.myApp.registrationTime = window.myApp.endTime - window.myApp.startTime window.myApp.registrationTime would need to be sent back to the server, as mentioned only the server will be able to keep track of the last 15 registrations in the way you want. A: As has already been mentioned, you can't really use cookies as they are stored on the user's machine, not the server. What you could do is get the time when the ready event fires, and then get the time when the form is submitted: $(document).ready(function() { var startTime = (new Date()).getTime(); $("#yourForm").submit(function() { var endTime = (new Date()).getTime(), totalTime = endTime - startTime; }); }); You could then store the time taken in a hidden input and submit it along with your form. Store the time in the database along with the user registration data, and simply query the database for the average of the last 15 registrations to get the data you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GUI layout using Tk Grid Geometry Manager Building a small application for personal use with Python and thought I'd try my hand with a little GUI programming using Tkinter. This is the GUI I've created so far: Application doubts: How can I make sure that the three LableFrames - A, B and C in the screenshot - have the same width? (Or rather, have the width equal to the widest of the three? For example, in the screenshot, A is the widest and I'd like B and C to also be as wide - up to the line D). (It doesn't have to dynamically calculated - it is enough if I can ensure that the width are the same when I code it, the first time round. They don't need to change on runtime.) Tk Grid Geometry Manager doubts: * *When you use frames, is the grid (row, column) specific to only the size of the frame or is it calculated based on the size of the form (root window)? *How is the size of a column determined in a grid? *I haven't fully understood what 'weight' does within a grid. When should it be used? The Python GUI Code: import Tkinter if __name__ == '__main__': form = Tkinter.Tk() getFld = Tkinter.IntVar() form.wm_title('File Parser') stepOne = Tkinter.LabelFrame(form, text=" 1. Enter File Details: ") stepOne.grid(row=0, columnspan=7, sticky='W', \ padx=5, pady=5, ipadx=5, ipady=5) helpLf = Tkinter.LabelFrame(form, text=" Quick Help ") helpLf.grid(row=0, column=9, columnspan=2, rowspan=8, \ sticky='NS', padx=5, pady=5) helpLbl = Tkinter.Label(helpLf, text="Help will come - ask for it.") helpLbl.grid(row=0) stepTwo = Tkinter.LabelFrame(form, text=" 2. Enter Table Details: ") stepTwo.grid(row=2, columnspan=7, sticky='W', \ padx=5, pady=5, ipadx=5, ipady=5) stepThree = Tkinter.LabelFrame(form, text=" 3. Configure: ") stepThree.grid(row=3, columnspan=7, sticky='W', \ padx=5, pady=5, ipadx=5, ipady=5) inFileLbl = Tkinter.Label(stepOne, text="Select the File:") inFileLbl.grid(row=0, column=0, sticky='E', padx=5, pady=2) inFileTxt = Tkinter.Entry(stepOne) inFileTxt.grid(row=0, column=1, columnspan=7, sticky="WE", pady=3) inFileBtn = Tkinter.Button(stepOne, text="Browse ...") inFileBtn.grid(row=0, column=8, sticky='W', padx=5, pady=2) outFileLbl = Tkinter.Label(stepOne, text="Save File to:") outFileLbl.grid(row=1, column=0, sticky='E', padx=5, pady=2) outFileTxt = Tkinter.Entry(stepOne) outFileTxt.grid(row=1, column=1, columnspan=7, sticky="WE", pady=2) outFileBtn = Tkinter.Button(stepOne, text="Browse ...") outFileBtn.grid(row=1, column=8, sticky='W', padx=5, pady=2) inEncLbl = Tkinter.Label(stepOne, text="Input File Encoding:") inEncLbl.grid(row=2, column=0, sticky='E', padx=5, pady=2) inEncTxt = Tkinter.Entry(stepOne) inEncTxt.grid(row=2, column=1, sticky='E', pady=2) outEncLbl = Tkinter.Label(stepOne, text="Output File Encoding:") outEncLbl.grid(row=2, column=5, padx=5, pady=2) outEncTxt = Tkinter.Entry(stepOne) outEncTxt.grid(row=2, column=7, pady=2) outTblLbl = Tkinter.Label(stepTwo, \ text="Enter the name of the table to be used in the statements:") outTblLbl.grid(row=3, column=0, sticky='W', padx=5, pady=2) outTblTxt = Tkinter.Entry(stepTwo) outTblTxt.grid(row=3, column=1, columnspan=3, pady=2, sticky='WE') fldLbl = Tkinter.Label(stepTwo, \ text="Enter the field (column) names of the table:") fldLbl.grid(row=4, column=0, padx=5, pady=2, sticky='W') getFldChk = Tkinter.Checkbutton(stepTwo, \ text="Get fields automatically from input file",\ onvalue=1, offvalue=0) getFldChk.grid(row=4, column=1, columnspan=3, pady=2, sticky='WE') fldRowTxt = Tkinter.Entry(stepTwo) fldRowTxt.grid(row=5, columnspan=5, padx=5, pady=2, sticky='WE') transChk = Tkinter.Checkbutton(stepThree, \ text="Enable Transaction", onvalue=1, offvalue=0) transChk.grid(row=6, sticky='W', padx=5, pady=2) transRwLbl = Tkinter.Label(stepThree, \ text=" => Specify number of rows per transaction:") transRwLbl.grid(row=6, column=2, columnspan=2, \ sticky='W', padx=5, pady=2) transRwTxt = Tkinter.Entry(stepThree) transRwTxt.grid(row=6, column=4, sticky='WE') form.mainloop() (Note: For Python 2.4.3) A: If you use the same columnspan and use sticky='WE' on all three LabelFrames then they should have the same width. For example, you want to use stepTwo = Tkinter.LabelFrame(form, text=" 2. Enter Table Details: ") stepTwo.grid(row=2, columnspan=7, sticky='WE', \ padx=5, pady=5, ipadx=5, ipady=5) Questions 1) When you use frames, is the grid (row, column) specific to only the size of the frame or is it calculated based on the size of the form (root window)? There is an interdependence here. The preferred size of the form will depend on the preferred sizes of the children and the layout, but the actual sizes of the children will depend on the actual size of the form and the layout. Layout is done from the children to the root to determine the preferred sizes, and then when it gets to the root, the preferred size is used as the actual size (unless overridden). Layout then goes back down assigning actual sizes. 2) How is the size of a column determined in a grid? The preferred size of a column is determined based to be the minimum preferred width of all the items in that row. The actual size of the column is determined by the preferred size plus some percentage of the extra space of the parent widget. 3) I haven't fully understood what 'weight' does within a grid. When should it be used? The weight determines the percentage of extra space that I mentioned above. The amount of the extra space given to the column is column_weight/total_weight.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Redirecting non www to www in CakePHP using app/webroot Gurus of So I am trying to redirect any user that comes to http://domain.com to http://www.domain.com. I have found a bunch of different ways to do that on SO, but I need to make them fit the dynamic app config from CakePHP. Currently, this is what my .htaccess reads: <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ app/webroot [L] RewriteRule (.*) app/webroot [L] </IfModule> I am running Ubuntu 10.04 on a Slicehost slice. Any help is super appreciated. Thank you. UPDATE - SOLUTION - Thanks to Rob Wilkerson <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.myapp\.com [NC] RewriteRule ^(.*)$ http://www.myapp.com/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ app/webroot/$1 [QSA,L] </IfModule> A: From one of my own apps: <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.myapp\.com [NC] RewriteRule ^(.*)$ http://www.myapp.com/$1 [R=301,L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php?url=$1 [QSA,L] </IfModule>
{ "language": "en", "url": "https://stackoverflow.com/questions/7539402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Images in html inside div don't appear below each other (please see the pic)? Why images appear in such manner , .. ? <div id='container'> <div class='imgContainer'> <div class='myLocation'> <img src='https://graph.facebook.com/1055505/picture' style='width:30px'> Tova Schherr </div> </div> <div class='imgContainer'> <div class='myLocation'> <img src='https://graph.facebook.com/1205050/picture' style='width:30px'> Alison Carmel </div> </div> ..... .. ...... </div> you must know that the data are sample to show the example, so it will not work. here is CSS class for myLocation .myLocation { margin-bottom:1px; width:100%; background-color:#F7F7F7; color:#006699; padding:7px; padding-right:12px; } A: Maybe, your doctype require to close the image tag. <img src="" /> A: Try to use fixed height on .imgContainer .imgContainer { height:80px; vertical-align:middle; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7539406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: phonegap with codeigniter backend So I am getting better at using phonegap but am still trying to fully add codeigniter as the backend. I have been able to .load in jquery something from a controller of my CI to my phonegap android app but can't seem to submit anything TO the server properly. Do you need a rest server to communicate with CI from phonegap? I was planning on using ajax post to info to CI but so far unable to get it to work. I'd really appreciate it someone can help me over this hurdle. Thanks link to relative answer Controller: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Welcome extends CI_Controller { public function index() { //$this->load->view('welcome_message'); $data['query']=$this->site_model->get_last_ten_articles(); $this->load->view('partial1',$data); } public function addarticle(){ $headline=$this->input->post('headline'); $article=$this->input->post('article'); $this->site_model->insert_entry($headline,$article); } } Javascript(on phonegap device) function add_article(){ $.ajax({ type: 'POST', url: 'http://testlab.site40.net/droiddev/welcome/addarticle/', data: {"headline": "test headline","article": "test article"} error: function(){alert('fail');}, success: function(data){ alert('article added'); }, dataType: "json" }); } A: First of all, lets get your example running, your post data is json, and the datatype is json but your CI implementation is accessing post variables. The quick and dirty fix is to submit a uri string in the post data such as: &headline=test%20headline&article=test%20article This can be generated from a form with the jquery serialize function: var myData = $('#form-id').serialize(); This post data will be set in the $_POST var on submission and then later accessible through the CI post function: $this->input->post() *Note: remeber to remove the dataType setting in the ajax call for this to work. For a more politically correct way to solve this problem, you're going to want to leave your javascript alone (thats all good) but you need to set the CI backend up as a RESTful service, the default installed controller and input classes won't handle it. You need to use something like Phil Sturgeon's REST implementation: * *There is a github project for the code, *A blog post (read this first - its a good short primer on REST servers for CI concerned usage), *And the tutorial you already know about. *Oh and a video on setting it up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using sub-domains with Google Analytics I have added Google Analytics to my primary domain and added the script to the head section of each page. I have done similarly with a sub-domain. Both the primary domain and the sub-domain are showing under the primary domain statistics. I have used the multi-domain script in each head section. I have created a filter by following the Google instructions, but the filtered profile doesn't show anything at all. How can I get statistics for each domain & sub-domain separately? A: very simple, just create separate profile for each sub-domain and add profile specific code into all the pages of respective sub-domain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Plot Variable Frequency using ggplot2 I'd like to plot a bar graph showing frequency of a string in ggplot. The input file (t1. txt) looks like: do 4 re 2 mi 5 and my current r script is: library("ggplot2") t1<-read.table("t1.txt",header=FALSE,sep='\t') ggplot(t1,aes(V1))+geom_bar() However this isn't what I'd like - it has a correct x axis, but the y axis should show the variable from the second column (V2). Can anyone help? Thanks. A: All you need to do is put the actual V2 in the command then. The default first two items to aes are x and y. You've only given x. ggplot(t1,aes(V1,V2))+geom_bar()
{ "language": "en", "url": "https://stackoverflow.com/questions/7539431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Content positioning into a UIScrollView I'm trying to add a scroll view to an existing screen of my app to help scroll the screen upward when keyboard hides a text field into this view. I have added the scroll view as a subview of the main view in Interface Builder. Then I added all other objects as subviews to this scrollview. I have set the scroll view size to 320x460 with x=0 and y=0. Now, I notice the layout is broken and all objects (labels,text fields overlap in the same place). Do you know the proper way to position this scrollview in interface builder so that I can easily position the other objects? Thx for helping, Stephane A: What you did is correct. It sounds like you moved the other UI elements into the scroll view after you positioned them. In this case they would default to the center position and be overlapped. If you find it difficult to use dragging in Xcode's Interface Builder, try the position and size tab and type in the coordinates. Alternatively, reposition your UI elements in code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do i tell my uitableviewcontroller to reloadData in a asynch socket I'm using cocoaAsyncSocket when i click on a button in my tableViewController to fetch the dat I want in the function didReadData to call reloadData of my tableView. how should get the reference of my tableView ? please tell me, if i should use appDelegate, singletons or simply send it as a parameter. or if my design all together is wrong. Thanks A: I would consider having your socket class send a NSNotification which the table view controller listens to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spark View Engine site works for about 30 minutes then gets a "Dynamic view compilation failed." error First off, this may be a duplicate of "http://stackoverflow.com/questions/3892891/spark-views-work-initially-but-then-get-a-dynamic-view-compilation-failed-erro" but the answer to that question has not solved my issue. My issue is the same with the linked question but the answer in question is not working. I was wondering if anyone has come across another solution that works for them that is not the same as the previous questions answer. This is the error that is displayed: Dynamic view compilation failed. (0,0): error CS0518: Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported c:\Code\XXXX\src\XXXX.Web\Views\Shared\application.spark(27,18): error CS1969: One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll? c:\Code\XXXX\src\XXXX.Web\Views\Shared\application.spark(27,45): error CS1969: One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?
{ "language": "en", "url": "https://stackoverflow.com/questions/7539438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select ten recent review comments from ten different users I have two database tables, Users and Review. The User table has a reference key to the Review table. User table ---------- userid name password email Review Table ------------ reviewid userid comment datetime I am using mysql database I want to query 10 recent user review comments without repeating the same user in case where are user have 4 most recent reviews. So in effect the 10 result will be from different users. How do I do this? A: Try SELECT *, COUNT(*) reviews_no FROM review GROUP BY userid HAVING reviews_no > 4 ORDER BY datetime DESC LIMIT 10
{ "language": "en", "url": "https://stackoverflow.com/questions/7539445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP File Get Contents getting PHP? I'm using PHP's file_get_contents in a way that makes it an API without XML. I've done this several times before, but today, it's outputting the file's ACTUAL PHP as opposed to the output HTML which is what I'm trying to get! Here's the code: File I'm getting, udp.php <?php session_start(); $user = $_SESSION['xxxxxx']; require("connect.php"); $data = mysql_query("SELECT * FROM xxx WHERE xxx='$xx'"); $row = mysql_fetch_assoc($data); /* Fetch Array */ $email = $row['email']; $name = $row['firstname'].' '.$row['lastname']; $location = $row['location']; $dob = $row['dob']; $gender = $row['gender']; $dp = $row['dp']; $joindate = $row['joindate']; $var = $email.'@@@@'.$name.'@@@@'.$location.'@@@@'.$dob.'@@@@'.$gender.'@@@@'.$dp.'@@@@'.$joindate; echo $var; ?> And I'm using this: <? $getdata = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/udp.php'); echo $getdata; ?> To get the file contents from udp.php, but the problem is, I'm not getting $var, I'm getting the ACTUAL PHP! The return data is the exact PHP file contents. The actual udp.php file renders $var the way I want it to, but when getting the file, it renders the exact PHP. That is kind of confusing to me :S Any Ideas? Thanks! :) A: $_SERVER['DOCUMENT_ROOT'] contains a local filesystem path. The PHP interpreter is never being invoked, so you just get the file contents. You either need to file_get_contents() it via a URL, or capture the output from include() with some buffering and store the value that way. A: Use include() to get the interpreted PHP file. A: That is how it's supposed to work. If you did file_get_contents on an executable file, would you expect it to execute the file and return the output? Not really. If you want to process the PHP file and get the resulting output, use include instead. A: Honestly, I think you need to read up on programming in general, and PHP specifically. What you can do to fix what you posted is to create a function in udp.php by wrapping the code in a function named something like udp_getdata() {} and then return $var; instead of echo. Then in the other code, you require_once("udp.php"); and then change: $getdata=udp_getdata(); At this point, $get_data should be set to the contents of the return value of the function udp_getdata() That is not to say that all your code is correct, and will work, mind you. I never got that far.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploy Haskell code that uses the Snap Framework What's your experience with deploying Haskell code for production in Snap in a stable fashion? If the compilation fails on the server then I would like to abort the deployment and if it succeeds then I would like it to turn of the snap-server and start the new version instead. I know there are plenty of ways. Everything from rsync to git-hooks (git pull was a nightmare). But I would like to hear your experiences. A: Where I work, we use Happstack and deploy on Ubuntu linux. We actually debianize the web app and all the dependencies, and then build them in the autobuilder. To actually install on the server, we just run apt-get update && apt-get install webapp-production The advantage of this system is that it makes it easy for all developers to develop against the same version of the dependencies. And you know that all the source code is checked in properly and can be rebuilt anywhere .. not just on one particular machine. Additionally, it provides a mechanism to make patches to libraries from hackage when needed. The downside is that apt-get and cabal-install do not get along well. You either have to build everything via apt-get or do everything via cabal-install. A: Here's what we do. First off, our servers are all the same version of ubuntu, as well as our development machines. We write code, test, etc. in whatever os we care to use and when we're ready to push we build on the devel machine(s). As long as that compiled cleanly, we stop (number of frontend servers)/2, rsync the resources directory and a new copy of the binary, and then use scripts start it back up. Then repeat for the other half. In my opinion, I think you should question the logic of maintaining a full toolchain on your frontend server(s) when you can easily transfer just the binary and static assets - provided that the external libraries (database, image, etc) versions match the build environment. Heck, you could just use a virtualbox instance to do the final compile, again, so long as the release of the os and libraries match.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle 11g: Index not used in "select distinct"-query My question concerns Oracle 11g and the use of indexes in SQL queries. In my database, there is a table that is structured as followed: Table tab ( rowid NUMBER(11), unique_id_string VARCHAR2(2000), year NUMBER(4), dynamic_col_1 NUMBER(11), dynamic_col_1_text NVARCHAR2(2000) ) TABLESPACE tabspace_data; I have created two indexes: CREATE INDEX Index_dyn_col1 ON tab (dynamic_col_1, dynamic_col_1_text) TABLESPACE tabspace_index; CREATE INDEX Index_unique_id_year ON tab (unique_id_string, year) TABLESPACE tabspace_index; The table contains around 1 to 2 million records. I extract the data from it by executing the following SQL command: SELECT distinct "sub_select"."dynamic_col_1" "AS_dynamic_col_1","sub_select"."dynamic_col_1_text" "AS_dynamic_col_1_text" FROM ( SELECT "tab".* FROM "tab" where "tab".year = 2011 ) "sub_select" Unfortunately, the query needs around 1 hour to execute, although I created the both indexes described above. The explain plan shows that Oracle uses a "Table Full Access", i.e. a full table scan. Why is the index not used? As an experiment, I tested the following SQL command: SELECT DISTINCT "dynamic_col_1" "AS_dynamic_col_1", "dynamic_col_1_text" "AS_dynamic_col_1_text" FROM "tab" Even in this case, the index is not used and a full table scan is performed. In my real database, the table contains more indexed columns like "dynamic_col_1" and "dynamic_col_1_text". The whole index file has a size of about 50 GB. A few more informations: * *The database is Oracle 11g installed on my local computer. *I use Windows 7 Enterprise 64bit. *The whole index is split over 3 dbf files with about 50GB size. I would really be glad, if someone could tell me how to make Oracle use the index in the first query. Because the first query is used by another program to extract the data from the database, it can hardly be changed. So it would be good to tweak the table instead. Thanks in advance. [01.10.2011: UPDATE] I think I've found the solution for the problem. Both columns dynamic_col_1 and dynamic_col_1_text are nullable. After altering the table to prohibit "NULL"-values in both columns and adding a new index solely for the column year, Oracle performs a Fast Index Scan. The advantage is that the query takes now about 5 seconds to execute and not 1 hour as before. A: Are you sure that an index access would be faster than a full table scan? As a very rough estimate, full table scans are 20 times faster than reading an index. If tab has more than 5% of the data in 2011 it's not surprising that Oracle would use a full table scan. And as @Dan and @Ollie mentioned, with year as the second column this will make the index even slower. If the index really is faster, than the issue is probably bad statistics. There are hundreds of ways the statistics could be bad. Very briefly, here's what I'd look at first: * *Run an explain plan with and without and index hint. Are the cardinalities off by 10x or more? Are the times off by 10x or more? *If the cardinality is off, make sure there are up to date stats on the table and index and you're using a reasonable ESTIMATE_PERCENT (DBMS_STATS.AUTO_SAMPLE_SIZE is almost always the best for 11g). *If the time is off, check your workload statistics. *Are you using parallelism? Oracle always assumes a near linear improvement for parallelism, but on a desktop with one hard drive you probably won't see any improvement at all. Also, this isn't really relevant to your problem, but you may want to avoid using quoted identifiers. Once you use them you have to use them everywhere, and it generally makes your tables and queries painful to work with. A: Your index should be: CREATE INDEX Index_year ON tab (year) TABLESPACE tabspace_index; Also, your query could just be: SELECT DISTINCT dynamic_col_1 "AS_dynamic_col_1", dynamic_col_1_text "AS_dynamic_col_1_text" FROM tab WHERE year = 2011; If your index was created solely for this query though, you could create it including the two fetched columns as well, then the optimiser would not have to go to the table for the query data, it could retrieve it directly from the index making your query more efficient again. Hope it helps... A: I don't have an Oracle instance on hand so this is somewhat guesswork, but my inclination is to say it's because you have the compound index in the wrong order. If you had year as the first column in the index it might use it. A: I don't know if it's relevant, but I tested the following query: SELECT DISTINCT "dynamic_col_1" "AS_dynamic_col_1", "dynamic_col_1_text" "AS_dynamic_col_1_text" FROM "tab" WHERE "dynamic_col_1" = 123 AND "dynamic_col_1_text" = 'abc' The explain plan for that query show that Oracle uses an index scan in this scenario. The columns dynamic_col_1 and dynamic_col_1_text are nullable. Does this have an effect on the usage of the index? 01.10.2011: UPDATE] I think I've found the solution for the problem. Both columns dynamic_col_1 and dynamic_col_1_text are nullable. After altering the table to prohibit "NULL"-values in both columns and adding a new index solely for the column year, Oracle performs a Fast Index Scan. The advantage is that the query takes now about 5 seconds to execute and not 1 hour as before. A: Your second test query: SELECT DISTINCT "dynamic_col_1" "AS_dynamic_col_1", "dynamic_col_1_text" "AS_dynamic_col_1_text" FROM "tab" would not use the index because you have no WHERE clause, so you're asking Oracle to read every row in the table. In that situation the full table scan is the faster access method. Also, as other posters have mentioned, your index on YEAR has it in the second column. Oracle can use this index by performing a skip scan, but there is a performance hit for doing so, and depending on the size of your table Oracle may just decide to use the FTS again. A: Try this: 1) Create an index on year field (see Ollie answer). 2) And then use this query: SELECT DISTINCT dynamic_col_1 ,dynamic_col_1_text FROM tab WHERE ID (SELECT ID FROM tab WHERE year=2011) or SELECT DISTINCT dynamic_col_1 ,dynamic_col_1_text FROM tab WHERE ID (SELECT ID FROM tab WHERE year=2011) GROUP BY dynamic_col_1, dynamic_col_1_text Maybe it will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Use jQuery to position element relative to another that is not the parent If you look here: http://dev.driz.co.uk/tips/ You will see I am experimenting with some Facebook ripoff tooltips. What I'm trying to learn is how to position the tip relative to another object. So for example if a user hovered the red box it would show the relevant tooltip but in relation to the object with the arrow pointing at the redbox. I've thought about using the outerWidth and height or even the position() method. but not sure how I would use it. Also need to position the arrow in relation as well such as where on the box and move it up and down if the user scrolls the page ie. moves the element. If someone can provide some examples that'd be awesome. NOTE I'm not trying to do the hover bit at the moment just trying to get the tip to position itself in relation to the other object. Can anyone help? Thanks A: var top = $("#link").offset().top; top += $("#link").height(); var left = $("#link").offset().left; $("#tip").css({ top: top+"px", left: left + "px" }); This code positions #tip relative to the #link. It's very likely that you want to show #tip below #link, hence top += $("#link").height();.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WiFi only version iPad app? I have an iPad that worked perfectly with my iPads with WiFi only environment. But It was rejected due to one of the function that I suspected that the cellular network has something to do with it. Currently, without the necessary resources to test in that environment, I want to target this app only for WiFi version of iPad. Does anyone know if we can submit a WiFi only version app for iPad? A: Of course it's not possible, and it's not really reasonable. As a developer you want to have as large userbase as possible, so targeting only wifi iPad version would not serve you at all. Just test it thorougly on different device configurations, fix the bugs and submit again. If you have Mac OS X Lion, you could use Network Link Conditioner Utility for simulating lousy internet connection (3G/Edge). Don't underestimate the importance of testing on the real device though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to sort a list using my own logic (not alphabetically or numerically) I've spent the last 30 mins looking through existing answers for what I think is a common question, but nothing quite hits it for me. Apologies if this is a dupe. I've got a list of objects. List<Journey> journeys; The object has a 'status' property - this is a string. class Journey { public string Name; public string Status; } I want to sort based on this string, however not alphabetically. The status depicts the object's position through a journey, either "Enroute", "Finished", or "Error". When sorted ascending I want them to appear in the following order: "Error", "Enroute", "Finished". (In practice there are more statuses than this so renaming them to fall in alphabetical order isn't an option) Aside from creating a class for 'status' with value and sort order properties, and then sorting based on that, how do I do this? Or is that the best method? A: You can define the you sorting logic inside of custom function which is provided to Comparison delegate: List<Journey> list = new List<Journey>(); list.Sort(new Comparison<Journey>((Journey source, Journey compare) => { // here is my custom compare logic return // -1, 0 or 1 })); A: Just another thought: class Journey { public enum JourneyStatus { Enroute, Finished, Error } public string Name; public JourneyStatus Status; } Used with OrderBy: var journeys = new List<Journey>(); journeys.Add(new Journey() { Name = "Test1", Status = Journey.JourneyStatus.Enroute }); journeys.Add(new Journey() { Name = "Test2", Status = Journey.JourneyStatus.Error }); journeys.Add(new Journey() { Name = "Test3", Status = Journey.JourneyStatus.Finished }); journeys.Add(new Journey() { Name = "Test4", Status = Journey.JourneyStatus.Enroute }); journeys = journeys.OrderBy(x => x.Status).ToList(); foreach (var j in journeys) Console.WriteLine("{0} : {1}", j.Name, j.Status); Output: Test1 : Enroute Test4 : Enroute Test3 : Finished Test2 : Error Or you might modify the lambda passed to OrderBy to map the value of Status string to an int. In some situations you might want to implement IComparer<T>, like Jon said. It can help keeping the sorting logic and the class definition itself in one place. A: You need to create a class that implements IComparer<Journey> and implement the Compare method accordingly. You don't mention how you are sorting exactly, but pretty much all methods of the BCL that involve sorting have an overload that accepts an IComparer so that you can plug in your logic. A: Aside from creating a class for 'status' with value and sort order properties, and then sorting based on that, how do I do this? As this is some custom order you need creating such a class is a good idea. A: Derive from Comparer<T> or StringComparer class, implement class with your custom logic, pass instance of this class to sort method. A: One way to do this is to assign an order number to each item. So create a database table to hold your items and their order: Column Name, Column Order Enrout , 0 Finished, 1 Error, 2 Then when I populate a drop down I can sort by the Order in my SQL select rather than the name. Or if you don't want to use a database, you could change Status to include the order and then just parse out the Status name: so Status values might look like this: "0,Enrout","1,Finished","2,Error" then it will naturally sort. Then just use split to separate the order from the name: string[] statusArr = status.split(','); string order = statusArr[0]; string statusname = statusArr[1]; There's a lot of ways to skin this cat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS NSDateformatter issue - dateFromString does not work properly as expected The following snippet will give an unexpected output: Snippet: NSString* testDateStr = [[NSString alloc] initWithString:@"2010-04-04 19:11:11"]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSLog(@"'%@'", testDateStr); NSLog(@"'%@'", [dateFormatter dateFromString:testDateStr]); Output: '2010-04-04 19:11:11' '2010-04-04 09:11:11 +0000' Notice the time hour in date produced is wrong. Is there anything I am doing wrong here? A: NSDateFormatter defaults to the local timezone. When you print the description of the NSDate object, it prints in GMT (notice the +0000 at the end). This code is working exactly as expected. (19:11:11 in your local timezone is the same as 09:11:11 in GMT.) You can always override the timezone of the NSDateFormatter by calling setTimeZone:. A: The output is not wrong: It looks like you are running in a locale with a GMT + 10 timezone. 19:11:11 in your local timezone is equivalent to 09:11:11 GMT (+0000)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add current slide body class on slide change I'm using slidesjs to create a slideshow on my site, this is working fine but I want to add a incremented class to the body tag e.g. slide-1 at load and then when the slide changes slide-2 etc until the slide fully rotates and it goes back to slide-1 My current code is; <script> $(function(){ $('#feature-slideshow').slides({ preload: true, preloadImage: '<?php bloginfo('template_url'); ?>/images/loading.gif', generateNextPrev: false, effect: 'fade', play: 5000, hoverPause: true, animationStart: function() { $("body").addClass("slide"); } }); }); </script> I have two problems; 1) the I want the initial class set before the slideshow has loaded so that the style which is a background is applied when the page is loaded rather than the slideshow 2) How to increment the slide-x class when the slideshow is transitioned/changed. Any help would be greatly appreciated A: Just add the initial class to body directly (<body class="slide-1">). No need to let JavaScript do this since it will always start at slide 1. To increment that number you can set the currentClass option so that we can get the index of the current slide with .index(). $(function(){ var slideshow = $("#feature-slideshow"); slideshow.slides({ preload: true, preloadImage: '<?php bloginfo('template_url'); ?>/images/loading.gif', generateNextPrev: false, effect: 'fade', play: 5000, hoverPause: true, currentClass: "current" animationStart: function() { var idx = slideshow.children(".current").index(); document.body.className = "slide-"+(idx+1); } }); }); A: Ok managed to get this to work, thanks to Marcus for his help, I just tweaked your code to pickup the correct list 'pagination' which had the current class applied; $(function(){ var slideshow = $("#feature-slideshow"); slideshow.slides({ preload: true, preloadImage: '<?php bloginfo('template_url'); ?>/images/loading.gif', generateNextPrev: false, effect: 'fade', play: 5000, hoverPause: false, currentClass: "current", animationStart: function() { var idx = $('ul.pagination').children(".current").index(); document.body.className = "slidebg-"+(idx+1); } }); }); I had to apply slidebg-3 to the body tag as for some reason when the slideshow cycles it includes the first list Works great though apart from removing all other body classes, I suppose I could add it as an ID as I'm not using one of those Anyway hope this helps someone else!
{ "language": "en", "url": "https://stackoverflow.com/questions/7539468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flex AdvancedDataGrid c/p rows issue I'm a newbie in Flex/AS3 development and I came across an issue that bugs me for a while now. I'm using an AdvancedDataGrid with some columns, and an ArrayCollection as the provider. I would like to make a copy/paste functionality so that multiple rows can be selected, copied, and then pasted below the selected (or last selected row). The problem is when I copy the data from one row to another, both of those rows become highlighted on mouse-over (upper instance isn't even selectable) - just as in this topic: Flex DataGrid/DataProvider bug? First I thought it was the issue of copying the reference, but it persist even if I use ObjectUtil.copy() method. Furthermore, I manually change one of the properties called "order" so that the objects of the ArrayCollection aren't identical, but it doesn't help. Dataprovider is called newTreatmentData, and the DataGrid is newTreatmentDG. Any suggestions are more then welcome. Here's part of the code that is relevant: private function getSelectedRow(event:Event):void { selectedRow = newTreatmentDG.selectedIndex; } private function copySelection(event:Event):void { bufferData = new ArrayCollection(); var sortedIndices:Array = newTreatmentDG.selectedIndices.sort(); for (var i:int = 0; i < newTreatmentDG.selectedIndices.length; i++){ //copy selected rows to the buffer var j:int = sortedIndices[i]; bufferData.addItem(newTreatmentData[j]); } } private function pasteSelection(event:Event):void { var rowsToMove:int = newTreatmentData.length - selectedRow - 1; //number of rows to move after pasting for (var i:int = 1; i <= bufferData.length; i++){ if (selectedRow + bufferData.length + i > newTreatmentData.length){ // adding objects to the array collection to avoid range error newTreatmentData.addItem(null); } } for (i = 1; i <= rowsToMove; i++){ newTreatmentData[selectedRow + bufferData.length + i] = ObjectUtil.copy(newTreatmentData[selectedRow + i]) //first move the rows to "give room" for pasting newTreatmentData[selectedRow + bufferData.length + i].order = selectedRow + bufferData.length + i; //manually changing the "order" property, but it doesn't help } for (var j:int = 1; j <= bufferData.length; j++){ //paste the data from the buffer newTreatmentData[selectedRow + j] = ObjectUtil.copy(bufferData[j-1]) newTreatmentData[selectedRow + j].order = selectedRow + j; //again changing the order property } newTreatmentData.refresh(); } A: I solved it by changing the mx_internal_uid property of every object in the dataprovider ArrayCollection. It seems that AdvancedDataGrid checks it to see if rows are equal. I assumed (and you know what they say about assumptions) that an object's UID changes when you copy its value into another object (hence the U in UID ;) ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7539471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AlertDialog Android HELP I have one countdown timer, and I want onFinish to pop up yes/no message box, and do something with it, but I get this error: The constructor AlertDialog.Builder(new CountDownTimer(){}) is undefined. CountDownTimer start1 = null; start1 = new CountDownTimer(60000, 1000) { public void onTick(long millisUntilFinished) { tvPreostaloVrijeme.setText(Integer .toString((int) (millisUntilFinished / 1000))); } public void onFinish() { broj1.setText(""); broj2.setText(""); op.setText(""); posalji.setEnabled(false); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener) .setNegativeButton("No", dialogClickListener).show(); } } .start(); DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: //Yes button clicked break; case DialogInterface.BUTTON_NEGATIVE: //No button clicked break; } } }; A: AlertDialog.Builder builder = new AlertDialog.Builder(this); remove this with getApplicationContext() AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
{ "language": "en", "url": "https://stackoverflow.com/questions/7539473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a shell right click menu item to edit desktop.ini I am trying to create a right click shell menu item to edit desktop.ini. I have managed to get this far: [HKEY_CLASSES_ROOT\Folder\shell\editdesktop] @="editdesktop" [HKEY_CLASSES_ROOT\Folder\shell\editdesktop\command] @="notepad "%L/desktop.ini" use the cmd command to create an desktop.ini and append the following format to the desktop.ini file ,Then open it(desktop.ini) with notepad.exe /* Format start */ [.ShellClassInfo] InfoTip= ConfirmFileOp=0w /* Format end */ // ps: i just want to creat the folder InfoTip , ,when i hover the folder,it will so 2 me. A: CMD.exe nor Windows Scripting Host has .ini support so implementing this without overwriting is a bit risky, you also need to set the correct attribute on the folder and this could be SYSTEM or READONLY depending on a registry key! This example should work in the default windows configuration and tries its best to not overwrite a existing file: [HKEY_CLASSES_ROOT\Folder\shell\editdesktop\command] @="cmd /C ((if not exist \"%L\\desktop.ini\" (>\"%L\\desktop.ini\" (echo.[.ShellClassInfo]&echo.InfoTip=&echo.ConfirmFileOp=0w)))&attrib +s \"%L\"&attrib +h +s \"%L\\desktop.ini\"&start notepad \"%L\\desktop.ini\")" It is probably a better idea to write a WSH or powershell script...
{ "language": "en", "url": "https://stackoverflow.com/questions/7539475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get value from TextBox (C#) I have been saving to the registry the infos that were typed into the TextBox on a form which was earlier created.After opening form, I want to appear all of the infos which was saved into the TextBox. When I attempt to run the following code,it's returning null value. What might be the problem? Code: SQLSERVER = textBox1.Text; SQLDATABASE = textBox2.Text; SQLUSER = textBox3.Text; SQLPASS = textBox4.Text; try { SqlConnection Baglanti = new SqlConnection("Data Source='" + SQLSERVER + "'; Initial Catalog='" + SQLDATABASE + "'; User id='" + SQLUSER + "'; Password='" + SQLPASS + "';"); Baglanti.Open(); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software", true); if (key != null) { RegistryKey key2 = key.CreateSubKey("BilkerSoft"); key.SetValue("SQLSERVER", SQLSERVER, RegistryValueKind.String); Registry.CurrentUser.CreateSubKey("BilkerSoft").SetValue("SQLSERVER", SQLSERVER); Registry.CurrentUser.CreateSubKey("BilkerSoft").SetValue("DATABASE", SQLDATABASE); Registry.CurrentUser.CreateSubKey("BilkerSoft").SetValue("USER", SQLUSER); Registry.CurrentUser.CreateSubKey("BilkerSoft").SetValue("PASSWORD", SQLPASS); } } catch (Exception ex) { MessageBox.Show("Hata oluştu:'" + ex.Message + "'"); } RegistryKey key1 = Registry.CurrentUser.OpenSubKey("BilkerSoft",true); try { if (key1 != null) { key1.SetValue("SQLSERVER", SQLSERVER, RegistryValueKind.String); Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("SQLSERVER", SQLSERVER); Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("DATABASE", SQLDATABASE); Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("USER", SQLUSER); Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("PASSWORD", SQLPASS); } Baglanti = new SqlConnection("Data Source='" + SQLSERVER + "';Initial Catalog='" + SQLDATABASE + "';User id='" + SQLUSER + "';Password='" + SQLPASS + "'"); Baglanti.Open(); Baglanti.Close(); MessageBox.Show("Kayıt Başarılı"); } catch (Exception ex) { MessageBox.Show("Hata oluştu:'" + ex.Message + "'"); } } private void Form1_Load(object sender, EventArgs e) { RegistryKey key2 = Registry.CurrentUser.OpenSubKey("BilkerSoft", true); textBox1.Text = Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("SQLSERVER", SQLSERVER).ToString(); textBox2.Text = Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("DATABASE", SQLDATABASE).ToString(); textBox3.Text = Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("USER", SQLUSER).ToString(); textBox4.Text = Registry.CurrentUser.OpenSubKey("BilkerSoft").GetValue("PASSWORD", SQLPASS).ToString(); } private void button2_Click(object sender, EventArgs e) { Application.Exit(); } } A: So, when you make the call Registry.CurrentUser.OpenSubKey("BilkerSoft", true);, what is that a SubKey of exactly? When you made the subkey, you were creating it off of the value of the subkey "Software" but then you're trying to find one that doesn't reference that Software subkey... so it doesn't see it, right? So you've got: ->Software ->BilkerSoft But what you're initially looking for via key2 is: ->BilkerSoft (A subkey off the root, which does not exist) I suspect that if you qualify where you're looking for the subkey, it'll find it just fine. "BilkerSoft" is under "Software", not at the same level as "Software". Meaning, that if you did something like key2 = key.OpenSubKey("BilkerSoft", true); it would find it (since key is the "Software" registry key). Haven't test this - I'm on a Mac - but seems like what you want. A: void ReadReg(string key, params Action<RegistryKey>[] results) { var k = Registry.CurrentUser.OpenSubKey(key); if (k != null) { foreach (var item in results) { item(k); } k.Close(); } } void WriteReg(string key, params Action<RegistryKey>[] results) { var k = Registry.CurrentUser.OpenSubKey(key, true); if (k != null) k = Registry.CurrentUser.CreateSubKey(key); foreach (var item in results) { item(k); } k.Close(); } Write ==> WriteReg(@"Software\BilkerSoft", key => { key.SetValue("SQLSERVER", textBox1.Text); }, key => { key.SetValue("DATABASE", textBox2.Text); }, key => { key.SetValue("USER", textBox3.Text); }, key => { key.SetValue("PASSWORD", textBox4.Text); }); Read ==> ReadReg(@"Software\BilkerSoft", key => { textBox1.Text = key.GetValue("SQLSERVER").ToString(); },key => { textBox2.Text = key.GetValue("DATABASE").ToString(); },key => { textBox3.Text = key.GetValue("USER").ToString(); },key => { textBox4.Text = key.GetValue("PASSWORD").ToString(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7539478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: WPF DataGrid binding custom row header give me suggestion I am trying to do togglebutton visiblity change on true/false properties, my togglebutton in row header template, I also create convert for change properties. Visibility="{Binding Path=col1, Converter={StaticResource ResourceKey=DemoConvertor}}" refer this like: https://skydrive.live.com/P.mvc#!/selectembed.aspx/.Public/dgRowToggleButtonSample.zip?ref=11&cid=0c0b4f9d80b744cd&sc=documents
{ "language": "en", "url": "https://stackoverflow.com/questions/7539480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: scope of $this is funked in PHP is it a bug or a feature? I have this code: class a(){ function b(){ if(isset($this){ echo 'instance! '; echo get_class($this); }else{ echo 'static'; } } } class C{ public function test(){ a::b(); } } $CC=new C; $CC->test(); This will echo instance C A: The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object). source So definitely, it's a feature, it's by design, and it's not a bug.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Need a update-query to populate table column "display_order" I have a table on mysql with these columns: * *id *property_id *display_order The data is to be like this: 1 , 1 , 1 2 , 1 , 2 3 , 1 , ... 3 , 2 , 1 4 , 2 , 2 5 , 2 , ... but the display_order is currently set to 1 on all rows. I need a mysql query in order to set display_order as given in the above example. This a 1 to N realation ship * *property table *photo table ... = 3 , 4 5 ... N ( <-dysplay order) I don't no how perform this update. A: create an UPDATE with a @variable, give it an initial value ..., with case change ... to 1, 1 to 2 and 2 to ... and assign its value to the colunm, updating fields from a subselect ordered by the columns that form your key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android's Activity.runOnUiThread is not static, so how can i use it? For example, if I have a thread doing expensive stuff, and from that thread I want to fire runOnUiThread in the Main (activity) class. Obviously I shouldn't make an instance of my activity class (Main). So if I try Main.runOnUiThread(mRunnable); from my thread it gives me an error saying it's not a static method, and therefor it can't be accessed in my way. Now my understanding would be that the activity class is nearly almost accessed in a static way. How would I do this? (Btw: I'm doing this because I was getting CalledFromWrongThreadException, Only the original thread that created a view hierarchy can touch it's views) A: Raunak has the right idea. I'll just add that you can also specify an integer in the method sendEmptyMessage as an identifier to the handler. This will allow you to create one handler that can handle all of your UI updates, e.g. public static final int EXAMPLE = 0; public static final int ANOTHER_EXAMPLE = 1; private final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch( msg.what ){ case EXAMPLE: //Perform action break; case ANOTHER_EXAMPLE; //Perform action break; } } } //Call to submit handler requesting the first action be called handler.sendEmptyMessage(EXAMPLE); Hope this helps! A: You should use the Handler class. The handler class runs on the UI thread. When you finish work in your thread, call handler.sendEmptyMessage(), from where you can make the changes to your ui. private final Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // make changes to ui } } A: Your question doesn't really provide enough details, but from the sound of things, you're in a private inner class (Runnable?) in your activity (Main). If that is the case, you can either write: Main.this.runOnUiThread(mRunnable); or runOnUiThread(mRunnable); //will see that there is no runOnUiThread in the current class and begin looking "upwards" Also, you may want to look at AsyncTask, specifically at the onPostExecute, onPreExecute and onProgressUpdate callbacks, which run on the UI thread. A: first create a runnable outside onCreate. Like this: private Runnable myRunnable = new Runnable() { @Override public void run() { //work to be done } }; and then call the runnable using: runOnUiThread(myRunnable); A: For those who are looking for an easy instant solution follow the simple steps * *Make a reference of your class before your onCreate() method MyClass obj; *Initialize it in you onCreate() method obj = MyClass.this; *Call runOnUiThread() obj.runOnUiThread(new Runnable() { public void run() { //perform your UI tasks here } }); Hope it helps. A: all of the above answers are not very correct. 1)if you want a piece of code to run on UI thread from any thread code base. you can do: Looper.getMainLooper().post(new Runnable(...)) because Looper.getMainLooper() is a static variable and initialized in ActivityThread. 2) if your runnable code snippet is inside an activity then you can use: MainActivity.this.runOnUiThread(...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JQuery .html() strips tr/td tags? http://jsfiddle.net/WXG7V/ As you can see below, I have a simple div containing a row I would like to append to the end of my table. If I alert the contents of the div back to the screen using ".html()", jQuery strips out all of the td/tr tags. <html> <head> <title>jQuery Strips Table Tags</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready( function() { alert($("#newRow").html()); $(".tasks > tbody:last").append($("#newRow").html()); }); </script> </head> <body> <table class="tasks" style="margin-left: 0px;"> <tr> <th>Feeder ID</th> <th>From</th> <th>To</th> <th># Reels</th> <th>Reel Length</th> <th>Type</th> <th>Colour</th> </tr> </table> </div> <div id="newRow" style="display: none;"> <tr> <td><input type="text" name="feeder_id" id="feeder_id" /></td> <td><input type="text" name="from" id="from" /></td> <td><input type="text" name="to" id="to" /></td> <td><select name="number" id="number"> <option value=1>1</option> <option value=2>2</option> <option value=3>3</option> <option value=4>4</option> <option value=6>6</option> <option value=8>8</option> <option value=9>9</option> <option value=12>12</option> <option value=14>14</option> <option value=16>16</option> </select></td> <td><input type="text" name="length" id="length" /></td> <td><select name="type" id="type"><option value="CU">Copper</option><option value="AL">Aluminum</option></select></td> <td><input type="radio" name="colour" id="black" value="black" />Black <input type="radio" name="colour" id="red" value="red" />Red <input type="radio" name="colour" id="blue" value="blue" />Blue <input type="radio" name="colour" id="white" value="white" />White <input type="radio" name="colour" id="green" value="green" />Green </td> </tr> </div> A: <tr>, <td> are only valid elements inside <table>. Use display: table-row and display: table-cell in conjunction with <div> to replace the <tr> and <td>. Example: <div class="table"> <div class="row"> <div class="cell"> Foo </div> </div> </div> CSS: .table{ display: table; } .row { display: table-row; } .cell { display: table-cell; } A: If you are using this for templating, I would recommend checking out handlebars.js Then you could simply wrap your existing html in a tag <script id="newRow" type="text/x-handlebars-template"> and keep the rest of your markup in the same format you started with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Limiting (clamping) canvas size I want to make moveable world for my HTML game so I put 1600x1200 canvas inside my 800x600 div element and using left and top to move the world. I expected that div will clamp size of my canvas, but instead my canvas overlaps borders of my div. The div doesn't stretch, the canvas is scaled independently from the div. I tried !important, max-width and max-height, different displays, nothing works. Using CSS for width and height just scales the canvas. I also tried putting my canvas into SVG as foreign object, but I get error "getContext is not a function". So, how can I limit size of my canvas? A: The div is going to expand to the size of your canvas unless the div has overflow: hidden; set in its CSS. The child element is larger than the parent element, and you haven't strictly told the browser to limit the sizing of the parent element. The max-width and max-height attributes won't help you here because you aren't placing "wrappable" content within the div. If you put text in a div with max-width set, the value will be respected. If you put an element with an unchanging size, like an image or a canvas element, the browser can't dynamically wrap it like a bunch of floating divs or some text. In this case, you have overflow, which needs to be handled differently. You can achieve what you're looking for by playing with the position and/or margin attributes for the canvas element once you set the parent div to hide the overflow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How would I output HTML in the specified format from a Ruby array? I have an array of various food items, like so: 1% milk (low fat) 100% fruit juice blend (juicy juice) 100% whole wheat bagel 100% whole wheat bread 100% whole wheat cracker (triscuit) 2% milk (reduced fat) alfredo sauce all-bran cereal all-fruit preserves (no added sugar) ... wrap sandwich (vegetables only) wrap sandwich (vegetables, rice) yellow cake with icing yellow corn (corn on the cob) zucchini bread zucchini or summer squash Now, I know how to get an HTML list of all the elements in the array in Ruby. I could do something like this: puts "<ul>" foods.each do |e| puts "<li>#{e}</li>" end puts "</ul>" However, I don't know how to break the list into different sections for each letter, so that I can take this array and output a bunch of seperate lists of items (in HTML), like this: <div class="grid_1"> <h1>#.</h1> <ul> <li>1% milk (low fat)</li> <li>100% fruit juice blend (juicy juice)</li> <li>100% whole wheat bagel</li> <li>100% whole wheat bread</li> <li>100% whole wheat cracker (triscuit)</li> <li>2% milk (reduced fat)</li> </ul> </div> <div class="grid_1"> <h1>A.</h1> <ul> <li>alfredo sauce</li> <li>all-bran cereal</li> <li>all-fruit preserves (no added sugar)</li> ... How would I create this output in Ruby? A: You could use Enumerable#group_by to group your values by the first character, like this: grouped_food = food.group_by { |f| f[0] } This would not put all the food starting with a number in a separate group, though. This would take some more magic: grouped_food = food.group_by { |f| f[0] =~ /[0-9]/ ? # if the first character is a number "#." : # group them in the '#.' group f[0].upcase+"." # else group them in the 'uppercase_first_letter.' group } A: You can first perform a group_by on your input list foods = foods.group_by{|x|x[0]=~/[a-z]/i?x[0].upcase():'#.'} and then proceed as before. foods.each do |key, list| puts "<div class='grid_1'>" puts "<h1>#{key}</h1>" puts "<ul>" list.each do |e| puts "<li>#{e}</li>" end puts "</ul>" puts "</div>" end
{ "language": "en", "url": "https://stackoverflow.com/questions/7539504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to put a Javascript event on something? I have a pre-made layout, cannot be changed. But I must put an onload() event to <BODY>. As I said, I'm not allowed just add "onload = sdfsdf" event. Then how? A: You could make a script to attach the event (i suppose that your problem is that you have no control over the html): <script> document.body.onload = function(){}; </script> A: Use JQuery: $(document).ready(function() { }); http://docs.jquery.com/Tutorials:Introducing_%24%28document%29.ready%28%29 A: You can register events on the body through a (java)script using: document.body.<event name> = function(){ // whatever your function does }; A: put all your code in an function that autoexecute: (function () { //your code here })(); and put it at the end of the body. A: Use window.onload = function(){ ... }. That has the equivalent result as <body onload="...">. A: If you want to make everything by yourself, without jQuery. MDN addEventListener. target.addEventListener(type, listener, useCapture<Optional>); Depending on the required effect, listener: * *DOMContentLoaded - loading of the DOM *load - loading of all the resource on the page - useful if the page contains large images
{ "language": "en", "url": "https://stackoverflow.com/questions/7539505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rewrite url using mod_rewrite My urls currently look like this: http://domain.com/news/articles.php?id=22&category=investments&title=securing-your-future-making-the-right-investment How can I use mod_rewrite to make the url look more like this: http://domain.com/news/articles/investments/securing-your-future-making-the-right-investment EDIT: need to include the id variable too A: Add something like this to your .htaccess file: ^/news/articles/([0-9]+)/(.*)$securing-your-future-making-the-right-investment$ /news/articles.php?id=$1&category=$3s&title=$2 [L] Don't know about the $3, but category doesn't seem to be present in the url you listed so I guess it isnt needed. This should make it work ;) A: #enable mod rewrite RewriteEngine On RewriteRule ^/news/articles.php?id=([0-9]+)&category=([a-zA-Z]+)&title=([a-zA-Z]+)$ /news/articles/$2/$1_$3 the ID must exist in the URL so the it looks like: http://domain.com/news/articles/investments/{ID}_securing-your-future-making-the-right-investment Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook get like count for search query I'm using https://graph.facebook.com/search?q=watermelon&type=post to retrieve posts with query watermelon. Is it possible to also get the like count for the posts I retrieve? A: The likes element is returned for search result entries that have been liked. Not all posts have been liked or the users permissions don't allow viewing of likes. Here is a screenshot from the graph explorer though for your query which has some likes information: A: The Facebook FQL does not have the feature of count, but you could always count the number of objects in the array with whatever language you are using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question to mapKeyPath I am following the Restkit Tutorial on https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md and this is pretty good because RestKit is a really cool framework - I think. There is just one point I don't get. In the documentation is a line with "article" but I cannot see where article is declared and where it comes from. // Define the relationship mapping [article mapKeyPath:@"author" toRelationship:@"author" withMapping:authorMapping]; Can someone give some light into the darkness? Is this the right area on how to handle 1:n relationships that are nested? A: The line should be: [articleMapping mapKeyPath:@"author" toRelationship:@"author" withMapping:authorMapping]; The updated article on the wiki has the correction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails how to update image? And how to do RESTful routing? I am trying to update my photographer model. But how problems with Rails routing and paperclip wont replace image. When I submit my form the url is: http://localhost:3000/admin/photographers/save.75 which gives an error. Couldn't find Photographer without an ID And my image is not updated. My form: <%= simple_form_for @photographer, :url => save_admin_photographers_path(@photographer), :html => {:multipart => true, :method => :post} do |f| %> <%= javascript_include_tag "tiny_mce/tiny_mce" %> <%= javascript_include_tag "init_my_tiny_mce" %> <%= f.input :name, :label => 'Name' %> <%= f.text_area :text, :label => 'Text', :size => '12x12' %> <%= f.file_field :image, :label => 'Image' %> <% if @photographer %> <% if @photographer.image %> <p class="ok"> <label for="dd">image ok</label> <%= image_tag("http://s3-eu-west-1.amazonaws.com/kjacobsen/photographer/image/#{@photographer.id}/#{@photographer["image"]}", :size => "39x22") %> </p> <p> <label for="sdd">&nbsp;</label> <%= link_to("remove", {:action => "remove_image", :id => @photographer.id}, {:confirm => "Are your sure?"}) %> </p> <% else %> <p class="current"> <label for="dd"></label> No image uploaded for movie </p> <% end %> <br /> <% end %> <br /> <%= f.file_field :flv, :label => 'Upload FLV' %> <br /> <% if @photographer %> <% if @photographer.flv %> <p class="ok"> <label for="dd">flv: <%= @photographer["flv"] %></label> <%= link_to("remove", {:action => "remove_flv", :id => @photographer.id}, {:confirm => "Are your sure?"}) %> </p> <% else %> <p class="current"> No flv uploaded <br /><br /> </p> <% end %> <% end %> <br /> <%= f.file_field :quicktime, :label => 'Upload Quicktime' %> <br /> <% if @photographer %> <% if @photographer.quicktime %> <p class="ok"> <label for="dd">quicktime: <%= @photographer["quicktime"] %></label> <%= link_to("remove", {:action => "remove_quicktime", :id => @photographer.id}, {:confirm => "Are your sure?"}) %> </p> <% else %> <p class="current"> <label for="dd"></label> No quicktime uploaded <br /> </p> <% end %> <% end %> <%= f.button :submit, :value => 'Create movie' %> <% end %> My update controller: def save @photographer = Photographer.find(params[:id]) @photographer.update_attributes(params[:photographer]) if !@photographer.save flash[:notice] = "&nbsp;" render_action 'edit' else flash[:notice] = "update ok" redirect_to :action => 'edit', :id => @photographer.id end end My routes: namespace :admin do resources :photographers do collection do post :save end end end A: What you're doing is basically an update action. The update route is automatically created when you do resources :photographers, you can verify this by typing rake routes in the terminal. You should rename your controller action from save to update and remove the custom route: namespace :admin do resources :photographers end Then use the update route in your form: :url => admin_photographer_path(@photographer) You should also change your html method, the update action uses PUT: :method => :put Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Download bugzilla eclipse plugin? I want to download Mylyn bugzilla eclipse plugin from an update site. Can anyone tell me the update site, because most of the links I found were invalid, thanks. A: I think the reason you aren't getting any answers is because it's available from the main update site: http://download.eclipse.org/releases/indigo Search for mylyn, under Collaboration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery + CSS element change I'm using the following code to set all classes of the element to display:none with the exception of the first instance. How would I modify the code to set the classes all the elements todisplay:none with the exception of the SECOND instance only. $(document).ready(function () { $('selectorForElement').slice(1).css('display', 'none'); }); A: A conjunction of :not() and :eq() selectors should do it: $('.selectorForElement:not(:eq(1))').hide(); Live demo. A: $('selectorForElement:eq(0), selectorForElement:gt(1)').css('display', 'none'); A: Try the following $(document).ready(function () { $('selectorForElement:eq(0)').css('display', 'none'); $('selectorForElement:gt(1)').css('display', 'none'); }); The :eq(0) selector will select the first element in the selector (index equals 0). The :gt(1) selector will select all items with an index greater than 1 which skips the first and second elements. The result is everything but the second element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Wordpress extracting wp_usermeta I'm writing a script that will extract wp_usermeta in a readable layout. I've got sql like below: select distinct(user_id), meta_value as suburb from wp_usermeta where meta_key = 'suburb' order by user_id Now is there a way we can include all other fields aswell using sql query to join the column on the right and make the result coming out in one table so I can use this for csv export? UPDATE 25/SEP/2011, 12:34pm: Doesn't matter guys, I found my answer refer to below sql!!! SELECT u.id, u.user_login, MIN(CASE m.meta_key WHEN 'title' THEN m.meta_value END) AS title, MIN(CASE m.meta_key WHEN 'first_name' THEN m.meta_value END) AS first_name, MIN(CASE m.meta_key WHEN 'last_name' THEN m.meta_value END) AS last_name, MIN(CASE m.meta_key WHEN 'suburb' THEN m.meta_value END) AS phone, MIN(CASE m.meta_key WHEN 'state' THEN m.meta_value END) AS state, MIN(CASE m.meta_key WHEN 'country' THEN m.meta_value END) AS country, MIN(CASE m.meta_key WHEN 'postcode' THEN m.meta_value END) AS postcode, MIN(CASE m.meta_key WHEN 'contact_no' THEN m.meta_value END) AS contact_no, MIN(CASE m.meta_key WHEN 'email' THEN m.meta_value END) AS email, MIN(CASE m.meta_key WHEN 'occupation' THEN m.meta_value END) AS occupation, MIN(CASE m.meta_key WHEN 'workplace' THEN m.meta_value END) AS workplace, MIN(CASE m.meta_key WHEN 'maternitybg' THEN m.meta_value END) AS maternitybg, MIN(CASE m.meta_key WHEN 'trainingdate' THEN m.meta_value END) AS trainingdate, MIN(CASE m.meta_key WHEN 'traininglocation' THEN m.meta_value END) AS traininglocation, MIN(CASE m.meta_key WHEN 'coltraining' THEN m.meta_value END) AS coltraining, MIN(CASE m.meta_key WHEN 'trainingyear' THEN m.meta_value END) AS trainingyear, MIN(CASE m.meta_key WHEN 'coltraining' THEN m.meta_value END) AS coltraining, MIN(CASE m.meta_key WHEN 'isinstructor' THEN m.meta_value END) AS isinstructor, MIN(CASE m.meta_key WHEN 'gender' THEN m.meta_value END) AS gender, MIN(CASE m.meta_key WHEN 'idf_indig_tsi' THEN m.meta_value END) AS idf_indig_tsi, MIN(CASE m.meta_key WHEN 'idf_ct_ld' THEN m.meta_value END) AS idf_ct_ld, MIN(CASE m.meta_key WHEN 'comments' THEN m.meta_value END) AS comments FROM wp_users u LEFT JOIN wp_usermeta m ON u.ID = m.user_id AND m.meta_key IN ('title', 'first_name', 'last_name', 'suburb', 'state', 'country', 'postcode', 'contact_no', 'email', 'occupation', 'workplace', 'maternitybg', 'trainingdate', 'traininglocation', 'coltraining', 'isinstructor', 'gender', 'idf_indig_tsi', 'idf_ct_ld', 'comments') GROUP BY u.ID Hope this helps people looking for this solution! A: You really shouldn't use SQL directly within WordPress as they offer dozens of functions to do the work for you. Doing so will also keep your code flexible for future upgrades of WordPress. In your case, you are interested in get_user_meta()
{ "language": "en", "url": "https://stackoverflow.com/questions/7539527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are there UI guidelines for facebook canvas apps? Does Facebook offer guidelines or some kind of CSS style library for Facebook canvas apps? Something that a developer could use to make the look and feel of their canvas app compliment Facebook? I'm speaking along the lines of fonts, colors, dialog box styles, etc. I guess, in theory, I'm looking for something along the lines of interface builder in iOS development. A: Understanding the Platform Policies will help you better design and develop your app. Check the examples and explanations too. A: Facebook has published a social design guideline. They also have a brand permissions guideline for when you want to use their logo, colors, etc. But they don't have a specific css/stylesheet guideline like you are asking for. A: The following is a link to everything that facebook offers a developer, it does not include any stylesheet guidelines: https://github.com/facebook The only thing I could think of is when I was implementing Facebook credits, Facebook had guidelines regarding the image to use and a best practice for the flow of purchasing a virtual item with Facebook credits besides that you should be able to develop your app however you like. You said you where looking for something along the lines of interface builder in iOS development, but I would compare facebook more like the interface builder for Android, everything goes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Recipe for `final`: omit `virtual`? Is it a valid recipe to say that if I write final (to a member function) one should not write virtual? In a base class, final methods would make no sense: struct Driver { virtual void print(); }; If one would add final to print() this would defy the reason for polymorphism in the first place. So that would be useless (though possible). When I derive from this class I can detect errors with final, but only without virtual: struct KeyboardDriver : public Driver { virtual void prynt() final; // Oops: typo, but compiler-ok }; struct MouseDriver : public Driver { void prynt() final; // Error: Hooray, compiler found my typo }; The additional final for KeyboardDriver::prynt was legal. Because final only requires the member function to be virtual -- the compiler lets this pass (FDIS 9.2p9). But when I leave out the virtual the typo makes this function non-virtual -- it overrides nothing, i.e. no virtual function. Therefore final without virtual serves the same purpose to this respect as override does. Update: Is my analysis correct? Does the functionality of final without virtual include that one of override? A: That is not what final is for. What you are looking for is override. struct Base { virtual void print(); }; struct Derived : Base { void prynt() override; //compiler error }; struct Good : Base { void print() override; //no compiler error }; If you mark a function as override when it does not, then you get an error. Combined with your final function, you get all the comforts of compiler checked safety, with the clarity of explicitly marking functions virtual when coding standards demand it. struct Best : Base { virtual void print() final override; }; A: Your analysis is correct. Not marking a final member as virtual avoids declaring a new, non-overriden member and catches mistakes. However, since that's the purpose of override, it may be simpler to just use final override; then whether the member is marked virtual or not won't matter at all. A: I do not think it is an error, it's just a virtual function that can not be overloaded. Same thing that would happen if the function were declared virtual in a parent class, since virtual declarations are inherited. It would make no sense to forbid it. A: Is my analysis correct? Does the functionality of final without virtual include that one of override? No. The reason that this was a compiler error: void prynt() final; // Error: Hooray, compiler found my typo Is because final is only allowed on virtual functions. The compiler is complaining because you used it on a function that isn't virtual. There is nothing syntactically wrong about this line: virtual void prynt() final; // Oops: typo, but compiler-ok It may not be what you want, but this is legitimate (and even meaningful, depending on the circumstances) code. The problem you are encountering is due to wanting to do this: struct Driver { virtual void print(); }; struct MouseDriver : public Driver { void print(); }; Omitting the virtual is technically legal. But personally, I've always felt that it was bad form. You're putting vital information (which functions are overridden) into another class. I think it was a mistake to even allow this to compile. If you want to avoid this problem, then explicitly state virtual on all virtual functions, and use override in the places where you mean to create a new function. Then, this will fail to compile correctly. struct Driver { virtual void print(); }; struct MouseDriver : public Driver { virtual void print() override; };
{ "language": "en", "url": "https://stackoverflow.com/questions/7539538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem with pagination links with routing i need to route all /home/college, /home/school etc to thehome controller's index action, with the following prototype. function index($type="school"){ ... } below is my routing definition Router::connect('/home/:type',array('controller'=>'home','action'=>'index'),array('pass'=>array('type'),'type'=>'(college)|(school)')); i am also using pagination inside it. But when i generate the next and previous links it's like below http://mysite.com/home/index/school/page:2 How can i remove the 'index' from the link? A: I'm not sure if you will have much luck removing index as it is the default action. However, I'm surprised your route works as mode is undefined. Router::connect('/home/:type', array('controller'=>'home', 'action'=>'index'), array('pass'=>array('type'), 'type'=>'(college|school)')); Check out CakePHP Routes Configuration. A: Alternatively, you could just create a 'dummy' home action, and call index with it. function home($type="school"){ $this->setAction('index',$type); } http://api13.cakephp.org/class/controller#method-ControllersetAction
{ "language": "en", "url": "https://stackoverflow.com/questions/7539540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to get FlexSlider jQuery Slider to work with Drupal I've been wrestling with trying to get FlexSlider http://flex.madebymufffin.com/ to work with Drupal 7 all today as it suits my needs perfectly and the logic of how to get it work made sense but hasn't actually worked. My setup: Using a subtheme of AdaptiveTheme Created a custom view block that outputs an unordered list of images that link to a node. I have applied the appropriate FlexSlider classes to the wrapper and list. Declared the two js scripts in the template.php Declared the flexslider.css in my theme.info file I'm newish to drupal and am more a CSS kind of guy - but I think it's a jQuery conflict/version problem... Any ideas? This is what I had in my template.php <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script src="js/jquery.flexslider-min.js"></script> <script type="text/javascript"> $(window).load(function() { $('.flexslider').flexslider(); }); </script> </head> @WChargin @TylerSmith wrapping the jQuery might be the solution but I think I've got some Syntax wrong somewhere along the way. Or it may be just something else. I assume I have to wrap the third script with a variable code like so: (function($) { $(window).load(function() { $('.flexslider').flexslider(); })(jQuery); But when I put this in my template.php file it causes the site not to load. A: Drupal 7 requires that you wrap your jQuery with a variable scope. (function($) { //jQuery can go in here })(jQuery); Does this help? Edit: I made FlexSlider/have successfully (with great ease) installed it on a Drupal 7 setup here. One way or another, I should be able to help you sort this out. A: Drupal 7 Flexslider-Took me a long time to find this but it really was a good one. Now I know. Full jquery call: <script type="text/javascript"> (function($) { $(window).load(function() { $('.flexslider').flexslider(); }); })(jQuery); A: You need to add your js and css through the template.php file or a pre process file. I have this slider working perfectly with a view. use drupal_add_js() and drupal_add_css() Example code below: sjm is the name of my theme. file template.php: notice i am only loading css and js on the front page: <?php sjm_preprocess(); /** F U N C T I O N S */ function sjm_preprocess() { // add the main SJM js drupal_add_js(drupal_get_path('theme', 'sjm') . '/js/sjm.js', array('scope' => 'header', 'weight' => 0)); /** FRONT PAGE STUFF */ if (drupal_is_front_page()) { drupal_add_js(drupal_get_path('theme', 'sjm') . '/js/sjm_front.js', array('scope' => 'footer', 'weight' => 1)); addFlexSlider(); } } /** Flexslider 1.7 * */ function addFlexSlider() { drupal_add_js(drupal_get_path('theme', 'sjm') . '/js/FlexSlider-1.7/jquery.flexslider-min.js', array( 'scope' => 'footer', 'weight' => '1' )); drupal_add_css(drupal_get_path('theme', 'sjm') . '/js/FlexSlider-1.7/flexslider.css', array( 'group' => CSS_THEME, 'weight' => 0 )); } ?> Now for the js file being loaded: sjm_front.js (sjm.js processes other functions when it is not the front of the site.) File: sjm_front.js (function ($) { /* required to use the $ in jQuery */ $('.featured-wrapper').hide(); /* hide the ul list first */ $(document).ready(function () { $(window).load(function () { addFlexSlider(); }); }); // end of $(document).ready() /** FlexSlider */ function addFlexSlider(){ $('.featured-wrapper').show().flexslider({ animation: "slide", controlNav: false }); } } }(jQuery)); Hope this helps! :) Check out seanjmorris.com soon.... to see an active version of this. A: Spent 2 hours trying to work this out when all i needed to do was download the Library files from https://github.com/woothemes/FlexSlider/zipball/master add them into the sites-->all-->libraries folder and it worked... immediately!
{ "language": "en", "url": "https://stackoverflow.com/questions/7539542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select last 30 items per group by Hopefully the title makes any sense. For this example I'll have the next table in my database measurements ================================== stn | date | temp | time = 1 | 01-12-2001 | 2.0 | 14:30 = 1 | 01-12-2001 | 2.1 | 14:31 = 1 | 03-12-2001 | 1.9 | 21:34 = 2 | 01-12-2001 | 4.5 | 12:48 = 2 | 01-12-2001 | 4.7 | 12:49 = 2 | 03-12-2001 | 4.9 | 11:01 = ================================== And so on and so forth. Each station (stn) has many measurements, one per day second. Now I want to select the temp of each station of the last 30 days measurements where the station has at least 30 temperature measurements. I was playing with subquerys and group by, but I can't seem to figure it out. Hope someone can help me out here. edited the table My example was oversimplified leaving a critical piece of information out. Please review the question. A: select t1.stn,t1.date,t1.temp,t1.rn from ( select *, @num := if(@stn = stn, @num + 1, 1) as rn, @stn := stn as id_stn from table,(select @stn := 0, @num := 1) as r order by stn asc, date desc) as t1 inner join (select `stn` from table where concat_ws(' ',date,time) >= now() - interval 30 day group by `stn` having count(*) >= 30) as t on t1.stn = t.stn and t1.rn <= 30 order by stn,date desc,time desc A: This is the query that should select Last 30 entries where there are at least 30 entries for a station This query is based on the answer here by nick rulez, so please upvote him SELECT t1.stn, t1.date, t1.temp, t1.time FROM ( SELECT *, @num := if(@stn = stn, @num + 1, 1) as rn, @stn := stn as id_stn FROM `tablename`, (SELECT @stn := 0, @num := 1) as r ORDER BY stn asc, date desc ) as t1 INNER JOIN ( SELECT `stn` FROM `tablename` GROUP BY `stn` HAVING COUNT(*) >= 30 ) as t ON t1.stn = t.stn AND t1.rn <= 30 ORDER BY stn, date desc, time desc I have tested it on a sample database I made based on your schema and is working fine. To know more about such queries have a look here Within-group quotas (Top N per group) A: SELECT stn, date, temp FROM ( SELECT stn, date, temp, @a:=IF(@lastStn=stn, @a+1, 1) countPerStn, @lastStn:=stn FROM cache GROUP BY stn, date ORDER BY stn, date DESC ) as tempTable WHERE countPerStn > 30; Is the query I was looking for, sorry if my question was 'so wrong' that it pushed you all in the wrong direction. I'll up vote the answers who'm helped me to find the needed query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Self-closing tags using createElement I need to add a self-closing tag to XML file with DOM in PHP, but I don't know how, because standardly, this tag looks like this: <tag></tag> But it should look like this: <tag/> A: DOM will do that automatically for you $dom = new DOMDocument; $dom->appendChild($dom->createElement('foo')); echo $dom->saveXml(); will give by default <?xml version="1.0"?> <foo/> unless you do $dom = new DOMDocument; $dom->appendChild($dom->createElement('foo')); echo $dom->saveXml($dom, LIBXML_NOEMPTYTAG); which would then give <?xml version="1.0" encoding="UTF-8"?> <foo></foo> A: Just pass a node param to DOMDocument::saveXML in order to output only a specific node, without any XML declaration: $doc = new \DOMDocument('1.0', 'UTF-8'); $doc->preserveWhiteSpace = false; $doc->formatOutput = false; $node = $doc->createElement('foo'); // Trimming the default carriage return char from output echo trim($doc->saveXML($node)); will give <foo/> not containing any new line / carriage return ending char.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to use Boilerplate on Business Catalyst as it does not allow Web server configuration I want to use Boilerplate for my Adobe Business Catalyst Template. Every thing is fine but it(BC) do not allow .htaccess file as its an hosted solution. What alternatives are there to go without .htaccess file? I also posted on official Business Catalyst Support Forum but all in vain. A: Isn't Boilerplate just a HTML/CSS/JS framework? Why do you need access to .htaccess? You should just be able to FTP it across to your BC site and use it. By the way, BC doesn't allow access to .htaccess, but you don't need it in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript Json problem in IE9 Hy guys. In firefox and chrome this script alerts 'myclass', but does nothing in IE (i have version 9). var a = {"class" : "myclass"}; alert(a.class); if I use cssclass instead of class, it is working in IE too. var a = {"cssclass" : "myclass"}; alert(a.cssclass); This is very annoying. Is the word 'class' reserved in IE, or what can be the problem, and what is the solution? A: I think class is a reserved keyword. Because objects are associative arrays in javascript you could also use this to access the value: alert(a['class']);
{ "language": "en", "url": "https://stackoverflow.com/questions/7539555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Type cant be resolve in UnitTest after migrating Project from vs2005 to vs2010 (MSTest) We are actually analyzing what we have to do if we migrate our application from VS2005 up to VS2010. What i have done: I opened all solutions in VS2010 and let convert vs the projects. At the moment the production assemblies dont get an upgrade of the .NET Framework, it has to target the framework 2. The framework version of the unit test assemblies (MSTest) is switched to the version 4 by VS2010 automatically, thats ok so far. The Problem: Some unit tests are failing cause they can't access a config file through the ConfigurationMananger.OpenExeConfiguration(ConfigurationUserLevel.None) call. The following exception is thrown: System.Configuration.ConfigurationErrorsException: An error occurred loading a configuration file: Type is not resolved for member X ... System.Runtime.Serialization.SerializationException: Type is not resolved for member X The member X is derived from GenericIdentity and is marked as [Serializable]. All needed files (configuration, assemblies) are up to date and are correctly deployed in the output folder. I tried to switch the framework version of the production assemblies to version 4, but it didn't help. I found this ressources, but they dont helped me. post from stack Anybody has an idea why i get the described behavior? A: If i change my Identity from public MyIdentity : GenericIdentity { } to public MyIdentity : MarshalByRefObject, IIdentity { } all of my tests are gettin green.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fuzzy outline on a form button when using a background image with a 20px border-radius For some reason, exclusively on Windows machines, on the Sign in button on this page, I'm getting this odd fuzzy outline that's difficult to explain, so see for yourself: http://zis.smartlyedu.com/login It doesn't appear on Mac OS, but it does on Windows. Has anyone encountered this before? Here is the CSS for the button: div.input-submit input{ outline:none; font-family:Helvetica, Arial, sans-serif; width:100px; height:35px; color:#fff; font-weight:normal; float:right; font-size:18px; text-shadow:#000 1px 1px 1px; border:1px solid #fff; -moz-border-radius:20px; -webkit-border-radius:20px; -o-border-radius:20px; -ms-border-radius:20px; -khtml-border-radius:20px; border-radius:20px; background:-webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, rgba(0,0,0,0)), color-stop(100%, rgba(0,0,0,0.2))); background:-webkit-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.2)); background:-moz-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.2)); background:-o-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.2)); background:-ms-linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.2)); background:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,0.2)); background-color:#31639d; font-weight:bold; border:1px solid #fff } A: This solution has been found through comments at the original post. Alain, add display:none to the input element to confirm that the outline is originating from the input element. If you're sure about the origin's cause, disable all CSS attributes of the selectors which match your element, and add them back individually. This way, you will be able to find the cause of your CSS issue. Jason McCreary responded: Thanks, I tried your method and I found out that the issue was with the 1px border and the 20px border-radius. Apparently on Windows it freaks out if they're used at the same time on a submit button. To fix it, all I did was remove the borders and replace it with border: none;. If I removed the border-radius it would work fine, too. Thanks for the help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7539561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there a smarter alternative to "watch make"? I ran into this useful tip that if you're working on files a lot and you want them to build automatically you run: watch make And it re-runs make every couple seconds and things get built. However ... it seems to swallow all the output all the time. I think it could be smarter - perhaps show a stream of output but suppress Nothing to be done for 'all' so that if nothing is built the output doesn't scroll. A few shell script approaches come to mind using a loop and grep ... but perhaps something more elegant is out there? Has anyone seen something? A: How about # In the makefile: .PHONY: continuously continuously: while true; do make 1>/dev/null; sleep 3; done ? This way you can run make continuously and only get output if something is wrong. A: Using classic gnu make and inotifywait, without interval-based polling: watch: while true; do \ $(MAKE) $(WATCHMAKE); \ inotifywait -qre close_write .; \ done This way make is triggered on every file write in the current directory tree. You can specify the target by running make watch WATCHMAKE=foo A: Twitter Bootstrap uses the watchr ruby gem for this. https://github.com/twbs/bootstrap/blob/v2.3.2/Makefile https://github.com/mynyml/watchr Edit: After two years the watchr project seems not to be maintained anymore. Please look for another solution among the answers. Personally, if the goal is only to have a better output, i would recommend the answer from wch here A: I do it this way in my Makefile: watch: (while true; do make build.log; sleep 1; done) | grep -v 'make\[1\]' build.log: ./src/* thecompiler | tee build.log So, it will only build when my source code is newer than my build.log, and the "grep -v" stuff removes some unnecessary make output. A: This shell script uses make itself to detect changes with the -q flag, and then does a full rebuild if and only if there are changes. #!/bin/sh while true; do if ! make -q "$@"; then echo "#-> Starting build: `date`" make "$@"; echo "#-> Build complete." fi sleep 0.5; done * *It does not have any dependencies apart from make. *You can pass normal make arguments (such as -C mydir) to it as they are passed on to the make command. *As requested in the question it is silent if there is nothing to build but does not swallow output when there is. *You can keep this script handy as e.g. ~/bin/watch-make to use across multiple projects. A: This one-liner should do it: while true; do make --silent; sleep 1; done It'll run make once every second, and it will only print output when it actually does something. A: Here is a one-liner: while true; do make -q || make; sleep 0.5; done Using make -q || make instead of just make will only run the build if there is something to be done and will not output any messages otherwise. You can add this as a rule to your project's Makefile: watch: while true; do $(MAKE) -q || $(MAKE); sleep 0.5; done And then use make watch to invoke it. This technique will prevent Make from filling a terminal with "make: Nothing to be done for TARGET" messages. It also does not retain a bunch of open file descriptors like some file-watcher solutions, which can lead to ulimit errors. A: There are several automatic build systems that do this and more - basically when you check a change into version control they will make/build - look for Continuous Integration Simple ones are TeamCity and Hudson A: @Dobes Vandermeer -- I have a script named "mkall" that runs make in every subdirectory. I could assign that script as a cron job to run every five minutes, or one minute, or thirty seconds. Then, to see the output, I'd redirect gcc results (in each individual makefile) to a log in each subdirectory. Could something like that work for you? It could be pretty elaborate so as to avoid makes that do nothing. For example, the script could save the modify time of each source file and do the make when that guy changes. A: You could try using something like inotify-tools. It will let you watch a directory and run a command when a file is changed or saved or any of the other events that inotify can watch for. A simple script that does a watch for save and kicks off a make when a file is saved would probably be useful. A: You could change your make file to output a growl (OS X) or notify-send (Linux) notification. For me in Ubuntu, that would show a notification bubble in the upper-right corner of my screen. Then you'd only notice the build when it fails. You'd probably want to set watch to only cycle as fast as those notifications can display (so they don't pile up). A: Bit of archaeology, but I still find this question useful. Here is a modified version of @otto's answer, using fswatch (for the mac): TARGET ?= foo all: @fswatch -1 . | read i && make $(TARGET) @make -ski TARGET=$(TARGET) %: %.go @go build $< @./$@
{ "language": "en", "url": "https://stackoverflow.com/questions/7539563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Currency used in the cart must match the currency of the seller account My client's Google Checkout account is based in UK, hence its default currency is GBP. Accordingly, I thought I'd let users pay using GBP - they actually think they are paying in USD but behind the scenes I convert USD to GBP according to the conversion rate. Anyway, I keep getting the following error message: The currency used in the cart must match the currency of the seller account. You supplied a cart with USD and the seller account is associated with GBP. When I check the Integration Console for the message that is being sent from the website to Google Checkout's API, this is what I get: _type=checkout-shopping-cart&shopping-cart.items.item-1.item-name=Credits&shopping-cart.items.item-1.item-description=Description&shopping-cart.items.item-1.item-currency=GBP&shopping-cart.items.item-1.unit-price=64.42&shopping-cart.items.item-1.quantity=1 As you can see, I made sure the currency is set to GBP, yet it still complains. Is there anything I can do to fix this? A: How are users thinking they are paying in USD? If they see the Place Order page in USD, then the cart is posted in USD, hence your problem. Also please keep in mind that credit card companies will add extra fees for currency conversions, which are unknown at the time of transaction to both the seller and Google Checkout. Usually the fees appear as a separate item on the buyer's credit card statement. You may want to inform non-UK buyers about this and emphasize that the currency fees are out of your control. This doc has some info related to this error: https://checkout.google.com/support/sell/bin/answer.py?hl=en&answer=71444
{ "language": "en", "url": "https://stackoverflow.com/questions/7539568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simultaneous maximum & minimum from a set of elements In Book "Intro to algorithm -- by CLRS" mentioned in Sec-9.1 that Simultaneous Maximum & minimum finding can be done in the running time 3*floor(n/2). Same as for lower-bound also. I have written the following algorithm (taking help from CLRS) whose lower-bound is 2*floor(n/2). [ This is wrong --- thanks to Ricky Bobby ] I m using the variables: 'max' & 'min' to denote maximum & minimum elements, 'i' as indexing variable. Simultaneous_Maximum_&_Minimum (A, n) // Array A[1...n] { 1. If n is even, compare the first two elements and assign the larger to max and smaller to min. Set StartIndex = 3. 2. If n is odd, set both max & min to the first element. Set StartIndex = 2. 3. for (i = StartIndex; i <= n; i = i+2 ) { // Processing elements in pair if (max < A[i]) { // Compare max with A[i] if (A[i] < A[i+1]) // Compare max with A[i+1] max = A[i+1]; // we sure that A[i] or A[i+1] can't be min else { // When max less than A[i] but A[i] not less than A[i+1] max = A[i]; // Set A[i] as max if (min > A[i+1]) // Possible that A[i+1] can be min min = A[i+1]; // if yes, set A[i+1] as min } } // When max is not less than A[i] else if (min > A[i]) { // Compare min with A[i] if (A[i] > A[i+1]) // Compare min with A[i+1] min = A[i+1]; // we sure that A[i] or A[i+1] can't be max else { // When min is greater than A[i] but A[i] not greater than A[i+1] min = A[i]; // Set A[i] as min if (max < A[i+1]) // Possible that A[i+1] can be max max = A[i+1] // if yes, set A[i+1] as max } } } else { // max > A[i] and min < A[i] -- so A[i] can't be max or min if (max < A[i+1]) max = A[i+1] if (min > A[i+1]) min = A[i+1] } } } Thanks to Ricky Bobby for pointing out my mistakes -- we can't done find simultaneous maximum & minimum in 2*floor(n/2) running time. A: Tell me if i'm wrong, but you're not look at the case : max>A[i]>min if max>A[i]>min : if A[i+1] > max max =A[i+1] if A[i+1] <min min = A[i+1] So your algorithm is wrong in general case. In decreasing order or increasing order it might works, but it's pretty useless, since for a sorted list you can find min and max with this espression : (min,max) = (A[0],A[n]).sort() so in O(get(A[0]) + get(A[n])) A: Methinks that if the array is sorted, the minimum can be found at array[0] and the maximun at array [n-1]. Or the other way round for a descending ordering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I compare two lists in python, and return that the second need to have the same values regardless of order? a = [1, 2, 3, 4] b = [2, 4, 3, 1] c = [2, 3] When comparing a to b, should return True: all items in a are presented in b, and all items in b are presented in a. When comparing a to c, should return False: there are items in a that don't exist on c. What is the pythonic way to do it? A: Use sets or frozensets. set_a = {1, 2, 3, 4} #python 2.7 or higher set literal, use the set(iter) syntax for older versions set_b = {2, 4, 4, 1} set_a == set_b set_a - set_b == set_b - set_a The biggest advantage of using sets over any list method is that it's highly readable, you haven't mutated your original iterable, it can perform well even in cases where a is huge and b is tiny (checking whether a and b have the same length first is a good optimization if you expect this case often, though), and using the right data structure for the job is pythonic. A: Use sets: In [4]: set(a) == set(b) Out[4]: True In [5]: set(a) == set(c) Out[5]: False A: Turn them into sets: >>> set([1,2,3,4]) == set([2,4,3,1]) True >>> set([2, 3]) == set([1,2,3,4]) False If your lists contain duplicate items, you'll have to compare their lengths too. Sets collapse duplicates. A: Sort, then compare. sorted(a) == sorted(b)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Online game backend architecture using mono I need to write backend for a flash game. The game it self is not complicated. The game itself is a small session(around 2 minutes long) but there are many sessions active at a time. What I though of is making a gateway server which accepts connections and multiple servers that host game sessions. Gateway will tell the game server to create new game session and will forward all messages to it's message queue. Game server will process it and reply back to gateway, which in turn will send response back to the client. I want to do this using mono and run on linux as daemons. Can you give opinions about how to make this architecture better? UPD: The game is not realtime and avg packets per second from a single game session will be around 5-15. Game session has 2 to 4 players. They all have average size of around 10 to 50 bytes. Udp is possible but will be an overkill, so it will to go with tcp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can not send special characters (UTF-8) from JSP to Servlet: question marks displayed I have a problem sending special characters like cyrillic or umlauts from a jsp to a servlet. I would greatly appreciate your help here. Here is what I have done: * *Defined the utf-8 charset in the jsp: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> ... <div class="authentication"> <form name="registerForm" action="register" method="get" accept-charset="UTF-8"> <input type="input" name="newUser" size="17"/> <input type="submit" value="senden" /> </form> </div> ... *Set Tomcat URIEncoding for Connector, in the server.xml <Connector URIEncoding="UTF-8" ... *Inside the servlet - set the CharacterEncoding to UTF and read request public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ request.setCharacterEncoding("UTF-8"); String username = request.getParameter("newUser"); System.out.println("encoding: "+request.getCharacterEncoding()); System.out.println("received: "+username); *Here is what gets displayed when using for example: Однако encoding: UTF-8 received: ?????? Am I missing something ? I suppose the servlet can not decode the String properly, but I have no idea why is this happening. I've followed all the advises on this topic but had no luck. thanks in advance. A: Everything looks fine. Only the System.out.println() console also needs to be configured to interpret the byte stream as UTF-8. If you're sitting in an IDE like Eclipse, then you can do that by setting Window > Preferences > General > Workspace > Text File Encoding to UTF-8. For other environments, you should be more specific about that so that we can tell how to configure it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to execute bulk insert statement in java (using JDBC) with db=SQL Server 2008 Express I am trying to execute a BULK INSERT statement on SQL Server 2008 Express. (It basically takes all fields in a specified file and inserts these fields into appropriate columns in a table.) Given below is an example of the bulk insert statement-- BULK INSERT SalesHistory FROM 'c:\SalesHistoryText.txt' WITH (FIELDTERMINATOR = ',') Given below is the Java code I am trying to use (but its not working)...Can someone tell me what I am doing wrong here or point me to a java code sample/tutorial that uses the Bulk Insert statement? -- public void insertdata(String filename) { String path = System.getProperty("user.dir"); String createString = "BULK INSERT Assignors FROM " + path + "\\" +filename+ ".txt WITH (FIELDTERMINATOR = ',')"; try { // Load the SQLServerDriver class, build the // connection string, and get a connection Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String connectionUrl = "jdbc:sqlserver://arvind-pc\\sqlexpress;" + "database=test01;" + "user=sa;" + "password=password1983"; Connection con = DriverManager.getConnection(connectionUrl); System.out.println("Connected."); // Create and execute an SQL statement that returns some data. String SQL = "BULK INSERT dbo.Assignor FROM " + path + "\\" +filename+ ".txt WITH (FIELDTERMINATOR = ',')"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(SQL); // Iterate through the data in the result set and display it. while (rs.next()) { //System.out.println(rs.getString(1) + " " + rs.getString(2)); System.out.println(" Going through data"); } } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } } A: I'd guess that your SQL string is missing the single quotes around the filename. Try the following: String SQL = "BULK INSERT dbo.Assignor FROM '" + path + "\\" +filename+ ".txt' WITH (FIELDTERMINATOR = ',')"; EDIT in response to your comment: I wouldn't expect there to be anything in the ResultSet following a bulk insert, in much the same way that I wouldn't expect anything in a ResultSet following an ordinary INSERT statement. These statements just insert the data they are given into a table, they don't return it as well. If you're not getting any error message, then it looks like your bulk insert is working. If you query the table in SQLCMD or SQL Server Management Studio, do you see the data? INSERT, UPDATE, DELETE and BULK INSERT statements are not queries, so you shouldn't be using them with the executeQuery() method. executeQuery() is only intended for running SELECT queries. I recommend using the executeUpdate(String) method instead. This method returns an int, which is normally the number of rows inserted/updated/deleted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Log in to desktop application by Windows Live ID I want to create a login form for my desktop application that user can use Windows Live ID for that. I create an application in manage.dev.live.com and use Desktop Implementation section. I use a WebBrowser control and navigate to a given address. but I don't know how to receive the token for user. If I have made a mistake please tell me how to fix that. A: As of June 2011, Windows Live ID supports OAUTH 2.0 and should enable you to do that (read more about it). WPF code example can be found at https://github.com/liveservices/LiveSDK/tree/master/Samples/CSharpDesktop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Detect Programming Language from code snippet Possible Duplicate: Detecting programming language from a snippet Is there a way to identify the following for a text snippet? * *Whether it is a piece of code *The programming language in which it is written A: Not in general. A large part of the problem is that many programming languages are similar - there are snippets of code that may be valid in mulitple languages. It all depends on the length of the snippet. If you have enough code, you can probably figure out which language it is written in, but it might require quite a lot of code to correctly identify the language. A: Depends on how long is the code snippet, for extremely short code sample it may not be possible at all, and still not easy for long code snippets. But anything that is developed for this purpose cannot ensure 100% accuracy of detecting the programming language for any length of code snippet (except if everything in the language is in the code snippet). A lot of the programming languages is similar. One very accurate (not 100% though) is to look for the header files or libraries etc that are included in the code, and how they are added (using, #include etc), it can be a huge and very accurate hint about the programming language.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What do this expression mean? (SetConsoleTextAttribute function in C) I'm in a the middle of creating a console based small game for our C programming class assignment and I decided to make it more presentable and unique by adding text colors and text backgrounds. While I was on my quest searching for a solution, I've found this handy function that will do just the way I wanted for my project but the problem is that there is this part I do not understand: WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F); Where, BackC and ForgC are given integers and the data type WORD is just a typedef for an unsigned short int. Specifically, what I don't understand is the ((BackC & 0x0F) << 4) + (ForgC & 0x0F) part. Can anyone help me with this? I know that I can just use the function but I really want to know how the function works...Thanks! Here is the full source code (colorExample.c) #include <windows.h> #include <stdio.h> void SetColorAndBackground(int ForgC, int BackC); int main() { SetColorAndBackground(10,1); //color value range 0 up-to 256 printf("what is text background color \n"); SetColorAndBackground(11,1); printf("how about this?"); getch(); return 0; } void SetColorAndBackground(int ForgC, int BackC) { WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor); return; } A: ForgC and BackC are two values that can really only expand to take up of 4 bits each (you can tell this because they are being bitwise ANDed with 0x0F, which clears all but the last 4 bits of the first operand). So if we look at them as 8-bit wide values, they would be of the form ForgC 0000xxxx BackC 0000yyyy Then you bitwise shift ForgC 4 bits to the left, making ForgC xxxx0000 BackC 0000yyyy And then you add them together¹, making ForgC xxxx0000 BackC 0000yyyy Result xxxxyyyy So what this does in effect is "combine" both values into one. SetConsoleTextAttribute might then separate them again, or it might use the combined value as-is. ¹ Technically this should be a bitwise OR instead of integer addition. Although in this specific case (where the two operands are guaranteed to not have an 1-bit in the same position) both operations will produce the same result, bitwise OR makes the intent clearer. A: If takes the lower 4 bits of each BackC and ForgC and joins them to get a 8 bit value. (( BackC & 0x0F // take last 4 bits of BackC ) << 4) // and shift 4 to the left + ( ForgC & 0x0F // plus take last 4 bits of ForgC ) E.g. if BackC is 0b......abcd and ForgC is 0b.....efgh (both in binary representation) you'll get the value 0xabcdefgh.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Emacs: how do I set a major-mode stored in a variable? Suppose I have a variable newName which is bearing some mode name, e.g. "python-mode". How do I make current buffer of the mode specified by newName? (progn (let (newName) (setq newName "python-mode") (newName) ;; doesn't work! It doesn't set current buffer's mode to be a python mode. ) ) This also doesn't work: (set-variable 'major-mode "python-mode") This question is fundamental - since it is equal to "is it really possible to treat data as code in lisp?" Edit @phils Your solution doesn't work for me. I copy a buffer - and I want the new one to have the same mode as the old one. So I store the mode of the original buffer in the variable. Then try to apply Your solution. It gives error (it's the essence - I omit here the buffer-copying stuff): (let (sameMode) (setq sameMode major-mode) (funcall (intern sameMode)) ) sameMode stores here mode in the form of "python-mode" (example for python-mode). A: (let ((mode "python-mode")) (funcall (intern mode))) or (let ((mode 'python-mode)) (funcall mode))
{ "language": "en", "url": "https://stackoverflow.com/questions/7539615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scheme function that sum number u and list x u+x1+x2 Im new to Scheme and trying to make function that is (in f u x), u is integer, x is a list and f binary function. The scheme expression (in + 3 '(1 2 3)) should return 3+1+2+3=9. I have this but if i do (in + 3 '(1 2)) it return 3 not 6. What am i doing wrong? (define (in f u x) (define (h x u) (if (null? x) u (h (cdr x) (f u (car x))))) (h x 0)) A: From what I understand of what your in function is supposed to do, you can define it this way: (define in fold) ; after loading SRFI 1 :-P (More seriously, you can look at my implementation of fold for some ideas, but you should submit your own version for homework.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7539616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where GTK finds icon names to use with gtk_image_new_from_icon_name()? GTK can construct images by name of the "icon from current icon theme". For example: #!/usr/bin/env python import gtk; wnd=gtk.Window(); img=gtk.Image(); img.set_from_icon_name( "go-jump", gtk.ICON_SIZE_BUTTON ); wnd.add( img ); img.show(); wnd.show(); gtk.main() This will display a window with a pretty arrow inside it. But - only on ubuntu. On Windows or OSX it will display window with a "no image" icon inside :(. So my questions is - where GTK keeps icon names like "go-jump"? Is it some list or specification available like for stock icons? Maybe it's some GTK API i can use to list such icons? A: Better late than never ! Here are two little Python scripts showing all existing icons sorted by their name: * *http://dl.0xdeadc0de.fr/misc/gtkiconview_freedesktop.py for those in the Icon Naming Specification. *http://dl.0xdeadc0de.fr/misc/gtkiconview_local.py for those included in packages such as 'gnome-icon-theme-symbolic'. A: The names are in the Icon Naming Specification. If this doesn't work on Windows or OSX, then report it as a bug - GTK needs at least one icon theme installed in order to work properly. A: Developing on Debian but wanting cross-platform support, I've recently installed gtkmm and co on both Windows and OS X, via MSYS2 and Homebrew respectively. As an aside, gtkmm, MSYS2, and Homebrew are excellent projects and well worth a look (I have no affiliation blah blah). In that time, I think I've gained a decent understanding of why this happens and how to 'fix' it. Why This is not a bug in GTK+, as the accepted answer suggests. It's a fact of life when using a library tailored to Linux on another platform, via an environment that creates a Linux-like picture. On Linux, you have a single environment with a standardised filesystem - via the FHS and FreeDesktop specs - with icons always in /usr/share/icons. In contrast, on other platforms, you install Linux-like environments for compilation and sometimes runtime, each with its own virtual filesystem - which is difficult to track by other programs, without doing dangerous things to the end-user's PATH, especially if you're trying multiple such environments... You get the idea. The end result is that your program, by default, doesn't necessary have any awareness of where your environment's virtual root resides. How The solution, I've found, is to copy all required resources to the same folder as your executable - i.e. the directory you'll eventually redistribute, or if you're writing OSS, do this in your makefile or such. This is because, as far as I can tell, a program - looking for GTK+ resources, DLLs, etc. - checks its own directory before the (probably not helpful) PATH. A little opposite to how shells do things, but handy! So, you copy the relevant icon themes, as installed by your package manager, into a new folder within said directory. At a minimum, do this for the standard theme: copy it to $YOURDIR/share/icons/Adwaita. Then restart your program. If you're anything like me, now all the icons work perfectly. The same applies for pretty much any other resource that you need to redistribute with your application. Notably, I'd suggest doing the same thing with all DLLs needed by your binary. These may or may not work for you out-of-the-box and depending on how you invoke your binary - but you really can't afford to speculate about whether your end-users already have the right set of DLLs installed somewhere in their PATH, of the right version compiled by the right compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Closest group of 3 points Is there a known, efficient algorithm for finding the closest group of three points in a cloud? This is similar to the closest pair of points problem but I am looking for three points instead of two. Edit The definition of "closest" will affect the complexity of the algorithm. As Jack pointed out, finding the minimum area triangle is 3sum-hard and in any case not well suited to my application. I am hoping there is a more efficient algorithm for finding the minimum perimeter (i.e. |AB|+|AC|+|BC|) triangle or something similar (e.g. minimum |AB|²+|AC|²+|BC|².) I know of no reason why this should be 3sum-hard as the existence of 3 colinear points elsewhere would not affect the result. Note: my points have eight dimensions, so any algorithm that is restricted to fewer dimensions is not suitable. A: This problem is similar to the classical problem of finding the closest pair in a set of points. You can adapt the worst-case O(n log n) algorithms that solve the closest-pair problem to solve this one. The specific problem was featured in Google's Code Jam competition. Here is a resume of the analysis: The number of points can be pretty large so we need an efficient algorithm. We can solve the problem in O(n log n) time using divide and conquer. We will split the set of points by a vertical line into two sets of equal size. There are now three cases for the minimum-perimeter triangle: its three points can either be entirely in the left set, entirely in the right set, or it can use points from each half. Further: "To find the minimum perimeter for the third case (if it is less than p)": * *We select the points that are within a distance of p/2 from the vertical separation line. *Then we iterate through those points from top to bottom, and maintain a list of all the points in a box of size p x p/2, with the bottom edge of the box at the most recently considered point. *As we add each point to the box, we compute the perimeter of all triangles using that point and each pair of points in the box. (We could exclude triangles entirely to the left or right of the dividing line, since those have already been considered.) We can prove that the number of points in the box is at most 16, so we only need to consider at most a small constant number of triangles for each point. It seems to me you could even adapt the method to work in the |AB|²+|AC|²+|BC|² case. A: There is an obvious algorithm which works in O(n^2). 1) perform Delaunay triangluation - O(n log n), so we get a planar graph. As it is Delaunay triangluation, which maximises the minimum angle, it is clear that the closest 3 points must be connected by at least 2 edges (but they don't necessarily need to form the triangle!). Otherwise there would be more closer points or more closed angles. 2) for each point (vertex of the graph), we examine each couple of adjacent edges and look the 3 vertices defined by these 2 edges. How much time will the step 2) will take? Since the graph is planar, the number of edges is <= 3n - 6, i.e. O(n). So this step will take O(n^2) in the worst case (O(n) in the typical case, where the degree of each vertex is limited). So the whole algorithm is O(n^2). Note that the step 2) is somehow naive (brute force) solution, so I think there is a space for improvement (also, the steps 1 and 2 could probably be merged somehow). A: The problem you mentioned is variation of 3sum hard problem. Have a look at http://www.cs.mcgill.ca/~jking/papers/3sumhard.pdf for details. This problem can be also expressed as finding smallest triangle from given points. EDIT: Essentially, 3sum hard problem means that lower bound is O(n^2). There might be small improvement here and there but nothing much can be done. For this specific problem (smallest triangle), see chapter 3 of http://www.cs.princeton.edu/~chazelle/pubs/PowerDuality.pdf. A: This a specific form of the k-nearest neighbor problem, namely where k=3. The cited page does not specify algorithmic complexity, but it's fairly obvious to see that a naive approach of computing the distance from the selected point to all other points, then computing the distance from that point to all other points, as well as the distance from our original point to the newly selected point is O(nk-1). Consider the pseudocode: for pointB in searchSpace do: distanceAB := calculateDistance(pointA, pointB) for pointC in {searchSpace} - {pointB} do: distanceBC := calculateDistance(pointB, pointC) distanceCA := calculateDistance(pointC, pointA) if (distanceAB + distanceBC + distanceCA) < currentMin then: currentMin := distanceAB + distanceBC + distanceCA closestPoints := {pointA, pointB, pointC} Note that we assume that pointA has already been removed from searchSpace. This is an O(n2) algorithm. Assuming dimension is relatively small, or that the function calculateDistance grows linearly or less with the dimension, this gives the solution in a decent time constraint. Optimizations could certainly be had, but they may not be required. If you want to see some real code, wikipedia has many links to implementations. A: Thomas Ahle's Answer does a great job explaining the logic however it does not have the code for the same. Here's a Java Implementation for the same import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class MainClass { static class Point{ double x; double y; Point(double x, double y){ this.x = x; this.y =y; } } static class ComparatorByXCoordinate implements Comparator<Point>{ @Override public int compare(Point P1, Point P2) { if (P1.x > P2.x) return 1; if (P1.x < P2.x) return -1; return Double.compare(P1.y, P2.y); } } static class ComparatorByYCoordinate implements Comparator<Point>{ @Override public int compare(Point P1, Point P2) { return Double.compare(P1.y, P2.y); } } static double DistanceBetweenPoints(Point P1, Point P2){ return Math.sqrt((P1.x-P2.x)*(P1.x-P2.x) + (P1.y-P2.y)*(P1.y-P2.y)); } static double Perimeter(Point A, Point B, Point C){ return DistanceBetweenPoints(A, B) + DistanceBetweenPoints(B, C) + DistanceBetweenPoints(C, A); } public static void main(String[] args) throws IOException { InputStreamReader r = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(r); int n = Integer.parseInt(br.readLine()); Point[] PointsX = new Point[n]; Point[] PointsY = new Point[n]; for (int i = 0; i < n; i++){ String[] st = br.readLine().split(" "); double xCoordinate = Double.parseDouble(st[0]); double yCoordinate = Double.parseDouble(st[1]); Point p = new Point(xCoordinate, yCoordinate); PointsX[i] = p; PointsY[i] = p; } Arrays.sort(PointsX, new ComparatorByXCoordinate()); Arrays.sort(PointsY, new ComparatorByYCoordinate()); System.out.printf("%.12f", solveNoCross(PointsX, PointsY, 0, n)); } static double solveNoCross(Point[] PointsX, Point[] PointY, int low, int high){ if (high - low < 3){ return Double.MAX_VALUE; } else if (high - low == 3){ return Perimeter(PointsX[low], PointsX[low+1], PointsX[low+2]); } int mid = low + (high-low)/2; //Overflow Issues :( Point midPoint = PointsX[mid]; Point[] firstHalf = new Point[mid - low]; Point[] secondHalf = new Point[high - mid]; int firstHalfPointer = 0; int secondHalfPointer = 0; for (Point point: PointY){ double pointX = point.x; double pointY = point.y; double midX = midPoint.x; double midY = midPoint.y; if (pointX < midX || (pointX == midX && pointY < midY)){ firstHalf[firstHalfPointer++] = point; } else{ secondHalf[secondHalfPointer++] = point; } } double min = Math.min(solveNoCross(PointsX, firstHalf, low, mid), solveNoCross(PointsX, secondHalf, mid, high)); return Math.min(min, solveCross(PointY, midPoint, min, PointY.length)); } private static double solveCross(Point[] pointY, Point midPoint, double min, int pointYLen) { // For Solving When There Are Cross Triangles Such That Some Vertices Are in One Half and Some in Other double midX = midPoint.x; double midY = midPoint.y; double MCP = Double.MAX_VALUE; // Minimum Cross Perimeter int boundingFactor = 0; double periRange; ArrayList<Point> pointsInPeriRange = new ArrayList<>(); if (min == Double.MAX_VALUE){ periRange = 2 * 1E9; } else{ periRange = min/2; } for (int FirstPointIterator = 0; FirstPointIterator < pointYLen; FirstPointIterator++){ Point Firstpoint = pointY[FirstPointIterator]; double FirstPointX = Firstpoint.x; double FirstPointY = Firstpoint.y; if(Math.abs(FirstPointX - midX) > periRange) continue; while(boundingFactor < pointsInPeriRange.size() && FirstPointY - pointsInPeriRange.get(boundingFactor).y > periRange) { boundingFactor += 1; } for (int SecondPointIterator = boundingFactor; SecondPointIterator < pointsInPeriRange.size(); SecondPointIterator++){ for (int ThirdPointIterator = SecondPointIterator + 1; ThirdPointIterator < pointsInPeriRange.size(); ThirdPointIterator++){ Point SecondPoint = pointsInPeriRange.get(SecondPointIterator); Point ThirdPoint = pointsInPeriRange.get(ThirdPointIterator); MCP = Math.min(MCP, Perimeter(Firstpoint, SecondPoint, ThirdPoint)); } } pointsInPeriRange.add(Firstpoint); } return MCP; } } The input format is an integer denoting the number of points followed by the points! Sample Run - Input: 4 0 0 0 3 3 0 1 1 Output: 6.650281539873
{ "language": "en", "url": "https://stackoverflow.com/questions/7539623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: iTunes Connect validation I have an app (v1.0) that I uploaded successfully a couple of weeks ago. Now we have updated it (v1.1) but when I try to validate it I get "No suitable applications records were found." I have added the version in iTunes Connect. Targets Bundle version and Bundle version string, short is set to 1.1 In the Organizer, after doing Archive, the two looks the same (except of course for the version number). Thankful for any help. PS. It also doesn't validate the old file that was validated. A: Did you make sure that the status is "ready for upload".
{ "language": "en", "url": "https://stackoverflow.com/questions/7539624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does .pem file contain both private and public keys? I am wondering if PEM-files contain both private and public keys? What does "PEM" stand for? A: You can decode your PEM formatted x509 certificate with the following command: openssl x509 -in cert.pem -text -noout PEM certificate contains public key only or private key only or both. For the following example: -----BEGIN CERTIFICATE----- MIICLDCCAdKgAwIBAgIBADAKBggqhkjOPQQDAjB9MQswCQYDVQQGEwJCRTEPMA0G A1UEChMGR251VExTMSUwIwYDVQQLExxHbnVUTFMgY2VydGlmaWNhdGUgYXV0aG9y aXR5MQ8wDQYDVQQIEwZMZXV2ZW4xJTAjBgNVBAMTHEdudVRMUyBjZXJ0aWZpY2F0 ZSBhdXRob3JpdHkwHhcNMTEwNTIzMjAzODIxWhcNMTIxMjIyMDc0MTUxWjB9MQsw CQYDVQQGEwJCRTEPMA0GA1UEChMGR251VExTMSUwIwYDVQQLExxHbnVUTFMgY2Vy dGlmaWNhdGUgYXV0aG9yaXR5MQ8wDQYDVQQIEwZMZXV2ZW4xJTAjBgNVBAMTHEdu dVRMUyBjZXJ0aWZpY2F0ZSBhdXRob3JpdHkwWTATBgcqhkjOPQIBBggqhkjOPQMB BwNCAARS2I0jiuNn14Y2sSALCX3IybqiIJUvxUpj+oNfzngvj/Niyv2394BWnW4X uQ4RTEiywK87WRcWMGgJB5kX/t2no0MwQTAPBgNVHRMBAf8EBTADAQH/MA8GA1Ud DwEB/wQFAwMHBgAwHQYDVR0OBBYEFPC0gf6YEr+1KLlkQAPLzB9mTigDMAoGCCqG SM49BAMCA0gAMEUCIDGuwD1KPyG+hRf88MeyMQcqOFZD0TbVleF+UsAGQ4enAiEA l4wOuDwKQa+upc8GftXE2C//4mKANBC6It01gUaTIpo= -----END CERTIFICATE----- you will get: Certificate: Data: Version: 3 (0x2) Serial Number: 0 (0x0) Signature Algorithm: ecdsa-with-SHA256 Issuer: C = BE, O = GnuTLS, OU = GnuTLS certificate authority, ST = Leuven, CN = GnuTLS certificate authority Validity Not Before: May 23 20:38:21 2011 GMT Not After : Dec 22 07:41:51 2012 GMT Subject: C = BE, O = GnuTLS, OU = GnuTLS certificate authority, ST = Leuven, CN = GnuTLS certificate authority Subject Public Key Info: Public Key Algorithm: id-ecPublicKey Public-Key: (256 bit) pub: 04:52:d8:8d:23:8a:e3:67:d7:86:36:b1:20:0b:09: 7d:c8:c9:ba:a2:20:95:2f:c5:4a:63:fa:83:5f:ce: 78:2f:8f:f3:62:ca:fd:b7:f7:80:56:9d:6e:17:b9: 0e:11:4c:48:b2:c0:af:3b:59:17:16:30:68:09:07: 99:17:fe:dd:a7 ASN1 OID: prime256v1 NIST CURVE: P-256 X509v3 extensions: X509v3 Basic Constraints: critical CA:TRUE X509v3 Key Usage: critical Certificate Sign, CRL Sign X509v3 Subject Key Identifier: F0:B4:81:FE:98:12:BF:B5:28:B9:64:40:03:CB:CC:1F:66:4E:28:03 Signature Algorithm: ecdsa-with-SHA256 30:45:02:20:31:ae:c0:3d:4a:3f:21:be:85:17:fc:f0:c7:b2: 31:07:2a:38:56:43:d1:36:d5:95:e1:7e:52:c0:06:43:87:a7: 02:21:00:97:8c:0e:b8:3c:0a:41:af:ae:a5:cf:06:7e:d5:c4: d8:2f:ff:e2:62:80:34:10:ba:22:dd:35:81:46:93:22:9a To understand difference between Public Key Algorithm and Signature Algorithm sections read this (both are public). A: A PEM file may contain just about anything including a public key, a private key, or both, because a PEM file is not a standard. In effect PEM just means the file contains a base64-encoded bit of data. It is called a PEM file by allusion to the old Privacy-Enhanced Mail standards which preceded S/MIME as a mail security standard. These standards specified the format of various keys and messages in a particular base64 format. See RFC 1421 for example. Typically a PEM file contains a base64 encoded key or certificate with header and footer lines of the form -----BEGIN <whatever>----- and -----END <whatever>----. Over time there have evolved many possibilities for <whatever>, including private keys, public keys, X509 certificates, PKCS7 data, files containing multiple certificates, files containing both the private key and the X509 certificate, PKCS#10 certificate signing requests, ... RFC 7468 has been written to document this de facto format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: .html() Problem I've been having a little problem getting the .html() function in jQuery to work. Basically, the page gets a bit of HTML via a PHP file using the jQuery post() function, and then it has to insert it into the document. It gets the data from the PHP file fine, it just won't insert it into the document. The snippet of JavaScript code is below. function lookup(inputString,location) { if(inputString.length == 0) { // Hide the suggestion box. var suggestions = '#suggestions'+location; $(suggestions).hide(); } else { $.post( "boatnames.php", {queryString: ""+inputString+"", number: ""+location+""}, function(data){ if(data.length >0) { var suggestions = '#suggestions'+location; $(suggestions).show(); var autosuggestions = '#autoSuggestionsList'+location; $(autosuggestions).html(data); } }); } } function fill(thisValue,location) { var textfield = "#BoatName"+location; $(textfield).val(thisValue); var suggestions = '#suggestions'+location; $(suggestions).hide(); } I am using jQuery 1.6, jQuery UI 1.8.16 and the latest version of jQuery validate. It works on another page, so most likely something I have messed up, but I cannot see it! All scripts are in the <head></head> and the part I want to add the HTML to does exist. A: If I remember correctly, the returned data variable is an object and the actual HTML your page is returning is in the responseText property. You can try this: $(autosuggestions).html(data.responseText); A: When I have this type of problem, the cause is usually either: * *The selector is wrong, i.e., the variable autosuggestions does not hold the value of an actual element ID. (In my case, I've usually made a typo in somewhere.) *The returned data is not valid HTML. So, verify that: * *$(autosuggestions).length !== 0. *typeof data is "string" and that string actually contains HTML. A: jQuery has a function specifically designed for plopping HTML from the server into an element. var autosuggestions = '#autoSuggestionsList'+location; var params = {queryString: ""+inputString+"", number: ""+location+""}; $(autosuggestions).load("boatnames.php", params, function(){ var suggestions = '#suggestions'+location; $(suggestions).show(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7539634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Achievement URL I tried creating an achievement and saw myself having to create a new page with the open graph tags describing the achievements and left the content of the page empty. I was able to register and publish the achievement to a user and finally I was able to click on the achievement. The problem is that when a user sees their friends achievement and clicks on it, they are getting redirected to that empty page that I created that only contains the open graph tags describing the achievement. My expected outcome was that a user would click on the achievement in the ticker, and be redirected to the game, not the actual achievements url. Is this how achievements work? I promise I've clicked on achievements and being taken to the game who published the achievement. A: You can add this meta tag to your achievement html page, to redirect users to your apps. The facebook linter will still be able to register your achievement. <meta HTTP-EQUIV="REFRESH" content="0; url=https://apps.facebook.com/my_apps"> A: One option is to have the empty open graph page redirect to the game via javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome extension - just to save current page into local html file I am new to both Chrome extension development and website techniques (mainly JS). Trying to learn by myself, I wanted to create a Chrome extension that can save the current page, say, to desktop. I know this simply can be done by "Ctrl+S", but I want to implement the same thing as a Chrome extension. If possible, I want to create an extension that first create a popup menu, in which the top row will be the button to save page. I tried to figure it out by myself, however, I got the code below, which is not working. Could you please give me some hints on how to proceed? manifest.json { "name": "Extract", "version": "2.0", "description": "The first extension that I made.", "browser_action": { "default_icon": "icon.png", "popup": "popup.html" }, "permissions": [ "tabs" ] } popup.html <style> body { min-width:357px; overflow-x:hidden; } img { margin:5px; border:2px solid black; vertical-align:middle; width:75px; height:75px; } </style> <script> function saveAsMe (filename) { document.execCommand('SaveAs',null,filename) } </script> Thanks in advance! A: You cannot write files to disk using HTML5 or extensions unless you go native with NPAPI. There are FileSystem APIs that you can use to store it in the Chrome file system. AFAIK, last time I used it it created some GGUID file which you cannot change. For more information regarding this, visit the HTML5 Tutorial regarding Exploring the FileSystem APIs
{ "language": "en", "url": "https://stackoverflow.com/questions/7539647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add a background gradient image from top to bottom? body { color:#999; background-color:#000; font-family:"Helvetica Neue", Helvetica, arial, sans-serif; font-size:11px; line-height:1.8em; background-image: url(../images/bck.jpg); padding:0; margin:0; } How can i modify it to add a gradient background image from the top to bottom of the site? A: /* IE10 */ background-image: -ms-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%); /* Mozilla Firefox */ background-image: -moz-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%); /* Opera */ background-image: -o-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%); /* Webkit (Safari/Chrome 10) */ background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #FFFFFF), color-stop(1, #00A3EF)); /* Webkit (Chrome 11+) */ background-image: -webkit-linear-gradient(top, #FFFFFF 0%, #00A3EF 100%); /* Proposed W3C Markup */ background-image: linear-gradient(top, #FFFFFF 0%, #00A3EF 100%); Edit it as it suits you. A: Mob has a good answer for CSS3. However, if you want to use an image to support older browsers, but want it to repeat in only a certain direction, just use repeat-x or repeat-y, as follows: background: #000 url('../images/bck.jpg') repeat-x; If you'd rather keep your rules separate, just add: background-repeat:repeat-x; to your rules. You can also use 'repeat-y' or 'no-repeat', depending upon your needs. As you saw already, the default behavior is to repeat-all. If you are not worried about legacy support, Mob's answer is a good fit, as it doesn't rely on a fixed image size, and it will always span the proper distance, regardless of the height of your content.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding all characters till it finds the FIRST occurrence of a string given and then keep fetching the rest with preg_match_all $HTML = ' <div class="tsts">CONTENT GOES HERE 1ENDENDENDENDEND<div class="tsts">CONTENT GOES HERE 2ENDENDENDENDEND <div class="tsts">CONTENT GOES HERE 3ENDENDENDENDEND <div class="tsts">CONTENT GOES HERE 4ENDENDENDENDEND '; preg_match_all('%<div class="tsts">([\S\s]+)ENDENDENDENDEND%',$HTML,$matches); I want it to find "CONTENT GOES HERE 1", "CONTENT GOES HERE 2", "CONTENT GOES HERE 3", "CONTENT GOES HERE 4" in the matches By the way I MUST use \s\S because I need to match all kind of characters including special characters, new lines, tabs , but I want it to stop when it finds the ENDENDENDENDEND and get the other results how do I do this? because its only stopping in the last occurence of ENDENDENDENDEND, and I want it to stop in the first one that it finds. so it can match the rest. How do I do this? I tried so much and nothing =X. Thanks very much in advance. A: No, you don't have to use \s\S for that. And the + quantifier is likely the second problem here. The normal .*? will do, if you don't forget the /s flag. In your case a [^<>]*? might be even better, because you don't want to match tag delimiters. A: I don't have php environment, however the point is the express isn't it? see the grep test: kent$ echo "' <div class="tsts">CONTENT GOES HERE 1ENDENDENDENDEND<div class="tsts">CONTENT GOES HERE 2ENDENDENDENDEND <div class="tsts">CONTENT GOES HERE 3ENDENDENDENDEND <div class="tsts">CONTENT GOES HERE 4ENDENDENDENDEND '; "|grep -Po "(?<=<div class="tsts">)([\s\S]*?)(?=ENDENDENDENDEND)" CONTENT GOES HERE 1 CONTENT GOES HERE 2 CONTENT GOES HERE 3 CONTENT GOES HERE 4
{ "language": "en", "url": "https://stackoverflow.com/questions/7539651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to add a progress bar to a gridview i am a beginner in android programming so maybe it's a silly question... I read a lot about async task to add a progress bar but i can't find out the solution i need: I have to show a grid view, but i need to search for data on images and texts to show in it. So if i load the relative data in an array in an asynctask the adapter of the grid doesn't have data and crashes. Otherwise, if i put the progress dialog in the oncreate method of the gridview, it waits the loading of data but don't show the progess bar(it just to at the end of loading data, not during it). So I don't know the correct approach. I thought to start with a previous activity only to show the progress dialog, loading the data, and at the end starting the gridview, but it not seems to me an economic approach... what do you think? So: How can I attach data to the adapter from the asynk task? I tried with notyfydatasetchange but it doesn't work in my onCreate Method i have: mAdapter = new ImageAdapter(this); mGrid.setAdapter(mAdapter); but the same adapter constructor needs data... (al least the number of objects...) and this is my adapter: public class ImageAdapter extends BaseAdapter{ Context mContext; public final int ACTIVITY_CREATE = dirObjList.size()*2; public ImageAdapter(Context c){ mContext = c; map = new HashMap<Integer,SoftReference<Bitmap>>(); } public Map<Integer,SoftReference<Bitmap>> map; @Override public int getCount() { return dirObjList.size(); } public RowData getItem(int position) { return dirObjList.get(position); } public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; RowData currDirObj= getItem(position); if(convertView==null){ LayoutInflater li = getLayoutInflater(); convertView = li.inflate(R.layout.icon, null); holder = new ViewHolder(); holder.tv = (TextView)convertView.findViewById(R.id.icon_text); holder.iv = (ImageView)convertView.findViewById(R.id.icon_image); convertView.setTag(holder); } else{ holder = (ViewHolder)convertView.getTag(); } holder.iv=setThumbs(holder.iv,position); holder.tv.setText(currDirObj.mTitle); convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SharedPreferences indexPrefs = getSharedPreferences("currentIndex", MODE_PRIVATE); SharedPreferences.Editor indexEditor = indexPrefs.edit(); indexEditor.putInt("currentIndex", 0); SharedPreferences drPrefs = getSharedPreferences("currentDir", MODE_PRIVATE); SharedPreferences.Editor drPath = drPrefs.edit(); drPath.putString("currentDir", dirObjList.get(position).mDetail); drPath.commit(); final Intent intent = new Intent(ImageGrid.this, SpeakinGallery.class); startActivity(intent); } }); return convertView; } } and this is my async task public class MyTask extends AsyncTask<Void, Void, String> { ProgressDialog progress; public MyTask(ProgressDialog progress) { this.progress = progress; } public void onPreExecute() { progress.show(); } public String doInBackground(Void...unused) { getSubDirs(startDIRECTORY); return "foo"; } public void onPostExecute(Void unused) { progress.dismiss(); //mAdapter.notifyDataSetChanged(); } } A: AsyncTask is most definitely your friend. I find it works really well to create a member instance of ProgressDialog inside of your AsyncTask class. Let's say you have an Activity class called MyActivity. Create an inner class called DownloadTask. private class DownloadTask extends AsyncTask<Object, Void, Object> { private ProgressDialog dialog; @Override protected void onPreExecute() { dialog = ProgressDialog.show(MyActivity.this, "", "Loading..."); } @Override protected Object doInBackground(Object... params) { // download information and return it return dataObject; } @Override protected void onPostExecute(Object result) { // use result object from background task and // attach data to adapter dialog.dismiss(); } } And then in your onCreate() method, call new DownloadTask().execute();
{ "language": "en", "url": "https://stackoverflow.com/questions/7539653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert swedish characters to opencart tables I just created a script to import a given file (csv) to opencart. The remote server transmits the data as iso-8859-1 and opencart uses utf8_bin collaction as default. My problem is, that the script, where default echo statements show the desired output without problems or weird characters, doesn't submits the data to the database without messing up the special swedish characters. Am example would be the word: Värmepump This definately shouldn't look like that. Any idea what exactly could fail? I already tried to add the SET NAMES 'utf8' query but it didn't help. A: Well, if the data is utf8 encoded, my guess would be there's some issue either in the database or in the database connection. Here's a few debugging tips for you. MySQL database and table character sets/collations (from command line) mysql -u [youruser] [yourdatabase] -p mysql> SHOW CREATE DATABASE [yourdatabase]; mysql> SHOW CREATE TABLE [yourtable]; Everything should be utf8. MySQL database connection (from PHP script) $result = mysql_query("SHOW VARIABLES LIKE '%character%'"); while ($row = mysql_fetch_assoc($result)) { error_log(print_r($row, true)); } Everything should be utf8 here as well. EDIT: Your string is in fact encoded twice. Running a simple echo utf8_decode(utf8_decode('Värmepump'))."\n"; in an ANSI-encoded PHP file outputs the expected "Värmepump". Make sure you encode your data only once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Malloc crashes in recursive function I'm currently coding an implementation of the Burrows-Wheeler Transform which requires sorting a (large) array. Since I want to parallelize parts of the code of a recursive sort function, I decided to allocate some of the local variables in the heap (using malloc()) to prevent stack overflows or - at least- make the program die gracefully. That raised a whole new bunch of issues. I stripped the code down to the essential part (i.e., what causes the issues). The following code compiles without errors. The resulting program works fine when compiled with icc, but it crashes (randomly) when compiled with gcc or tcc. #include <stdlib.h> #include <stdio.h> #include <string.h> unsigned char *block; int *indexes, *indexes_copy; void radixsort(int from, int to, int step) { int *occurrences, *first_index_of, i; if((occurrences = malloc(1024)) == 0) exit(1); if((first_index_of = malloc(1024)) == 0) exit(1); memset(occurrences, 0, 1024); for(i = from; i < to; i++) occurrences[block[indexes[i] + step]]++; first_index_of[0] = from; for(i = 0; i < 256; i++) first_index_of[i + 1] = first_index_of[i] + occurrences[i]; memset(occurrences, 0, 1024); memcpy(&indexes_copy[from], &indexes[from], 4 * (to - from)); for(i = from; i < to; i++) indexes[first_index_of[block[indexes_copy[i] + step]] + occurrences[block[indexes_copy[i] + step]]++] = indexes_copy[i]; for(i = 0; i < 256; i++) if(occurrences[i] > 1) radixsort(first_index_of[i], first_index_of[i] + occurrences[i], step + 1); free(occurrences); free(first_index_of); } int main(int argument_count, char *arguments[]) { int block_length, i; FILE *input_file = fopen(arguments[1], "rb"); fseek(input_file, 0, SEEK_END); block_length = ftell(input_file); rewind(input_file); block = malloc(block_length); indexes = malloc(4 * block_length); indexes_copy = malloc(4 * block_length); fread(block, 1, block_length, input_file); for(i = 0; i < block_length; i++) indexes[i] = i; radixsort(0, block_length, 0); exit(0); } Even when the input is a very small text file (around 50 bytes), the program is very unstable with the latter two compilers. It works with ~50% probability. In the other cases, it crashes in the 2nd or 3rd iteration of radixsort when calling malloc(). It always crashes when the input file is bigger (around 1 MiB). Also in the 2nd or 3rd iteration... Manually increasing the heap doesn't do any good. Either way, it shouldn't. If malloc() can't allocate the memory, it should return a NULL pointer (and not crash). Switching back from heap to stack makes the program work with either compiler (as long as the input file is small enough). So, what am I missing / doing wrong? A: if((occurrences = malloc(1024)) == 0) make that: if((occurrences = malloc(1024 * sizeof *occurences)) == 0) But there are more problems ... UPDATE (the 1024 = 4 * 256 seems merely stylistic ...) for(i = 0; i < 256; i++) first_index_of[i + 1] = first_index_of[i] + occurrences[i]; The [i+1] index will address the array beyond its size;
{ "language": "en", "url": "https://stackoverflow.com/questions/7539657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IE7 and IE8 JS support for Math.floor (or some other method?) I've researched around this subject for quite some time but I can't find out which method or code is causing me problems with IE7 and IE8 - it works fine in IE9, Chrome and FF. Using IE9's F12 tools to debug, the javascript stops at this line with the error object doesn't support this property or method when running IE7 or IE8 mode: pmt = (Math.floor((princ*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100).toFixed(2); The script is located inline, not via a linked file. The pmt variable is not declared prior to this, and it seems to point to the variable as the problem. Would the script benefit from the variable being declared earlier? Thanks in advance. ANSWER: As per the comment by Cory below, the problem wasn't due to any specific method, but simply my failure to add the var declaration before the pmt variable. All sorted now - thanks A: I dont think its a problem with math.floor or IE take a look at this fiddle: http://jsfiddle.net/4ULQL/2 May be you are passing in the wrong parameters and the expression is evaluating to something incorrect and hence the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoiding error 100: invalid parameter (requires valid redirect URI) in application requests dialog I'm developing a game for Facebook. I need a way for users to invite others to the game. For that, I use the apprequests dialog. I redirect the user to the dialog URL, which I glue together like this: $url = "http://www.facebook.com/dialog/apprequests?app_id=".$id."&message=".urlencode("foobar")."&redirect=".urlencode("http://some.arbitrary.url.com"); (Of course, with not-so-arbitrary arguments, but they still look sane to me.) Upon navigating there, the user is scolded by "API Error Code: 100, API Error Description: Invalid Parameter, Error Message: Requires valid redirect URI.". I googled around for a solution, but it seems that all the people receiving this error were forgetting to escape their URLs / messages. I also tried some URLs that should be accepted without remarks, like the application canvas URL. Does anyone know what mistakes am I making? A: So, turns out the solution is to use redirect_uri and not to escape the URL to redirect to, so the code I wrote before should read: $url = "http://www.facebook.com/dialog/apprequests?app_id=".$id."&message=".urlencode("foobar")."&redirect_uri="."http://some.arbitrary.url.com"; A: Try replacing the redirect parameters with redirect_uri A: From my experience with this error; facebook gives you same error whatever the parameter which caused the error. my problem that I didn't use encodeURIComponent(contentParam); for all the parameters so any special character in any parameters gave me the above error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery Tokeninput add if not exists I am in the process of writing a script that builds upon user input, I have some fields that its values need to be quired from the database, and if no entry found I want to add a new value so the next user will find it through autocomplete. I found this great looking & easy to implement jquery plugin called TokenInput, but it doesn't seem to accept entries that are not available in my database query. Here's the link for the plugin: http://loopj.com/jquery-tokeninput/demo.html Is there a workaround for this ? Or do you suggest another plugin that already has this feature. And I'm a little bit concerned about the security aspect of this sort of websites is there something special I need to take care of when doing this sort of implementation ? A: To add to Shawn's answer (i.e. you need something server side to actually add it as a new item in the database), you might be able to make this change to allow the addition on the javascript side of things. A: This is now handled in the latest master of this plugin, using the allowFreeTagging option: https://github.com/loopj/jquery-tokeninput/blob/master/src/jquery.tokeninput.js#L57 The version number and docs haven't been updated in 2 years, so you'll have to use master. A: When you enable tokenInput on a field, $(selector).tokenInput(url, ... that url is where tokenInput sends search queries. It points to a script which returns suggestions based on database entries matching the search query. What you want is to have that script add another suggestion to the list for that case when nothing in your database matches the search query. How to do this depends very much on the script. Because you tagged your question with php, I'm guessing the url points to a php script which returns a JSON object full of suggestions. In that case, modify the php script so that it adds a new suggestion to the list: "{id: " . $idForThisNewSuggestion . ", name: \"" . $searchQueryString . " (new suggestion)\"}" A: Here's my solution with local json $("#input").tokenInput(yourjsondata,{ preventDuplicates: false, onResult: function (item) { if($.isEmptyObject(item)){ return [{id:'0',name: $("tester").text()}] }else{ return item } }, }); Everything with id:0 is a new entry A: I also changed the onBlur function to select the first item if they click off the search box - its more intuitive to users: .blur(function () { $(this).val(""); if ($(".token-input-selected-dropdown-item").length>0) add_token($(".token-input-selected-dropdown-item").data("tokeninput")); hide_dropdown(); }) A: $(document).ready(function() { $("#expert").tokenInput("source.php", { theme: "facebook", noResultsText:'Skill Not Found - Enter to Add', queryParam:'q', onResult: function (item) { if($.isEmptyObject(item)){ return [{id:$("#token-input-expert").val(),name: $("#token-input-expert").val()+'*'}] }else{ return item } }, preventDuplicates:true<?php if($expert_rank_json){?>, prePopulate: <?php echo $expert_rank_json ?> <?php } ?> }); A: In the .php file, before the while condition, you can use this: array_push($yourarray, array('id'=> 0 ,'name'=> $_GET["term"])); A: I have added some functionalities to SteveR's answer, because I wanted the value to appear at the top of the dropdown even if there are results. Also onAdd if the item selected does not exist in the databese I want to add it: $("#my_input").tokenInput(my_results_route), { hintText: "Select labels", noResultsText: "No results", searchingText: "Searching...", preventDuplicates: true, onResult: function(item) { if($.isEmptyObject(item)){ return [{id:'0', name: $("tester").text()}]; } else { //add the item at the top of the dropdown item.unshift({id:'0', name: $("tester").text()}); return item; } }, onAdd: function(item) { //add the new label into the database if(!parseInt(item.id)) { //database insertion ajax call console.log('Add to database'); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7539660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Django CheckboxSelectMultiple with django uni-form I have a form in my django project with a ModelMultipleChoiceField rendered as a CheckboxSelectMultiple widget: class EventCreateForm(forms.Form): ... event_types = forms.ModelMultipleChoiceField(EventType.objects.all(), widget=forms.CheckboxSelectMultiple()) ... I'm using django uni-form to render this form to the page: @property def helper(self): helper = FormHelper() submit = Submit('submit', 'Submit') helper.add_input(submit) helper.form_action = '' helper.form_method = 'POST' return helper However, when django uni-form tries to render the field I get the following error: Caught TypeError while rendering: 'ManyRelatedManager' object is not iterable I know the usual problem with this error is forgetting to call .all() on the manager, however this is being called by django uni-form. Is this a problem with django uni-form or am I doing something wrong? A: I solved my issue. The problem was when I was prepopulating the data, I was passing event.event_types (a manager instance) rather than event.event_types.all().
{ "language": "en", "url": "https://stackoverflow.com/questions/7539662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt QGraphicsView use topleft as scale origin How would I take the topleft corner as seen through the QGraphicsView and keep it the topleft while scaling? So if I happen to have the symbol 'A' in the topleft corner while scaling, the A will stay there yet scales. At present the center of the screen is taking as the scale origin. But I would like the topleft corner be the origin for transformation. That is, topleft as seen in the graphics view, not of the total graphics scene. How would I do this? This is my scale code to scale the scene at 100% of it's width to the viewport: void GraphicsView::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); double scale_delta = (double) event->size().width() / scene()->width(); resetMatrix(); scale(scale_delta, scale_delta); } SOLUTION void GraphicsView::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); if (!first_shown) { centerOn(0, 0); first_shown = true; } QPointF topleft = mapToScene(viewport()->rect().topLeft()); resetMatrix(); QPointF shift = (mapToScene(viewport()->rect().bottomRight() + QPoint(1, 1)) - mapToScene(viewport()->rect().topLeft())); shift /= (double) event->size().width() / scene()->width(); fitInView(QRectF(topleft, topleft + shift)); } A: If I understand your question correctly, the basic steps you'll need are: * *Translate Qt's idea of the origin to where you want to scale around, i.e. top-left *Then apply the scale *Then translate back again
{ "language": "en", "url": "https://stackoverflow.com/questions/7539665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ communication between objects I'm sure this kind of question has been asked (and answered) before, so please link me to a previous discussion if so... In C++, say I have an object of type ClassA which includes a private member variable object of type ClassB. How would I go about calling a reference to the ClassA object within ClassB? I am using the Observer Design Pattern where the ClassA object is the 'subject' and an object within ClassB, say of type ClassC, is an 'observer' of the ClassA object. Therefore when initialising object ClassC within ClassB one of its parameters needs to be a reference to its 'subject' object. A: Briefly: struct A; struct B : C { B(A &a) : c(a) { } C c; }; struct A { A() : b(*this) { } private: B b; }; B gets no special access to A just because it is a member. You must explicitly pass the reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ScrollView setOverScrollMode replacement in API < 9 From documentation, ScrollView.setOverScrollMode() is available in API from version 9 What can I use in API version 7 and 8 as replacement? A: Overscrolling hints didn't exist pre-gingerbread. So, aside from rolling your own, there's no replacement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7539674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }