text
stringlengths
8
267k
meta
dict
Q: Freezable.IsFrozen and DependencyObject.IsSealed What is the difference between those two? Aren't they semantically equivalent? A: No. Freezable.IsFrozen can be toggled (one time) from outside the class by calling the Freeze() method, DependencyObject.IsSealed is read-only and its value can only be set internally by the class itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why is my PHP script sending blank emails? When I render it on the server side after uploading, I get an email but it is blank. The From is blank the text is blank the part in ECHO where $name is comes out blank. Any ideas what I can do to make this work? Here is my form: <form action="survey.php" method="post" name="survey"> <table>`enter code here` <tr><th colspan="2">Survey</th></tr> <tr><td>Name:</td><td align="center"><input type="text" name="name" id="name" /></td></tr> <tr><td>When was your last visit</td><td align="center"><select id="long" name="long"> <option value="Select">Please Select</option> <option value="1-2 days">1-2 days ago</option> <option value="3-5 days">3-5 days ago</option> <option value="1-2 weeks">1-2 weeks ago</option> <option value="3-5 weeks">3-5 weeks ago</option> <option value="2 months">2 months</option> <option value="3+months">3+ months </option> <option value="Never">Never Visited</option> </select></td></tr> <tr> <td>Tell us about your experience?</td><td align="center"><textarea cols="22" rows="5" id="experience" name="experience"></textarea></td></tr> <tr><td>Will you come back to visit again?</td><td align="center"><input type="checkbox" id="visit" name="visit" value="Yes" />Yes<input type="checkbox" id="visit" name="visit" value="No" />No</td></tr> <tr><td colspan="2"><input type="submit" value="Submit" /><input type="reset" value="Reset" /></td></tr> </table> </form> And my PHP code <?php /* subject and e-mail variables*/ $emailSubject = $name; $webMaster = 'patrick@patrickspcrepair.com'; /* Gathering data Variables */ $nameField = $_POST['name']; $selectField = $_POST['long']; $commentsField = $_POST['experience']; $visitField = $_POST['visit']; $body = <<<EOD <br><hr><br> Name: $name<br> Date of last visit: $long<br> Expierence: $experience<br> Visit again: $visit<br> EOD; $headers = "From: $name\r\n"; $headers .= "Content-type: text/html\r\n"; $success = mail ($webMaster, $emailSubject, $body, $headers); /* Results rendered as HTML */ /* When changing the fields please leave the <<<EOD and the EOD; If they are deleted this form will not work */ $theResults = <<<EOD <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Coupon</title> <script language="javascript" type="text/javascript"> var d=datetime.getDate() var datetime=new Date() var day=datetime.getDay() var month=datetime.getMonth() var year=datetime.getYear() if (year < 1000) year+=1900 var days=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") var months=new Array("January","February","March","April","May","June","July","August","September","Octomber","November","December") </script> <style type="text/css"> #frame { position:absolute; top:16px; left:124px; height:355px; width:480px; border:2px dotted red; font:"Trebuchet MS", Veranda, sans-serif; color:red; padding: 10px; } </style> </head> <body> <div id="frame"> <h3 align="center">Thanks for Participating in our survey, $name!</h3> <p align="center">Here is a special offer for you:</p> <h2 align="center">Free Egg Roll!</h2> <p align="center">Please print out this coupon to recieve a free egg roll with the purchase of a meal.</p> <p>&nbsp;</p> <p>&nbsp;</p> <p style="font-size:x-small">Limit one coupon per visit. Coupon valid at all locations. Coupon will expire one month after date on coupon. Cannot be combined with other offers or promotions. Management has the right to refuse this coupon if found to be altered, copied, or fraudulent. Coupon Number : <script> function fakecounter(){ //decrease/increase counter value (depending on perceived popularity of your site!) var decrease_increase=50000 var counterdate=new Date() var currenthits=counterdate.getTime().toString() currenthits=parseInt(currenthits.substring(2,currenthits.length-4))+decrease_increase document.write(" # <b>"+currenthits+"</b>") } fakecounter() </script></p> </div> <script language="JavaScript" type="text/javascript"> document.write(days[day]+", "+months[month]+" "+d+" "+year) </script> <form><input type="button" value=" Print this page " onclick="window.print();return false;" /></form> </body> </html> EOD; echo "$theResults"; ?> A: From is blank because you have written $headers = "From: $name\r\n"; and $name is not declared anywhere. Change this to $headers = "From: $nameField\r\n";. The same can be said for references to $long (should be $selectField), $experience (should be $commentsField) and $visit (should be $visitField). As for echo "$theResults";: * *Why bother storing the HTML in a string to then echo it out? Just drop out of PHP mode and start outputting the HTML directly. *Why surround the variable $theResults in quotes? echo $theResults; is better, adding the quotes creates a new string in memory first, then echos it. A: Your are echoing fields that you did not declare... try adding extract($_POST); to the begining of your code A: How is your error reporting set? Does it print or go to a log? Echo phpinfo() to see. Your log will tell you a lot. In the following line I noticed that you have a space between "mail" and "(". There should be no space. $success = mail ($webMaster, $emailSubject, $body, $headers); If you are watching your error log you will catch things like this that are easy to miss.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to import a dll into a asp.net web application running on webserver I have a dll created in VS 2010. i put it into the app_code folder on the webserver and then i accesses it by trying to use imports GetWebPageData the dll is in the vs project under bin/debug if that means anything A: You need to copy the DLL to the bin (instead of app_code) folder of the web server, and even better - click on Add Reference on the Web Site in Visual Studio and add your DLL as a reference. And you should also probably read some more about ASP.NET fundamentals Here is an article that explains ASP.NET compilation in detail: http://www.west-wind.com/presentations/AspNetCompilation/AspNetCompilation.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7598843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Document is used being other tabs In my firefox addon. I have two tabs open in my browser, when I try to access the "document" after a interval/timeout, in one of the tabs, I grab the document of another tab instead... For example: Tab 1, document.title is: "Test page" Tab 2, document.title is: "Second tab" I run a script in tab 1: setTimeout(function(){alert(document.title)}, 5000). Should alert "Test Page", but the alert shows "Second tab". Here my script: gBrowser.addEventListener("DOMContentLoaded",function(e){ window = e.originalTarget.defaultView; document = window.document; setTimeout(function(){ alert(document.title); }, 5000); }, true); This only happends when I open the first tab, then a open the second. The same thing happens when I try to change any dom element. Also happend when a user click on a button. How to avoid that? This could be a bug with firefox or is with me? A: Don't forget to declare local variables: gBrowser.addEventListener("DOMContentLoaded",function(e){ var window = e.originalTarget.defaultView; var document = window.document; setTimeout(function(){ alert(document.title); }, 5000); }, true); Undeclared variables are automatically global and in particular can change between now and when your timeout runs (never mind lots of other nasty side-effects). Even better: switch on strict mode. It will make sure that this mistake produces a visible error and doesn't go unnoticed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make IIS server work with Zend I am trying to make my site work with the IIS I have installed on the server. I also have plesk control panel installed. I am trying to: * *make it look for the index.php inside the public folder and not just the httpdocs folder. *make the mod_rewrite work (i've extracted everything out of the public folder to the httpdocs folder to check if that would work, and it does load the basic page, but can't find anything else and says that file was not found on server). A: There is a number of links about this that can help you find your way. As @Mathieu said, mod_rewrite works only for the Apache server, not for IIS. You'll need something like IIS URL Rewrite for that. The following links seem to contain quite accurate information: * *http://framework.zend.com/wiki/display/ZFDEV/Configuring+Your+URL+Rewriter Hope that helps, A: First of all mod_rewrite is only for unix-style servers, .htaccess doesn't work with IIS. So you'll have a lot of problem with ANY MVC framework which offer routing via htaccess. Second, IIS and PHP have many performance issues and many functions work differently from live PHP/UNIX environments. First thing (Unless they changed it) you can't use / for file paths and must change all your paths for \ (escape the backslash) which becomes cumbersome or use PHP_DS constant and clutter your code... Suggestion, use an apache based server, apache CAN be installed on windows. Finaly, in IIS you can simple point your website directory into the public folder, but you might need to allow pĥp to move backwards in your directory structure if you use the ISAPI module. I remember once that ASP had to allow backward access in files to get out of the root folder of your IIS website. If you use the CGI version of php with IIS, you will probably NOT have this issue. later
{ "language": "en", "url": "https://stackoverflow.com/questions/7598849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I convert Bayer to RGB using OpenCV and vice versa OpenCV provided function to convert Bayer to RGB, but how to use this CV_BayerBG2BGR , and other similar function? I used code below, but the error appears stated invalid channel number. Since I use RGB image as originalImage, anyway how this function actually works? void main(){ // Declare and load the image // Assume we have sample image *.png IplImage *originalImage = cvLoadImage("bayer-image.jpg",-1); // The image size is said to be 320X240 IplImage *bayer2RGBImage; bayer2RGBImage = cvCreateImage(cvSize(100,100),8,3); cvCvtColor(originalImage,bayer2RGBImage,CV_BayerBG2BGR); //Save Convertion Image to file. cvSaveImage("test-result.jpg",bayer2RGBImage); //Release the memory for the images that were created. cvReleaseImage(&originalImage); cvReleaseImage(&bayer2RGBImage);} Furthermore, I'd like to convert common RGB image to bayer format (let say bilinear) too, whether openCV provide this function as well? any help would be really appreciated. Thanks in advance. A: Unfortunately OpenCV does not provide BGR to Bayer conversion. Only backward conversion is available. If you need a conversion to Bayer format then you should implement this conversion yourself or use another library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My hot-deploying (toy) server: need your design inputs (homework) from multiprocessing import Process a=Process(target=worker, args=()) a.start() I am making a multiple worker-process app (don't laugh yet) in which each worker can gracefully reload. Whenever the code is updated, new requests are served by new worker processes with the new code. This is such that * *A newly launched thread contains updated code *ensure that no requests are dropped I already made a worker that listens: * *serves requests when it gets aa request signal *kills itself when the next signal is a control signal I did it in zeromq. The clients connect to this server using zeromq. The clients do not interact by HTTP. What is a good way to reload the code? Can you explain a scheme that is simple and stupid enough to be robust? What I have in mind/ can do Launch a thread within the main process that iterates: * *Signal every worker process to die *Launch new worker processes But this approach will drop (I configured it that way) requests between the death of the last old worker and the spawning of the first new worker. And no, I am not a college student. The "homework" just means a curiosity-driven pursuit. A: Reloading code in python is a notoriously difficult problem. Here's how I would deal with it: * *at server startup, listen on your HTTP port (but do not start accepting connections) *Use multiprocessing or some such to create some worker processes; this should happen after the socket starts listening so that the subprocesses inherit the socket. *each worker can then accept connections and service requests. *when the parent process learns that it should reload, it shuts down the listening socket. *when a worker tries to accept a closed socket, it recieves a socket.error exception, and should terminate *the parent process can start a new main process (as in subprocess.Popen(sys.argv)) the new process can start accepting connections immediately. *the old process can now wait for the child workers to finish; the children cannot accept new connections (since the listening socket is shutdown). Once all child process have finished handling in-flight requests and closed, the parent process can also terminate. A: The way that I did this in python is fairly simple but depends on a middleman or message broker. Basically, I receive a message, process it and ack it. If a message is not acked, then after a timeout the broker requeues it. With this in place, you simpy kill and restart the process. In my case the process traps SIGINT and does an orderly shutdown. However it dies, the supervisor notices that the worker has died and starts a new one, which continues processing messages from the queue. I was inspired by Erlang's supervision tree model where everything is designed to survive the death of a process. I even made my workers send a heartbeat to the supervisor periodically (ZeroMQ PUB to supervisor SUB) so that the supervisor can kill and restart a process if it hangs for any reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple CRUD Generation This is what I have: * *An entity-relational schema, modelled for Doctrine 2.0 (in PHP); *The generated database, on a MySQL server. This is what I want: A very basic CRUD web-interface to the database, that allows me to (you guessed it!) create, read, update and delete records, with extra credit for implementing CRUD operations on entities and relations instead of records. Now, I'm terrible at writing web applications myself (read: I'm lazy). Are there any options to generate a CRUD web application from a MySQL database, or from a set of Doctrine entities? * *I'd be willing to stop using PHP (and thus rewrite the entities for JPA, Ruby ActiveRecord, etc...) but not MySQL. *I see a lot of similar questions: however, most of these questions have answers that give CRUD operations for in PHP code, or recommend using Doctrine. *An answer such as "There is no such tool, stop being lazy" would also be appreciated. A: You should have a look at Grocery CRUD. Really simple, easy to use /deploy and neat UI. http://www.web-and-development.com/grocery_crud/ I did a complete web CRUD of my DB in a couple of hours (including additional PHP webservices) Amazing :-) A: Symfony does this (at least the 1.x series I am used to). I should think version 2.0 also does, under either Doctrine or Propel (and both of those will work with MySQL). A: CakePHP (user guide) takes a database model and generates controllers that do basic CRUD operations for all of your tables. It also includes views and a basic stylesheet. A: If your hosting setup can handle Python, the web2py framework offers instant CRUD for a database and a very user friendly (and laziness-friendly) online dev environment. I don't think it's designed to be laid overtop of an existing database, but you can import a CSV file with your database contents. http://www.web2py.com One of the great things about web2py is that creating custom (public) CRUD pages is also dead easy. In a controller file it's as easy as form = CRUD.create(db.myTable) return dict(form = form) Then in a view file you just add {{=form}} And that's it! All of the form creation, input validation, etc., is handled for you. I should also add that the data abstraction layer in web2py is very easy to learn and meshes with mySQL easily. One great thing about it is that web2py performs on-the-fly changes to your datastructure or even migrations from one DB back-end to another. Not every hosting company knows how to support web2py, but it's easy to deploy on the Google App Engine or with a company like Fluxflex.com A: I've been looking for a drop-in admin panel like this too, so far I've 3: AjaxCrud - http://ajaxcrud.com/ Peek from Code Canyon - http://bit.ly/toKKrB SQLBuddy - http://www.sqlbuddy.com/ Love to hear any other suggestions! A: Ruby on Rails' "Scaffolding" should be exactly what you're looking for... A: As according to this answer, I've tried Xataface, which gave me as decent a result as CakePHP or Web2Py would have given me. Am now trying Symfony 2.0 (which is a lot harder then I'd have expected) for the extra credit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: vaadin: moving data from selected row of table1 to table2 I have two questions: * *I have two tables, table1 and table2. I need to design an application in such a way that a selected row of table 1 when clicked should get displayed in table 2. *How do I call a custom table? Suppose I have a class Table with empty constructor and I will pass arguments like Table(pagination). It has to show the table with pagination, Similarly, Table(lazyloading) has to show lazy loading table. Table(pagination, Lazy loading,search) must show all three properties. A: What you have to do for nr 1 is that you attach a Clicklistener to your table1 and on a Clickevent you take the selected Object ni table1 and add it to table2. Also add an if to not add rows that already exist in table 2. This is how you copy data public void copydata(){ Object o = table1.getValue(); if(!table2.getItemIds().contains(o)) table2.addItem(o); table2.setContainerDataSource(table2.getContainerDataSource()); } When it comes to your second question I have no clue what you are talking about, but I looks like you want to extend the Table class in vaadin to get your own features.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: CSS style override default textbox border to create invisible border? I want to display a text box in css/razor without the border (well, as white background) but it's picking up the color value from it's parent. Q: How can I override the default value in the parent css style so my textbox value looks like a label (white background color)? input[type="text"], input[type="password"], select { border: 1px solid #93A9C8; } .TextBoxAsLabel { border: none; background-color: #fff; background: transparent; } -- Called from razor page -- @Html.TextBoxFor(m => m.ImpToDate, new { @class = "TextBoxAsLabel" }) A: try: input.TextBoxAsLabel This makes your class more specific and will probably override the previous one. A: Simply change the border value from none to 0 (zero)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to use oauth with facebook problems Im trying to use this code to start building a simple facebook app but I cant seem to get to grips with the access token part so i can get the users birthday etc. Can someone please take a look and let me know what im doing wrong : <?php $app_id = "*********"; $canvas_page = "https://apps.facebook.com/hotness-battle/"; $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page) . '&scope=email,user_birthday'; $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); if (empty($data["user_id"])) { echo("<script> top.location.href='" . $auth_url . "'</script>"); } else { $token_url = 'https://graph.facebook.com/oauth/access_token?client_id=200482573356726&redirect_uri=http://www.impact25.com/hotness-battle/&client_secret=*******&code='.$data['oauth_token'].''; echo("<script> top.location.href='" . $token_url . "'</script>"); $uid = $data["user_id"]; $token = $data['oauth_token']; $full_name = json_decode(file_get_contents('http://graph.facebook.com/'.$uid))->name; $gender = json_decode(file_get_contents('http://graph.facebook.com/'.$uid))->gender; $birthday = json_decode(file_get_contents('http://graph.facebook.com/'.$uid.'?access_token='.$token))->birthday; echo $full_name; echo '<br><br>'; echo $gender; echo '<br><br>'; echo $token; echo '<br><br>'; echo $cookie['access_token']; } A: Okay, obviously you just copied the above code from somewhere...here are a couple of tips: * *Read the Canvas Tutorial *The second OAuth request is not needed ($token_url) since if the user authorized your app you'll have the access_token in the signed_request *Don't do multiple graph calls, one call will retrieve everything you need *Don't print the access_token to the user *Make secure calls to the graph ( https ) Here is a working code to get you started: <?php $app_id = "APP_ID"; $canvas_page = "https://apps.facebook.com/appnamespace"; $auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page) . '&scope=email,user_birthday'; $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); if (empty($data["user_id"])) { echo("<script> top.location.href='" . $auth_url . "'</script>"); } else { $uid = $data["user_id"]; $token = $data['oauth_token']; $graph_url = 'https://graph.facebook.com/' . $uid . '?access_token=' . $token; $user_info = json_decode(file_get_contents($graph_url)); $full_name = $user_info->name; $gender = $user_info->gender; $birthday = $user_info->birthday; echo $full_name; echo '<br><br>'; echo $gender; echo '<br><br>'; echo $birthday; echo '<br><br>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cast in IntentService::handleIntent the CustomResultReceiver passed as an intent extra I am trying to cast the Intent::extraParcelable received, to my custom RestResultReceiver like this public class APIHttpV1Service extends IntentService { ... protected void onHandleIntent (Intent intent) { final int apiCall = intent.getIntExtra("uri"); final RestResultReceiver resultReceiver = intent.getParcelableExtra(RestResultReceiver.EXTRA_ID_RESULT_RECEIVER); // check if the uri is correct if( apiCall == -1) { // TODO call failed as we didn't provide any URI resultReceiver.send(RestStatus.ERROR, Bundle.EMPTY); } ... } } and this is the RestResultReceiver public class RestResultReceiver extends ResultReceiver { private static final String TAG = "com...RestResultReceiver"; public static final String EXTRA_ID_RESULT_RECEIVER = "com...RestResultRecevier.Receiver"; private Receiver __mReceiver; public RestResultReceiver(Handler handler) { super(handler); } public void clearReceiver() { __mReceiver = null; } /** * Set the receiver * @param receiver the object getting called back using onReceiveResult */ public void setReceiver( Receiver receiver ) { __mReceiver = receiver; } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (__mReceiver != null) { __mReceiver.onReceiveResult(RestStatus.getEnum(resultCode), resultData); } else { Log.w(TAG, "Dropping result on floor for code " + resultCode + ": " + resultData.toString()); } } public void send(RestStatus resultStatus, Bundle resultData) { super.send(resultStatus.getCode(), resultData); } /** * Interface to implement for objects doing rest service call */ public interface Receiver { public void onReceiveResult(RestStatus resultStatus, Bundle resultData); } } At runtime I have a java.lang.ClassCastException exception. I am just wondering why I can get my RestResultReceiver. If I use final ResultReceiver resultReceiver = intent.getParcelableExtra(RestResultReceiver.EXTRA_ID_RESULT_RECEIVER); it doesn't throw any error but I can't call my custom send function obviously. Any idea? Thx a lot for any help you could provide :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to generate IIS7 CSR (for SSL) from C# code or using Powershell on server which IIS is running How I can generate a server SSL Certificate Signing Request (CSR) from C#? If PowerShell is a better option, that would be a good solution as well. A: Some general pointers: * *http://msdn.microsoft.com/en-us/library/aa382488%28VS.85%29.aspx *http://msdn.microsoft.com/en-us/library/aa382820%28VS.85%29.aspx *http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx *http://blogs.msdn.com/b/alejacma/archive/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c.aspx *http://learn.iis.net/page.aspx/144/how-to-set-up-ssl-on-iis-7/ EDIT - as per comments: The COM object CertEnroll provided by MS can be accessed via PowerShell... A: I know it's three years later, but the links in Yahia's solution state that they will not work for Server 2008. Using PowerShell, I was able to use Certreq.exe, which ships with Server 2008, to generate the CSR. The documentation for Certreq is here, along with the full format for the INF file. Of course, substitute your own values for the distinguished name. The letters correspond to these fields: * *CN: Common Name *O: Organization *OU: Organizational Unit *L: City/locality *S: State/Province *C: Country/region The script assumes you have an environment variable named TEMP that points to a directory for which you have write access: $reqFile = 'C:\ChangeMe\Request.req' Push-Location $env:TEMP @" [NewRequest] Subject = "CN=www.contoso.com, O=Contoso Inc, OU=Sales, L=Redmond, S=Washington, C=US" ProviderName = "Microsoft RSA SChannel Cryptographic Provider" KeyLength = 2048 MachineKeySet = true FriendlyName = "www.contoso.com" [RequestAttributes] CertificateTemplate="WebServer" "@ | Out-File .\request.inf -Encoding default -Force certreq -f -new request.inf `"$reqFile`" Pop-Location For those who are new to PowerShell, the @" and "@ delimiters must not be indented. (These define what is known as a "Here-String"... more information here.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Way to detect if String content is a DateTime - RegExp? Possible Duplicate: generically parsing String to date Following situation: I need to detect if a String contains a DateTime/Timestamp. The problem is that those DateTimes come in various formats and granularity such as: 2011-09-12 12-09-2011 12.09.2011 2011-09-01-14:15 ... and many many more variations I don't need to understand the semantics (e.g. distinct between day or months) I just need to detect let's say 80% of the most common DateTime variations. My first thought was using RegExp - which I'm far from being familiar with and also I would need to familiarize myselft with all variations in which DateTimes can come. So my questions: * *Does anybody know a canned RegExps to achieve this? *Is there maybe some Java library that could do this task? Thanks!! A: There is another question of same context, hope that link will help you: Dynamic regex for date time formats A: Use Java's DateFormat. You can set up as many formats as you want and iterate through them looking for a match. You will have to catch exceptions for the formats that don't parse and so this solution is not efficient but will work. Edit per comment: If you don't want to have exceptions due to performance the you would need to set up a list of regular expressions (one for each format you will support). Find the regex (if any) that matches your input and convert it to a date based on the matching format. What I would suggest would be to match a DateFormat to each regex and let the appropriate DateFormat do the work of parsing once you have identified the appropriate DateFormat. This would reduce the chance of errors in using the groups from the regex to produce the date. Personally, I don't know if this would actually be more efficient than try/catch so I would opt for the more straightforward mechanism (using DateFormat directly). A: you're going to struggle to find a generic match. For the day - month - year section you could possibly use a pattern like (\d{1,2}.){2}\d{4} which would match dates in format dd*mm*yyyy DateFormat would be a better choice, I think. As John B suggested above, create a list of valid formats and try to match against each one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP MySQL PDO::exec raises or throws no error for multi-command scripts When executing a multi-command script (for instance, a few CREATE TABLE commands and perhaps a few INSERT commands), particularly with the MySQL PDO driver for PHP, the return is always 0 (without any error info) even if the script contains errors - syntax or logic. This prevents you from running a long build script and then checking to see if the script was executed successfully or not. If an error occurs, the process terminates at the point where the script fails, but still exists with 0 and no error information. I have searched this site and the net for an answer to this question, and it seems that the general response is "there's nothing you can do about it". My current solution is to run a "verify build" query that checks for some data and assesses the response to that - this seems terribly inefficient. Has anyone come across this problem? If so, how have you ensured the build script was executed successfully? A: Thanks for everyone's answers - I did not find a solution to this, instead ended up using Doctrine, which tied in nicely with database migration. A: As a workaround, could you split the string that contains the script by ; and execute each statement individually? You can then isolate any issues down to a particular statement. At php.net, PDO::exec doesn't mention returning false on failure, but PDO::query does. A: Just create a stored function which will run your script, your function should return a value in case of a success and use a selection instead of execute. This way you'll know whether your script was successful. You can delete your installation function if the command terminated with success. A: You can get the info for each separate command using a construct like: do { // do something with your current rowset } while($pdo->nextRowSet());
{ "language": "en", "url": "https://stackoverflow.com/questions/7598888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Storing a large variable in HTML5 persistent storage from an action run in a PHP script I will begin by briefing as to what this actually should do... Fetch the entire contents of a web page, turn into a string, and save into persistant storage. However for some reason, it just... wont? Ive used php's html entities, and then JSON Stringify, however it just fails to work. My code is as follows... //arrays set above $url = "http://www.google.co.uk"; $handle = fopen($url, "r"); $contents = stream_get_contents($handle); $contents = htmlentities($contents); echo "<script lang='text/javascript'>var dataString = JSON.stringify('".$contents."'); tokens[".$t." = ".$rowtokens[5]."]; toStore[".$t." = dataString]; alert('CONTENT'); </script>"; EDIT : That source code renders the following <script lang='text/javascript'>tokens[0 = tokenvalue here]; toStore[0 = "&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD X... //All the rest of the html of the page. "];localStorage.setItem(token[0], toStore[0]);</script> A: You mean: tokens['".$t."'] = '".$rowtokens[5]."'; Currently it is evaluating to: tokens[something = test]; which is invalid and does not do what you want: * *Everything is happening inside the property name; nothing is being set *You don't have quotes which will probably mess up things If your code returns this: <script lang='text/javascript'>tokens[0 = tokenvalue here]; toStore[0 = "&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD X... //All the rest of the html of the page. "];localStorage.setItem(token[0], toStore[0]);</script> then it's not valid: * *It's <script type='text/javascript'> *I don't know what you mean with 0 = tokenvalue here (you're storing something in the number 0, which is not possible). Don't you mean tokens[0] = tokenvalue? *There are newlines, so you should remove them as you currently have an unterminated string A: Found the solution after a quick search Common sources of unterminated string literal It was the line breaks from php code that was killing it. This fixed it nicely $str = str_replace(array("\r", "\n"), '', $str);
{ "language": "en", "url": "https://stackoverflow.com/questions/7598889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filter divs depending on numeric quantity entry I'm trying to set up a filter using jQuery. I'll have a certain amount of divs, each with a numeric value (let's say price). I want to have a textbox and button that filters out any divs that are higher than the value given. So for instance, if I enter 10 and hit filter, all divs with a numeric value of 10 or above are hidden. I can only find filter scripts that are executed via buttons like this, but none of those use a numeric value. Any help is greatly appreciated. Please bear in mind that my JavaScript skills are limited! A: Maybe something like this, iterate thru the each div that has a class of prices Get the value, parse it as an int, compare it to textbox with the id of myTextBox $('div.prices').each(function() { var value = parseInt($(this).text()); if (value >= parseInt($('#myTextBox').val())) $(this).hide(); else $(this).show(); }) jsFiddle A: Here is the thing: http://jsfiddle.net/SMPAq/1/ UPDATE: Ok, here is the whole thing: <script> function sortmebaby() { var divList = $('#containerMonkey div[id^="monkey_"]'); $.each(divList, function(index, value) { console.log($(value).attr('xprice')); if ( $(value).attr('xprice') > $('#mankipower').val()) $(value).hide(); else $(value).show(); //alert(index + ': ' + value); }); } </script> <div id="containerMonkey"> <div id="monkey_1" xprice="1">1</div> <div id="monkey_2" xprice="2">2</div> <div id="monkey_3" xprice="3">3</div> <div id="monkey_4" xprice="4">4</div> <div id="monkey_5" xprice="5">5</div> </div> <input type="text" name="mankipower" id="mankipower"> <input type="button" value="PUSH" onclick="sortmebaby()">
{ "language": "en", "url": "https://stackoverflow.com/questions/7598890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Key value table to view with variable columns I have my data in a key-value table (in MySql) which has the shape: id, key, value Now for export to my users I need to transform it into a table with all the keys as columns. (actually only ~20 of the ~100 keys need to be in that table) The workflow would be to provide it my users so that they can correct the table and to reimport the tables. I'm just in writing a quite complex select command to give me such a table. It already is some heck of long command and I hope it will not need to be debugged. I can't help but think this should be an already solved problem ;) So I'm hoping anyone can provide me with some clues. A: So far I hacked together a script that will construct a view. DROP PROCEDURE IF EXISTS view_test; DELIMITER // CREATE PROCEDURE view_test() BEGIN DECLARE done INT DEFAULT 0; DECLARE curr_prop VARCHAR(31); DECLARE curr_table VARCHAR(31); DECLARE fixed_prop VARCHAR(31); DECLARE statement_a LONGTEXT DEFAULT 'SELECT pd.id,t0.date'; DECLARE statement_b LONGTEXT DEFAULT "FROM xxx.codes AS pd INNER JOIN xxx.eav AS t0 ON (pd.id = t0.idX)"; DECLARE n_prop INT DEFAULT 0; DECLARE cur1 CURSOR FOR SELECT DISTINCT prop FROM xxx.eav LIMIT 59; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; OPEN cur1; main_loop: LOOP FETCH cur1 INTO curr_prop; IF done THEN LEAVE main_loop; END IF; SET fixed_prop = curr_prop; SET fixed_prop = REPLACE(fixed_prop,'-','_'); SET fixed_prop = REPLACE(fixed_prop,'+','_'); SET fixed_prop = REPLACE(fixed_prop,' ','_'); SET n_prop = n_prop + 1; SET curr_table = CONCAT('t',n_prop); SET statement_a = CONCAT(statement_a,',\n',curr_table,'.value AS ', fixed_prop); SET statement_b = CONCAT(statement_b,' \nLEFT JOIN xxx.eav AS ',curr_table, ' ON (',curr_table,'.idX=pd.id AND t0.date=',curr_table,'.date AND ',curr_table,'.prop="',curr_prop,'")'); END LOOP; -- cleanup CLOSE cur1; SET @S = CONCAT('CREATE OR REPLACE VIEW auto_flat_table AS\n',statement_a, '\n',statement_b, '\nGROUP BY pd.id,t0.date'); -- ,'\nGROUP BY pd.id' PREPARE stmt_auto_demo FROM @S; EXECUTE stmt_auto_demo; DEALLOCATE PREPARE stmt_auto_demo; END // DELIMITER ; CALL view_test(); That will create such a view for myself - though I'm a bit confused why this GROUP BY is neccesary. Not being a SQL developer I'm pretty sure I took the long way in this program. Also that I'm only able to use 61 tables for joins is a bummer. I think we will soon need more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom membership provider for asp.net I want to use NauckIT asp.net membership provider for Postgres. I was playing with example and I managed to register/login/logout user. However, This membership provider also has role management, but i dont know how to use it. My question is: Is it possible to use ASP.NET Configuration utility (the one you start from menu Project>ASP.NET Configuration) to create roles and users? How do I achieve this? If this is not possible, Is there any other way to do this (besides inserting/update roles/users directly to Postgres DB - this is not much user friendly) Thank you in advance A: Roles are managed by a RoleProvider in ASP.Net I would imagine if it has a custom Membership provider, then it would also have a custom role provider as well. If this is the case, then you can certainly use the out of the box Management Pages for ASP.Net as it simply uses the Role and Membership providers that are already defined. It would appear that NauckIT does in fact have a role provider. Again, the management pages should work just fine if following the instructions in the link above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenGL not show result from secondary thread on iPhone I created EAGLContext and use it in the secondary thread. But there is no output displayed. The same code works fine if run in main loop. Do I need to notify somewhere on each render completion? A: EGL Context may be only active in one thread. You need to use eglMakeCurrent(). Also, you need to use eglSwapBuffers() once your rendering is done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SELECT unique row from field 3 to field 4 Is there a way to delete duplicate records based on two fields? I have a system where people can register for sport events. In the table: event_registrations • unique_id • eventname • id (person's id number) • Name and Surname One person can apply for many events - id may duplicate an event may have multiple participants - eventname may duplicate: --Johnsmith-- --Mountain Cycle-- --Johnsmith-- --Marathnon Walk-- --Linda-- --Mountain Cycle-- --Johnsmith-- --Mountain Cycle-- But a person may not register for a event they have already registered for: --Johnsmith-- --Mountain Cycle-- --Johnsmith-- --Mountain Cycle-- They Select a event name through a form. Then the form data and their user details is stored in table event_registrations. Any help would be appreciated A: First delete any rows with duplicate (eventname, id) combinations. Then add the UNIQUE constraint: ALTER TABLE yourTable ADD CONSTRAINT eventname_person_Unique UNIQUE INDEX eventname_id_U (eventname, id) ; Your form that adds registrations should be adjusted accordingly to treat the error it will get from MySQL when a duplicate row is rejected. A: A UNIQUE INDEX is the way to prevent this, as ypercube suggests. To identify/delete existing duplicates you could use this: SELECT eventname, id -- You should consider using a less ambiguous name here FROM Event_Registrations ER1 WHERE EXISTS ( SELECT * FROM Event_Registrations ER2 WHERE ER2.eventname = ER1.eventname AND ER2.id = ER1.id AND (ER2.registration_datetime < ER1.registration_datetime OR (ER2.registration_datetime = ER1.registration_datetime AND ER2.unique_id < ER1.unique_id ) ) ) A: If you need to do some data tidy up before adding the unique constraint then you could use the following (one good reason why always having a unique id column is a good idea): create table id_for_deletion (id int unsigned not null); insert into id_for_deletion (id) ( select a.delete_me_id from ( select eventname,id,max(unique_id) as delete_me_id from event_registrations group by eventname,id having count(*) > 1 ) a); delete from event_registrations where unique_id in (select id from id_for_deletion); drop table id_for_deletion;
{ "language": "en", "url": "https://stackoverflow.com/questions/7598909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: deleting Rows in rich:extendedDataTable I have a rich:extendedDataTable. I have a a4j:commandLink for each row, on click of this the row should get deleted. The problem what I am facing is, if I go on deleting the first rows the (firstRow+1)second row's value is set in the backing bean and always the second row is getting deleted. xhtml code is <a4j:commandLink id="acceptbtn" action="# {archiveOrderBean.acceptOrder}" styleClass="beforeSelect" title="#{mnOrdrMsgs.startitle}" onclick="animateRow(this);" reRender="auftragListNew"> <f:setPropertyActionListener value="#{archive}" target="#{archiveOrderBean.currentOrder}" /> <f:setPropertyActionListener value="#{row}" target="#{archiveOrderBean.currentRow}" /> <h:graphicImage value="/images/tick.png" style="border:0;vertical-align: top;" /> <a4j:support event="onclick" reRender="newclassification" onsubmit="javascript:blockFullScreen('Loading...Please wait');" oncomplete="javascript:myJQuery.unblockUI();" /> </a4j:commandLink> I also tried rerendering the table but still the value in the UI is not in sync with the backing bean data. Does anybody have a solution to this. I do not know if this is problem with richfaces 3.3.3 version. In addition to the action I also have the jquery code which flickers the row and removes the complete <tr>. Any help on this will be really helpful. A: The JQuery slide toggle removes the <tr> from the rich:extendedDataTable and when the deleteObject is done on the backing of rich:extendedDataTable it removes always the second row since the first tr is already removed by JQuery which is not rendered. I could manage to do this in 3 steps w.r.t a4j:commandLink * *onClick attribute: RowFlicker JQuery *action attribute: Remove the object from the backingbean List and reRender Table *oncomplete attribute: RowRemove using JQuery
{ "language": "en", "url": "https://stackoverflow.com/questions/7598911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show hide div in one area I have been looking all day to try and find something that matches what I want but I cant find anything anywhere. I want to create a show hide div that shows / hides the div in one fixed area. I want a gallery of thumbs on half my page and in the other half of the page I want to display the full profile associated to that thumb, so when i click on another thumb the previous thumb's div disappears and the new thumbs div appears in its place. I am looking to achieve something like this: (just how the text appears on the left hand side when you click on a thumb) http://www.tcsdigitalworld.com/team I have already achieved something simular on another website where the image swaps but I want to add text to this and show more content such as a profile. You can see what I have done there here: http://www.dansiop.com/epbs/index.php/brides/gowns/paloma-blanca.html If anyone can point me in the right direction I would really appreciate it. Many thanks UPDATE: Thank you all for your input but I am a bit of a massive n00b when it comes to javascript. I have tried doing all of these on the site that I want it to go on and I cant get any of them working. I can get some of them working at some point but not as it should. The closest I got it working was using the sample that Ernestas Stankevičius offered But as you can see it isnt quite working as when I click on the thumb they disappear - it doesnt do it on the link above but it does on my site. I am also not sure where I place what content to make it work. Where do I place the thumb src and where do i place the profile content, main image etc? I call this is my header: <script> $(document).ready(function(){ $('.thumb').click(function(){ $('#main').fadeOut(500).html($(this).children('.bla').html()).fadeIn(200); }) }); </script> I set this in my css (not what I want in the end but its a start as you sugested: #main { color: red } .bla { display: none } .thumb { cursor: pointer; background-color: blue; height: 100px; width: 100px; margin: 5px } and I use this html: <div id="main">sdfsdfsdf</div> <div class="thumb"> <div class="bla">asdasdasd1</div> </div> <div class="thumb"> <div class="bla">asdasdasd2</div> </div> <div class="thumb"> <div class="bla">asdasdasd3</div> </div> <div class="thumb"> <div class="bla">asdasdasd4</div> </div> Just to clarify, when I click on the thumbs the text changes as I want it to but the thumbs disappear (not as I want it to) Thanks in advance. Dan A: To expand a bit on richardneililagan answer... Here is a bit of extra HTML and some JS: <div id="leftpane"> <img class="thumb" id="img_1" /> <img class="thumb" id="img_2"/> <img class="thumb" id="img_3"/> <img class="thumb" id="img_4"/> </div> <div id="rightpane"> <div id="prof_1" class="profile">Profile for image 1</div> <div id="prof_2" class="profile">Profile for image 2</div> <!-- etc --> </div> Then you can have somehting like this to handle your events: $(".thumb").click(function() { var id = $(this).attr("id").split("_").pop(); $(".profile").fadeOut(); $("#prof_" + id).fadeIn(); } Hope that helps! Edit Ok, based on the code I wrote before, this is working (tested here: http://jsfiddle.net/deleteman/94jQS/) HTML <div id="leftpane"> <a class="thumb" href="#"><img id="img_1" src="http://img1.jarfil.net/3/test_iq-pixels_5x5_v1-a.png"/></a> <a class="thumb" href="#"><img id="img_2" src="http://www.kriptopolis.org/images/clasifica.jpg"/></a> <a class="thumb" href="#"><img id="img_3" src="http://www.blogdetrabajo.com/wp-content/uploads/test.jpg"/></a> </div> <div id="rightpane"> <div id="prof_1" class="profile">Profile for image 1</div> <div id="prof_2" class="profile">Profile for image 2</div> <div id="prof_3" class="profile">Profile for image 3</div> </div> CSS a.thumb img { width:100px; } .profile { display:none; } JS $(".thumb").click(function() { var id = $(this).children("img").first().attr("id").split("_").pop(); $(".profile").fadeOut('slow'); $("#prof_" + id).fadeIn(); return false; }); Is that better now? Would that work for you? A: That would be pretty easy if you've got HTML structured like a grid. <div id="leftpane"> <img class="thumb" /> <img class="thumb" /> <img class="thumb" /> <img class="thumb" /> </div> <div id="rightpane"> <!-- and the profile information goes here --> </div> ... 'cause that way, you can just target that whole #rightpane with a jQuery selector. $('#rightpane').children().hide(); A: There's a bunch of ways you could achieve this. You could store all the information you want to display in the full-sized window in a data object (for instance, an array containing objects, the objects have fields for title, desription text, and image.) Then you generate the thumbnails so that when you click on them, they call a function that takes an index of the array as an arguement. You can then generate new HTML using some string substitution method and insert it into the full-sized div (after removing the old content) by using InnerHTML. A: Need some imprvment, but u get the idea, I think. http://jsfiddle.net/qS5U5/ A: I didn't look at the source code of the example site you ghave, but it's unlikely that there are multiple divs that are hidden and shown, it's probably just one div, which is hidden, then the innerHTML is changed and then faded-in. It should be something like $("#theDivThatIsClicked").click(function() { $("#theDivThatWillContainTheText").hide(function() { $(this).html("add some text").show() }) });
{ "language": "en", "url": "https://stackoverflow.com/questions/7598919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Gtk::Widget on_enter_notify when mouse is down? I'm trying to have a list of Gtk::Widgets that when clicked on I need to highlight the widget, but when the user holds the button down, and drags to another widget, the first one will 'unhighlight' and the new one will highlight on enter_notify. I've tried using the on_enter_notify_event, and on_button_press_event in multiple combinations ( yes, I'm adding the events ), but every time I 'press' the widget, it starts a drag event, and enter_notify and leave_notify won't fire. Is there a way to ignore the drag event? I've tried ending it when it starts, but I think the problem is the on_notify won't trigger with the mouse down. Is there another way of doing it? Any help or suggestions would be greatly appreciated. A: Okay, apparently when a widget gets activated or clicked, the GdkDevice 'grab()'s the widget and only sends events to THAT widget. So I've taken the device from the event, and called 'ungrab()' on it so it allows the other cells to receive events. Then on my other cells I check the event->state in the on_enter_notify_event to see if the mouse is down, and voila! The cell is highlighted. bool cell::on_button_press_event(GdkEventButton* event) { highlight_cell(); gdk_device_ungrab(event->device, event->time); return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Object DataSource I'm trying to use an ObjectBindingSource to bind data to a gridview. The data is present in the view as a subclass as the controller, in the form of a model. var _controller = new DataController(param1, param2); you would access it in this manner foreach(var Variable in _controller.DataModel.Cars) <%: Car.Name %> ... How can I use this DataModel.Cars as the source for the Object binding source? I currently have <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Choices.ChoiceService.ChoiceCollection" DataObjectTypeName="Choices.ChoiceService.ChoiceObject" InsertMethod="Add" SelectMethod="AsReadOnly"/> A: Insert a Select Method on DataController say GetCars this way you would do: public class DataController { public IEnumerable<Car> GetCars(int param1, int param2) { return this.DataModel.Cars; } } and then you would use: <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="Choices.ChoiceService.DataController" DataObjectTypeName="Choices.ChoiceService.Car" SelectMethod="GetCars"> <SelectParameters> <asp:SessionParameter Name="param1" SessionField="param1" /> <asp:SessionParameter Name="param2" SessionField="param2" /> </SelectParameters> </asp:ObjectDataSource> You then set the session on the codebehind witht: Session["param1"] = 12; Session["param2"] = 13; Note:There are much better ways to do this, using the session like this is really ugly, this is only an example. You probably can pick a better one from the following list: http://msdn.microsoft.com/en-us/library/xt50s8kz.aspx Alternatively you can use the OnDataBinding event of the ObjectDataSource to programatically set the parameters directly on the ObjectDataSource instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can a disconnected TCP socket be reliably detected using MsgWaitForMultipleObjects? Twisted includes a reactor implemented on top of MsgWaitForMultipleObjects. Apparently the reactor has problems reliably noticing when a TCP connection ends, at least in the case where a peer sends some bytes and then quickly closes the connection. What seems to happen is: * *The reactor calls MsgWaitForMultipleObjects with some socket handles and QS_ALLINPUT. *The call completes and indicates the handle for a socket in this state (that is, has bytes waiting to be read and has been closed by the peer) is active. *The reactor dispatches this notification to the common TCP implementation. *The TCP implementation reads the available bytes from the socket. There are some, they get delivered to application code. *Control is returned to the reactor, which eventually calls MsgWaitForMultipleObjects again. *MsgWaitForMultipleObjects never again indicates that the handle is active. The TCP implementation never gets to look at the socket again, so it can never detect that the connection is closed. This makes it appear as though MsgWaitForMultipleObjects is an edge-triggered notification mechanism. The MSDN documentation says: Waits until one or all of the specified objects are in the signaled state or the time-out interval elapses. This doesn't sound like edge-triggering. It sounds like level-triggering. Is MsgWaitForMultipleObjects actually edge-triggered? Or is it level-triggered and this misbehavior is caused by some other aspect of its behavior? Addendum The MSDN docs for WSAEventSelect explains what's going on here a bit more, including pointing out that FD_CLOSE is basically a one-off event. After its signaled once, you'll never get it again. This goes some way towards explaining why Twisted has this problem. I'm still interested to hear how to effectively use MsgWaitForMultipleObjects given this limitation, though. A: In order to use WSAEventSelect and differentiate activities, you need to call WSAEnumNetworkEvents. Make sure you're processing each event that was reported, not just the first. WSAAsyncSelect makes it easy to determine the cause, and is often used together with MsgWaitForMultipleObjects. So you might use WSAAsyncSelect instead of WSAEventSelect. Also, I think you have a fundamental misunderstanding of the difference between edge-triggered and level-triggered. Your reasoning seems to be more related to auto-reset vs manual-reset events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to set a connection just for server callbacks and a connection just for client calls using WCF ? I don't think I was clear. What I meant was How to set a callback("server to client") in a different connection from a "client to server" connection using WCF ? I always saw callbacks examples using just one DuplexChannelFactory. This implies using only one TCP connection to make client to server calls and receive server to client callbacks. This question came to me after I read this this topic: Seeking WCF Duplex "TwoWay" Subscribe+Callback Example I the top answer, Ian Ringrose said: Some rules I found to help avoid deadlocks. (Look at my WCF questions to see the pain I had!) The sever must never call out to a client on the same connection as a call from the same client is in process on. And/or The client must never call back to the server on the same connection as is used for the “callbacks” while processing a call-back. And I was wondering how to implement it using WCF. A: This CodeProject on Robust Interapplication Communications using Double-Simplex WCF answers exactly your question: What I decided to do was run two separate WCF connections (double simplex). Each application would run a WCF Host for incoming messages and each application would run a WCF Client for outgoing messages. This is a pretty robust solution and will not be broken by stopping and starting the applications. The WCF Client simply re-establishes the connection if needed. The way it is solved meets the requirements you have extracted from the Ian Ringrose answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting records in order of the number of records that contain a certain field We have a table that is arranged as such: ID, Album_ID and Time_Voted. Each time a user votes, it creates a new record. We'd like to display the top five Album_IDs, (which had the most records containing that Album_ID at the end of every week). The only way I know how to do this is to SELECT all records from the past week, then run a "while" on the results,then iterate through an array and and add a +1 to the corresponding Album_ID key each time it finds an instance of the same Album_ID. This is quite inefficient, and I'm convinced there's a good way to do this via SQL query, but it's beyond my level of knowlege. So the question is, is there a way to, via query, get a count of each number of album_IDs, and then arrange by that count? Here's the original SQL statement I was working with. The YEARWEEK stuff was just to get last week. SELECT * FROM wp_album_votes WHERE YEARWEEK( Time_Voted ) = YEARWEEK( CURRENT_DATE - INTERVAL 7 DAY ) ORDER BY Album_ID A: SELECT Album_ID, COUNT(*) AS NumVotes FROM wp_album_votes WHERE YEARWEEK( Time_Voted ) = YEARWEEK( CURRENT_DATE - INTERVAL 7 DAY ) GROUP BY Album_ID ORDER BY NumVotes DESC LIMIT 5 A: select album_id, count( album_id ) from wp_album_votes group by album_id order by 2 desc. you can wrap your other text and dates onto this basic structure...
{ "language": "en", "url": "https://stackoverflow.com/questions/7598953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to retrieve the value of a kvp in c sharp, using the text of the key? I have various values and names stored in a db table, that my code will use for various tasks. These are read into a kvp , so that I can get to the right value from its key when I need to. As far as I've seen so far, getting to the value using the index of the key is easy, but can I get in via the name of the key instead kvp["name of key"].value for instance? I know any key/values stored in the config files can be accessed as ConfigurationManager.AppSettings["queryLoadJobDataDetails"] but as I need to read these values in as I go, adding them to web.config is a bit pointless! A: I'm just Guessing what you need here: using System.Collections.Generic; // IDictionary<string, object> kvps = new Dictionary<string, object>(); kvps.Add("something", 42); kvps.Add("else", "entirely"); object i = kvps["something"]; string s = kvps["else"] as string; Also look at TryGetValue: object v; if (kvps.TryGetValue("missing", ref v)) Console.WriteLine("Not missing: {0}", v);
{ "language": "en", "url": "https://stackoverflow.com/questions/7598954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create wsp package from powershell Please help, how to create wsp package from powershell? I know how to build solution, but I don't know how to emulate command Package, which exists for WebPart projects in project item context menu. Thank you! A: I guess this is what you want. set-alias msbuild C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe msbuild /t:package **[.csproj file]** Regards, Pedro
{ "language": "en", "url": "https://stackoverflow.com/questions/7598955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Look up GWT CellTable header style/s? How can TH style name/s of a GWT CellTable's heading be looked up programatically? I have looked at the Client Bundle documentation but it isn't immediately obvious to me how it all fits together. Thanks. A: Not sure exactly what you want to do when accessing the TH style names. If you want to override the standard css style of a celltable header, here are some of the css styles you can override to change the Look and Feel of the component. .cellTableFirstColumnHeader {} .cellTableLastColumnHeader {} .cellTableHeader { border-bottom: 2px solid #6f7277; padding: 3px 15px; text-align: left; color: #4b4a4a; text-shadow: #ddf 1px 1px 0; overflow: hidden; } .cellTableSortableHeader { cursor: pointer; cursor: hand; } .cellTableSortableHeader:hover { color: #6c6b6b; } .cellTableSortedHeaderAscending { } .cellTableSortedHeaderDescending { } Here is the complete list of styles for cellTables CellTable.css Now if you want to access you header programmatically, you can use this solution to get the TableSectionElement corresponding the the Header of your table. Then you can access the row, then the cells, and lookup for their styles I guess. Last thing if you want to override the header style, maybe you can use the following method when adding your column to your table public void addColumn(Column<T, ?> col, Header<?> header) Then create your Header or use a TextHeader for example then set your style on it before adding it to the table using public void setHeaderStyleNames(String styleNames) Example TextHeader textHeader = new TextHeader("headerTitle"); textHeader.setHeaderStyleNames("my-style"); myTable.addColumn(myColumn, textHeader); A: Easy solution: import com.google.gwt.user.cellview.client.CellTable.Resources; private String getCellTableHeaderStyle() { Resources res = GWT.create(Resources.class); return res.cellTableStyle().cellTableHeader(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Password-protect folder with web.config I have to password protect a directory on a Windows server. The page is supposed to show a list of files located in that directory. I don't have any previous knowledge (only worked with Apache before) so I've tried hacking something together by googling. (For someone who knows what they're doing I'm sure this will look ridiculous) What I have right now is I get a login-popup but no password is working. We have a table in our SQL database for adminusers so either fetching user-login from there or having the login embedded in the config file is fine. All I need is the folder to be password-protected. This is what I have right now in my web.config file that is located in the folder that is supposed to be password-protected. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.web> <authentication mode="Forms"> <credentials passwordFormat="Clear"> <user name="test" password="test" /> </credentials> </authentication> <authorization> <allow users="test" /> <deny users="*" /> </authorization> </system.web> <system.webServer> <directoryBrowse enabled="true" /> <security> <authentication> <anonymousAuthentication enabled="false" /> <basicAuthentication enabled="true" /> <windowsAuthentication enabled="false" /> </authentication> </security> </system.webServer> </configuration> Hopefully this is a simple problem and thanks in advance for any help! :) A: Try this: <configuration> <system.web> <authentication mode="Forms"> <credentials passwordFormat="Clear"> <user name="test" password="test" /> </credentials> </authentication> <authorization> <allow users="test" /> <deny users="*" /> </authorization> </system.web> <location path="admin"> <system.web> <authorization> <allow roles="admin" /> <deny users="*"/> </authorization> </system.web> </location> <system.webServer> <directoryBrowse enabled="true" /> <security> <authentication> <anonymousAuthentication enabled="false" /> <basicAuthentication enabled="true" /> <windowsAuthentication enabled="false" /> </authentication> </security> </system.webServer> </configuration> You can encrypt the user information using something like this: aspnet_regiis.exe -pef "sectionName" C:\Path\To\Your\Application
{ "language": "en", "url": "https://stackoverflow.com/questions/7598957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Is it possible to have two indexes in a coldfusion for-loop? <cfscript> for(firstIndex = 1, secondIndex = 1; firstIndex > 10, secondIndex > 5; firstIndex++, secondIndex++) WriteOutput('First Index:' & firstIndex & 'Second Index:' & secondIndex & '<br>'); </cfscript> obviously this code doesn't work, but is there a way to do this in CF or do I just have to create my own second variable in the loop and do if(secondIndex > 5) break; secondIndex++; A: Loops in CF may not have more that one index. The quickest way to do what you want is use a conditional loop: <cfscript> firstIndex = 1; secondIndex = 1; while (firstIndex < 5 && secondIndex < 10) { WriteOutput('First Index:' & firstIndex & ' Second Index: ' & secondIndex & '<br/>'); firstIndex++; secondIndex++; } </cfscript> BTW, your > signs will want to be < that signs--otherwise your above code will never iterate through a single loop. A: Not like you're doing it, no. Use a nested loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Identity From Multiple Inserts I think I already know the answer but... Given this statement: Insert Into Allergy (Name, Category, Composition) Select Name, Category, Composition From ETVault Where Strain In (6, 2, 4) Is it possible to get the identities that were inserted? I understand I can break this into multiple statements and capture scope_identity() after each but that's not what I'm asking. A: The first way I thought of doing this is to use a AFTER INSERT TRIGGER on the table, capture the entire rowset inserted, and get the identities from there. EDIT Of course, you can do this by capturing OUTPUT (doh) http://msdn.microsoft.com/en-us/library/ms177564.aspx Here is a working sample, Since you hadn't provided sample data, I created my own Allery and ETVault tables, so use the example in a brand new database. DROP TABLE Allergy GO CREATE TABLE Allergy ( ID INTEGER IDENTITY (1, 1), NAME VarChar (20), Category VarChar (20), Composition VarChar (20) ) GO DROP TABLE ETVault Go CREATE TABLE ETVault ( ID INTEGER IDENTITY (1, 1), Strain INT, NAME VarChar (20), Category VarChar (20), Composition VarChar (20) ) GO INSERT INTO dbo.ETVault ( Strain, NAME, Category, Composition ) VALUES ( 1, '1', '1', '1'), ( 2, '1', '1', '1'), ( 3, '1', '1', '1'), ( 4, '1', '1', '1'), ( 5, '1', '1', '1'), ( 6, '1', '1', '1'), ( 7, '1', '1', '1'), ( 8, '1', '1', '1') DECLARE @CaptureTable TABLE (ID INT) INSERT INTO dbo.Allergy ( NAME, Category, Composition ) OUTPUT INSERTED.Id INTO @CaptureTable SELECT dbo.ETVault.NAME, Category, Composition FROM dbo.ETVault Where Strain In (6, 2, 4) SELECT * FROM @CaptureTable It gives you the output (8 row(s) affected) (3 row(s) affected) ID ----------- 1 2 3 (3 row(s) affected)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Float to Char Array to std::string I'm having a bit of a problem with this piece of code: string StringServices::ToStringf(float value) { char buffer[10]; sprintf (buffer, "%f", value); return (string) buffer; // signal SIGABRT } Its been working previously and continues to work for other calls, but I currently get a SIGABRT on the return, when the function is being passed -211.0 The buffer loads up fine, and I'm really not sure why this isn't working. Can someone who understands std::string and c strings a lot better then me help me out here? A: You probably overflowed your buffer because you're not using snprintf. You have this tagged C++ so do it that way: std::string buffer = boost::lexical_cast<std::string>(value); Or without boost use a string stream: std::ostringstream os; os << value; // os.str() has the string representation now. A: The main problem with C and its string functions is that you have to do too much work manually. You also have to make too many decisions when you write in C. One of the trivial issues is buffer overflow. Consider this code: char buf[5]; // 5 chars, ok sprintf(buf, "qwert"); // 5 letters, ok You're going to have problems with this code, since when talking about strings, 5 chars means 4 letters + '\0'. So, you may try: printf("'%s'\n", buf); // you'll probably get 'qwertIOUYOIY*&T^*&TYDGKUYTU&*#*#T^&#$T67...' What you do with your code is a trivial buffer overflow :-) sprintf() just has no way to check the size of buf, so a piece of memory that goes right after buf can get corrupted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Properties in c++ in a book i am reading to learn basic c++, there is this example: #include <iostream> using namespace std; class Point { private: // Data members (private) int x, y; public: // Member functions void set(int new_x, int new_y); int get_x(); int get_y(); }; void Point::set(int new_x, int new_y) { x = new_x; y = new_y; } int Point::get_x() { return x; } int Point::get_y() { return y; } My question is, is it not possible in c++ to include the definition of the member functions inside the class itself? The above seems quite messy. The book says to define a class member function you should use 'return_type class_name::function(){arguments}. But in C# you can just do it within the same class and it is less code. I haven't been able to find much about properties in c++. Thanks for help. A: Although it is possible, it's not really recommended. Actually, the way it's done in your book isn't how it should be done either (and hopefully, later on in the book that will change!). The way you'll see it done 99% of the time (yes, I pulled that number out of my ass) is a class definition in a header file (.h extension) and the definitions in a source file (.cpp extension). The header file will be imported so to speak, into the source file via #include. A: You can define the members within the class as such. class Point { private: // Data members (private) int x, y; public: // Member functions void set(int new_x, int new_y) { x = new_x; y = new_y; } int get_x() { return x; } int get_y() { return y; } }; However, this isn't a popular style of coding in C++. Most C++ conventions suggest that you separate the implementations (definitions) from the interface (the declarations) in different files (definitions would go into Point.cpp, and declarations would go into Point.h), unless the definitions are very short (like accessors). A: You can define functions in the class definition in C++. This will cause them to be inline implicitly but that shouldn't matter because compilers have flexibility in terms of actually inlining. Usually this isn't done because it will increase compile time due to larger amounts of code being processed and the canonical C++ way it to put the method definitions in a separate source file. A: class Point { private: // Data members (private) int x, y; public: // Member functions void set(int new_x, int new_y) { x = new_x; y = new_y; } int get_x() { return x; } int get_y() { return y; } }; A: of course you can write #include <iostream> using namespace std; class Point { private: // Data members (private) int x, y; public: // Member functions void set(int new_x, int new_y) { x = new_x; y = new_y; } int get_x() { return x; } int get_y() { return y; } }; But whole point is to separate declaration and implementation. A: Yes we can Define a function inside a class.it has following advantage. 1)the function which you define inside a class is treated as an "inline" function . (inline keyword before any function suggest compiler to place body of the definition of the function to where ever that function is been called from at compile time) 2)due to which inline function execute Faster.then normal function. (remember its totally up to the compiler to make that function inline or not.you cannot force compiler to make it inline) A: Most answers point out that it is possible but not recommended, I do not agree with the latter. For simple one-liner accessors it just makes sense to provide them inside the class definition in most cases: class point { int x,y; public: // ... int posX() const { return x; } int posY() const { return y; } }; As of the setters, it will depend on whether you want to verify any invariant or not. In the former case, you might want to move it to a single translation unit, but even there if the checks are small I would just inline them inside the class definition. The recommendations for separating declaration and definition of the member methods include things like: * *smaller compile time: false, the compiler can parse the accessor trivially, it will not add much more to the parsing *smaller code size: false, if the function is not inlined, then the compiler must generate code for the function call, including calculation of the this pointer and actually perform the call. The inlined accessor will just require the reading of the member which will take less code. *higher compile time coupling: any change in the implementation of the function will require recompilation of all translation units that include the header... True, if you change the function, which for such a simple accessor will not happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex to get the text after first "space"? Here a string I need to parse using regex. http://carto1.wallonie.be/documents/terrils/fiche_terril.idc?TERRIL_id=1 Crachet 7/12 In fact this is an url followed by 1 space and a text. I need to extract url and the text in 2 separate ways. To extract the url \S+ is working just fine. But to extract the text after first space, it gets really hard to understand. I am using Yahoo Pipes. (I don't know if this link to edit the code will work) EDIT: Using (\S+) (.+) gives me something weird: A: According to the Pipes documentation, it looks like it uses fairly standard regex syntax. Try this: ^(\S+)\s(.+)$ Then the URL will be $1 and the comment will be $2. The . operator matches any character, which you will need since it looks like the comments may have spaces. EDIT: changed from literal space to \s since you might be looking at some odd whitespace character(s). You might as well throw a ^ and $ in there too, so the match fails instead of doing something weird.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the name of a property in c# Given this class: public class MyClass { public int MyProperty {get; set;} } How will I be able to extract the name of MyProperty in code? For example, I am able to get the name of the class like this typeof(MyClass).Name How can I do something similar for the property? The reason for the question is that I want this particular code to be resistant against refactorizations of the names. EDIT: With resistant I mean that I want the code at the call site to be robust in the face of changes of the propertyname. I have some stuff that is using a string representation of the property name. Sorry for the poor phrasing. I did not include call site code in order to keep the problem clean and not wander off into other discussions on the nature of the call site code. A: You do it like this, using compiler generated expression trees: public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess) { return ((MemberExpression)memberAccess.Body).Member.Name; } Now call the static method from code: class MyClass { public int Field; public string Property { get; set; } } var fieldName = GetMemberName((MyClass c) => c.Field); var propertyName = GetMemberName((MyClass c) => c.Property); // fieldName has string value of `Field` // propertyName has string value of `Property` You can now also use refactoring to rename that field without breaking this code A: In C# 6 we can do it very simply nameof(MyField); you can get method\type\propery\field\class\namespace names in the same way ex nameof(MyClass); nameof(namespacename1) // returns "namespacename1" nameof(TestEnum.FirstValue) // returns enum's first value MSDN Reference Look at this post A: You could use the following class which contains a method using an expression tree as an argument to determine a member name based on a lambda expression: public class MemberHelper<T> { public string GetName<U>(Expression<Func<T, U>> expression) { MemberExpression memberExpression = expression.Body as MemberExpression; if (memberExpression != null) return memberExpression.Member.Name; throw new InvalidOperationException("Member expression expected"); } } Then use it like so: MemberHelper<MyClass> memberHelper = new MemberHelper<MyClass>(); string name = memberHelper.GetName(x => x.MyField); A: If you only want to get name of an instance member, you can use shorter code: public static string GetMemberName<TValue>(Expression<Func<TValue>> memberAccess) { return ((MemberExpression)memberAccess.Body).Member.Name; } And use it like the following inside the class: ReflectionTools.GetMemberName(() => _someInstanceVariableOrProperty) A: With C# 6.0, you can use the new nameof operator. nameof(MyClass.MyField) // returns "MyField" nameof(MyClass) //returns "MyClass" See nameof (C# and Visual Basic Reference) for more examples. A: Using Reflection you can find all Members from MyClass with this. MemberInfo[] members = typeof(MyClass).GetMembers(); Now you can find your desired property for each Member. foreach ( MemberInfo memberInfo in members) { Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField Console.WriteLine("Member Type: {0}", memberInfo.MemberType); // Member Type: Property } If you want to find only Properties use PropertyInfo instead of MemberInfo. Or write this foreach ( MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property)) { Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField Console.WriteLine("Member Type: {0}", memberInfo.MemberType); // Member Type: Property } A: If you don’t want to waste your time, try the following one. I know there will be people run into the same problem. // Soner - tested! foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(item)) { string name = descriptor.Name; // Name object value = descriptor.GetValue(item); // Value var type = descriptor.PropertyType; // Type Console.WriteLine($"{name}={value}={type}"); } Don’t forget to add using System.ComponentModel;.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: html/css: making map 100% height for any monitor So I have this map I am trying to configure so that it takes the height of any monitor it displays on: http://www6.luc.edu/test/cabplan/maps/index2.html All the CSS is in the file, I have tried height 100% (that erases it completely), I tried position absolute (that throws the map over the top banner), I tried min-height with height 100% (it just takes the min-height). I am not sure what I am doing wrong. Also in the code the map shows that its 895 by 400, which is weird cause it does not look 895px, which I increase using Firebug it grows to the left but I cannot move the map left. I have tried float left, margin 0, margin-left 0 but nothing happens. Can anyone help me with the HTML/CSS edits? A: Have a look at this thread: Resize div on browser resize Be sure you are setting your body and html to 100% height as well. With the footer involved, you will set the bottom property to the height of your footer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Format with leading zeros in Erlang I would like to return the local time as string but with leading zeros. I tried this: {{Year, Month, Day}, {Hour, Minute, Second}} = erlang:localtime(). DateAsString = io_lib:format("~2.10.0B~2.10.0B~4.10.0B~2.10.0B~2.10.0B~2.10.0B", [Month, Day, Year, Hour, Minute, Second]). But if some of the components is one digit, the returned string is: [["0",57],"29","2011","17","33","34"] The current month 9 is printed as ["0",57]. Please, help. Thank you. A: Try: 1> lists:flatten([["0",57],"29","2011","17","33","34"]). "09292011173334" io_lib:format/2 (and it's companion io:format/2) actually returns a deep IO list. Such a list is printable and can be sent on a socket or written to a file just as a flat string, but is more efficient to produce. Flattening is often useless, because in all cases where the string will be printed or output to a file/socket it will automatically be flattened by Erlang. A: You want to be using something like this: DateAsString = io_lib:format("~2..0w~2..0w~4..0w~2..0w~2..0w~2..0w", [Month, Day, Year, Hour, Minute, Second]). The more common w format modifier does the right thing here, what with base and such, so there's no need to use the more complex B modifier. 2..0 says "2 characters wide, zero padded, no precision specified." We don't need precision here, since we're dealing with integers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: File not found - Google Safe Browsing Lookup API I try to make a browser call to https://sb-ssl.google.com/safebrowsing/api/lookup? With and without the API key, etc, but each time and no matter what I do, I get: File not found Firefox can't find the file at https://sb-ssl.google.com/safebrowsing/api/lookup?. Check the file name for capitalization or other typing errors. Check to see if the file was moved, renamed or deleted. Any ideas what might be the problem? A: The URL you are using is AFAIk from the Google Safebrowsing API V 1 which used to support GET requests and is now deprecated (and will be taken offline by December 1st) - I strongly recommend switching to V2 of the API which from what I gather only supports requests via POST. EDIT: SORRY - I overread the "Lookup" part... I just checked the URL you gave... From Firefox (latest version) I can confirm what you describe... OTOH when I try it via IE the result is different - it comes back with HTTP 403 which I assume is due to the fact that I don't have a valid key... I can only conclude that Firefox does something Google won't accept - it can be related to User agent or whatever... have you tried this with a simple wget or some http client component/class ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7598985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I troubleshoot a WCF service with failing load tests? I have a WCF 4 service running on IIS 7 (Windows Server 2008), deployed to a development server. The service works when I run a small website that consumes the service (click a button, the page calls the service, data is returned. It's very basic). I also created some unit tests that call the service and placed them into a load test. In a nutshell, the "unit tests" call the service and write the byte[] streamed back from the service to a file. The service performs as expected when running the load test. The problem is the load test fails after a very small number of iterations. Sometimes foour calls are successful, other times after five calls. Again, individually, the tests run fine but when I put them together to simulate a live environment (multiple users, multiple test iterations) this problem appears. The exception thrown is: Test method TestProject1.UnitTest1.RunReport threw exception: System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to http://xx.xx.xx.xx:yy/Service.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host Update #1: I just set the test iteration to 10 (run the test 10x) and the constant user load to 1. The test was able to complete succesfully. This was using the most basic of the unit tests. The second, more complicated test, was omitted for this run. A: Look in your application event log (eventvwr.exe). Assuming you're operating in a mostly-normal environment, there will be an entry for the server-side error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Domain Name is not sticking on application summary I added a like button to my site pages. It seems to work, but the debugger is giving me errors. When I try out the URL in the Object Debugger it gives the error below: Object Base Domain Not Allowed Object at URL 'http://www.gdiy.com/projects/visiting-paris/index.php' of type 'website' is invalid because the domain 'www.gdiy.com' is not allowed for the specified application id '279134608772109'. When I try adding the domain name in the facebook developer apps settings (https://developers.facebook.com/apps/) it is not sticking. I enter "gdiy.com" as the domain and press enter -> then save. If I refresh the page now the domain doesn't exist anymore. Debugger results page: http://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2Fwww.gdiy.com%2Fprojects%2Fvisiting-paris%2Findex.php What's wrong here? I even tried "www.gdiy.com" and that didn't work either. I also waited a couple hours before trying. A: I was having the same issue. I waited a day, came back, and it seemed to be fixed. I'm not sure if this was a Facebook bug that they fixed, or if there was something else weird going on. However, time seemed to do the trick this time. A: I use Chrome and doesn't work, and I try with Firefox and work it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Backbone: Correct way of passing 'this' reference to anon functions in success/error callbacks Given the backbone view function below, what is the correct way of passing this (i.e. the current view) to the anonymous function defined in the callbacks? addSomething: function(e) { var newSomething= this.model.somethings.create({ someProperty: xxx }, { success: function(m, response) { this.doSomething(); //***HERE**** }, error: function(m, response) { //Error } }); }, Without and changes, the this in the anon function is set to the window. I can a set a reference like this: var thisView = this; and then just refer to thisView instead of this in the anon function, but this doesn't seem very elegant. Is there a better way? A: In order to better organize my code and work around this problem, I never put success and error callbacks directly in-line with my calls. I always split them out to their own functions. This let's me keep the code clean and also use the _.bindAll method to ensure I have the correct context for this. SomeView = Backbone.View.extend({ initialize: function(){ _.bindAll(this, "createSuccess", "createError"); }, addSomething: function(e) { var newSomething= this.model.somethings.create({someProperty: xxx}, { success: this.createSuccess, error: this.createError }); }, createSuccess: function(m, response) { this.doSomething(); }, createError: function(m, response) { //Error } }); A: You can use call: this.doSomething.call(this); Or send whatever you want this to be in doSomething A: You could also use the that convention: addSomething: function(e) { var that = this; var newSomething= this.model.somethings.create({ someProperty: xxx }, { success: function(m, response) { that.doSomething(); //***THAT HERE**** }, error: function(m, response) { //Error } }); } This is quite a common pattern in javascript especially when context is lost with nested functions. Nested functions do have access to the variables in the outer function and hence it works. Derick's approach makes the code cleaner, irrespective of the fact of having extra functions but if you don't want them use 'that' ;) A: Backbone has a builtin way to handle this: the 'context' attribute. this.model.destroy({ success: function (model, resp, options) { model.releaseLock(); window.location.href = this.getURLForModelID(model.get('id')); }, error: function (model, resp, options) { this.displayError(resp.message); }, context: this }); A: You can pass context seemingly without using call, bind or apply (or Lo-Dash) by creating an anonymous function, passing this, and then immediately calling the handler methods on the object's prototype as shown in the following CoffeeScript example: View = require('views/base/view') module.exports = class LoginPageView extends View template: require('./templates/login-page') events: 'submit form': '_doLogin' # Called when the template is bound using Chaplin attach: -> super @$loginButton = @$('[name="login"]') _doLogin: (evt) -> evt.preventDefault() @$loginButton.attr 'disabled', true email = @$('[name="email"]').val() password = @$('[name="password"]').val() @model.save {email, password}, success: (model, response, options) => @_loginSuccess model, response, options error: (model, response, options) => @_loginError model, response, options _loginSuccess: (model, response, options) -> # TODO: Implement method body _loginError: (model, response, options) -> # TODO: Implement method body Perhaps it's a little verbose with the argument names, and the extra closure created by the anonymous function isn't the best implementation performance-wise, but it's certainly a bit easier to grasp and manage when working with individuals of varied skill levels. A: You could also use $.proxy: success: $.proxy(function(m, response) { this.doSomething(); }, this), error: function(m, response) { //Error }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: isAnnotationPresent() return false when used with super type reference in Java I m trying to get the annotation details from super type reference variable using reflection, to make the method accept all sub types. But isAnnotationPresent() returning false. Same with other annotation related methods. If used on the exact type, output is as expected. I know that annotation info will be available on the Object even I m referring through super type. @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Table { String name(); } @Table(name = "some_table") public class SomeEntity { public static void main(String[] args) { System.out.println(SomeEntity.class.isAnnotationPresent(Table.class)); // true System.out.println(new SomeEntity().getClass().isAnnotationPresent(Table.class)); // true Class<?> o1 = SomeEntity.class; System.out.println(o1.getClass().isAnnotationPresent(Table.class)); // false Class<SomeEntity> o2 = SomeEntity.class; System.out.println(o2.getClass().isAnnotationPresent(Table.class)); // false Object o3 = SomeEntity.class; System.out.println(o3.getClass().isAnnotationPresent(Table.class)); // false } } How to get the annotation info? A: First, see java.lang.annotation.Inherited. Second, as others pointed out, your code is a bit different from your question. Third, to answer your question.. I have encountered a similar need many times so I have written a short AnnotationUtil class to do this and some other similar things. Spring framework offers a similar AnnotationUtils class and I suppose dozen other packages today also contain pretty much this piece of code so you don't have to reinvent the wheel. Anyway this may help you. public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> annotationType) { T result = clazz.getAnnotation(annotationType); if (result == null) { Class<?> superclass = clazz.getSuperclass(); if (superclass != null) { return getAnnotation(superclass, annotationType); } else { return null; } } else { return result; } } A: The o1.getClass() will give you object of type java.lang.Class, which doesn't have @Table annotation. I suppose you wanted o1.isAnnotationPresent(Table.class). A: You're calling getClass() on a Class<?>, which will give Class<Class>. Now Class itself isn't annotated, which is why you're getting false. I think you want: // Note no call to o1.getClass() Class<?> o1 = SomeEntity.class; System.out.println(o1.isAnnotationPresent(Table.class)); A: In your code, o1, o2 and o3 are already the Class<?> objects on which you'll want to call isAnnotationPresent(Class<?>), you shouldn't call getClass() on them before, because at this stage, you'll call isAnnotationPresent(Class<?>)on the Class class itself, and not on your SomeEntity class...
{ "language": "en", "url": "https://stackoverflow.com/questions/7599006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Lazy-loading properties not loading in Doctrine 2.0 I'm using PHP and Doctrine 2.0. All entities work fine, with the exception of the entity-relation detailed below (or other entities are failing where I'm not noticing it). Consider the following entities: /** @Entity */ class Target { /** * @ManyToOne(targetEntity="k\entity\Source", cascade={"persist"}) * @JoinColumn(name="basic_vacancy_id", nullable=false) * @var \k\entity\Source */ $source; ... } /** @Entity */ class Source { ... } Now, when I call $target->getSource() I get an instance of k\entity\proxy\kentitySourceProxy (which is the correct proxy class). However, all the getters for Source's properties return NULL. What could I be doing wrong? I've added the fetch="EAGER" attribute to the relational annotation, and now everything seems to go just fine (except for the fact that loading is no longer lazy). What could cause Doctrine 2.0's lazy loading to break? A: As seen above in my question, I've added the fetch="EAGER" attribute to the relational annotation, and now everything seems to go just fine (except for the fact that loading is no longer lazy). This is of course a workaround, and no fix of the actual bug. In addition to this, I still don't know what caused my code/Doctrine to break. However, the performance impact of this workaround seems to be negligible - if even present at all. A: It looks like internal d2 bug. Or you use reflection to retrieve properties of your object. Proxy classes use persister to initialize them on any method call. Does it issue a query when you use getter on this proxy?
{ "language": "en", "url": "https://stackoverflow.com/questions/7599007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Git Bash gets stuck on diff / log, spontaneously repeats same command over and over I'm having an odd problem with Git Bash on Windows 7 / XP. It used to work fine, but recently I find that after I perform a git diff or git log, Git Bash becomes unusable: following the diff/log, even after I return to the command prompt, Bash keeps suddenly and apparently spontaneously repeating the same command, unprompted and while I'm in the middle of typing a subsequent command. Has anyone else had this problem? Any advice would be much appreciated, because this is really limiting Git Bash's usefulness at the moment. A: You have to use q to quit git's pager. Using Ctrl-C only causes problems on windows. Ctrl-C should not quit the pager (and it does not on a linux system). When you Ctrl-C on windows (msysgit I suppose?), you are somehow killing the process "from the outside" (i.e. from cmd.exe). I don't know the exact reasons why this happens. As I've experienced similar problems in the past: try to hit q and Ctrl-C repeatedly in random order, if you're lucky you'll get a working prompt back again ;) [There's no better solution I know of – but it worked for me …] A: Note that with Git 2.12 (Q1 2017, 6+ years later), a Ctrl+C in a git pager session should behave better. See commit 46df690, commit 246f0ed, commit 2b296c9 (07 Jan 2017) by Jeff King (peff). (Merged by Junio C Hamano -- gitster -- in commit 5918bdc, 18 Jan 2017) execv_dashed_external: wait for child on signal death Typing ^C to pager, which usually does not kill it, killed Git and took the pager down as a collateral damage in certain process-tree structure. This has been fixed. You can run any dashed external with commands like git -p stash list, where the command finishes running, but the pager is still going. The short version is that everything should stop normally (Git and pager) But in detail: When git runs a pager, it's important for the git process to hang around and wait for the pager to finish, even though it has no more data to feed it. This is because git spawns the pager as a child, and thus the git process is the session leader on the terminal. After it dies, the pager will finish its current read from the terminal (eating the one character), and then get EIO trying to read again. Note: EIO (error 5) tands for Error I/O, and is (source) the: catchall for all manner of unexpected hardware errors. It could be from a physical error, but additionally, an orphaned process (a process whose parent has died) that attempts to read from standard input will get this. BSD systems return this if you try to open a pty device that is already in use. An attempt to read from a stream that is closed will return EIO, as will a disk read or write that is outside of the physical bounds of the device. An open of /dev/tty when the process has no controlling tty will spit back EIO also. So (back to ^C in a pager): When you hit ^C, that sends SIGINT to git and to the pager, and it's a similar situation. The pager ignores it, but the git process needs to hang around until the pager is done. We addressed that long ago in a3da882 (pager: do wait_for_pager on signal death, 2009-01-22). But when you have a dashed external (or an alias pointing to a builtin, which will re-exec git for the builtin), there's an extra process in the mix. For instance, running: $ git -c alias.l=log l will end up with a process tree like: git (parent) \ git-log (child) \ less (pager) If you hit ^C, SIGINT goes to all of them. The pager ignores it, and the child git process will end up in wait_for_pager(). But the parent git process will die, and the usual EIO trouble happens. With Git 2.28 (Q3 2020), when an aliased command, whose output is piped to a pager by git, gets killed by a signal, the pager got into a funny state, which has been corrected (again). See commit c0d73a5, commit e662df7 (07 Jul 2020) by Trygve Aaberge (trygveaa). (Merged by Junio C Hamano -- gitster -- in commit 05920f0, 15 Jul 2020) Ctrl+C:Wait for child on signal death for aliases to builtins Signed-off-by: Trygve Aaberge When you hit ^C all the processes in the tree receives it. When a git command uses a pager, git ignores this and waits until the pager quits. However, when using an alias there is an additional process in the tree which didn't ignore the signal. That caused it to exit which in turn caused the pager to exit. This fixes that for aliases to builtins. This was originally fixed in 46df6906 (execv_dashed_external: wait for child on signal death, 2017-01-06), but was broken by ee4512ed ("trace2: create new combined trace facility", 2019-02-22, Git v2.22.0-rc0 -- merge listed in batch #2) and then b9140840 ("git: avoid calling aliased builtins via their dashed form", 2019-07-29, Git v2.23.0-rc1 -- merge). And: When we are running an alias to an external command, we want to wait for that process to exit even after receiving ^C which normally kills the git process. This is useful when the process is ignoring SIGINT (which e.g. pagers often do), and then we don't want it to be killed. Having an alias which invokes a pager is probably not common, but it can be useful e.g. if you have an alias to a git command which uses a subshell as one of the arguments (in which case you have to use an external command, not an alias to a builtin). This patch is similar to the previous commit, but the previous commit fixed this only for aliases to builtins, while this commit does the same for aliases to external commands. In addition to waiting after clean like the previous commit, this also enables cleaning the child (that was already enabled for aliases to builtins before the previous commit), because wait_after_clean relies on it. Lastly, while the previous commit fixed a regression, I don't think this has ever worked properly. Note that if you are using trace2 to debug the situation, the pager is now properly traced. When a pager spawned by the user exited, the trace log did not record its exit status correctly, which has been corrected with Git 2.31 (Q1 2021). See commit be8fc53, commit 85db79a, commit c24b7f6, commit 61ff12f (02 Feb 2021) by Ævar Arnfjörð Bjarmason (avar). (Merged by Junio C Hamano -- gitster -- in commit dcb11fc, 22 Feb 2021) pager: properly log pager exit code when signalled Signed-off-by: Ævar Arnfjörð Bjarmason When git invokes a pager that exits with non-zero the common case is that well already return the correct SIGPIPE failure from it itself, but the exit code logged in trace2 has always been incorrectly reported1. Fix that and log the correct exit code in the logs. Since this gives us something to test outside of our recently-added tests needing a !MINGW prerequisite, let's refactor the test to run on MINGW and actually check for SIGPIPE outside of MINGW. The wait_or_whine() is only called with a true "in_signal" from from finish_command_in_signal(), which in turn is only used in pager.c. The "in_signal && !WIFEXITED(status)" case is not covered by tests. Let's log the default -1 in that case for good measure. * *The incorrect logging of the exit code in was seemingly copy/pasted into finish_command_in_signal() in ee4512e ("trace2: create new combined trace facility", 2019-02-22, Git v2.22.0-rc0 -- merge listed in batch #2) A: Once you are stuck, try Ctrl-Break instead of Ctrl-c, it works for me. (the actual Pause/Break key near the Scroll Lock one).
{ "language": "en", "url": "https://stackoverflow.com/questions/7599014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Nivo Slider not working as it should in WebKit (chrome and safari) I'm using Nivo Slider on http://tinyurl.com/5wtrau2 and I am unable to get the slideshow to operate correctly in Webkit, Chrome or Safari(mac). The slider transitions by making the current image a background image of the container and then randomly fades each box. It appears like the background image is reloading and there's a slight pause. A: Adding the slideshow images with javascript/jquery and then invoking the Nivo Slider seems to have been the issue here for Windows Safari. I added the images into the html file and the problem was resolved, however it is still an issue with Chrome A: I used Google and found this: http://support.dev7studios.com/discussions/nivo-slider/561-flashing-before-transitions-in-mac-chrome#comment_13013897
{ "language": "en", "url": "https://stackoverflow.com/questions/7599016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Send empty packets to not timeout the connection Real world problem: I'm generating a page dinamically. This page is an xml which is retrieved by the user (curl, file_get_contents or whatever can by made server side scripting). Once the user make the request, he start waiting and I start retrieving a large set of data from the db and building an xml with them (using the php dom objects). Once I've done I fire the "print $document->saveXML()". It takes about 8 minutes to create this 40 megabytes document. Then as it is ready I serve the page/document. Now I have a user who has a 60 seconds connection timeout: he said I need to send the first octet each 60 seconds. How can I achieve such a thing? Since it's useless to post a 23987452 lines code cause nobody is gonna read them, I'll explain the script which serves this page as real-very-pseudo-pseudo-code: * *grab all the data from the db: an enormous set of rows *create a domdocument element *loop through each row and add a node element to the domdocument to contain a piece of data *call the $dom->saveXML() to get the document as a string *print the string so the user retrieve an xml document 1) I can't send real data since it is an xml document and it has to begin with "<?xml..." to not mess up the parser.` 2) The user can't deal with firewall/serverconfig 3) I can't deal with "buy a more powerful server" 4) I tried using an ob_start() at the top of the script and then at the beginning of each loop a "header("Transfer-Encoding: chunked"); ob_flush(); " but nothing: nothing comes before the 8 minutes. Help me guys!! A: I would * *Generate a random value *Start the XML generating script as a background process (see e.g. here) *Make the generating script write the XML into a file with the random value as the name when the script is done *Frequently poll for the existence of that empty file, e.g. using Ajax requests every 10 seconds, until it's there. Then fetch the XML from the file. A: You send padding and still have it be valid XML. Trivial examples include whitespace in a lot of places, or comments. Once you've sent the XML declaration, you could start a comment, and keep sending padding: <?xml version="1.0"> <!-- this comment to prevent timeouts: 30 60 90 ⋮ or whatever, the exact data doesn't matter of course. That's the easy solution. The better solution is to make that generation run in the background, and e.g., use AJAX to poll the server every 10s to check if its done. Or to implement an alternate notification method (e.g., email a URL when the the document is ready). If this isn't a browser accessing, you may want a trivially simple API: Have one request to start generating the document, and another to fetch it. The one to fetch it may return "not ready yet" as e.g., a HTTP status code 500, 503, or 504. Then the script requesting should retry later. (For example, with curl, the --retry option will do this).
{ "language": "en", "url": "https://stackoverflow.com/questions/7599019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: enumdisplayDevices returns multiple instances for one display card Hi I am using the following code fragment to get number of display adapters in my windows 7 system. I have a NVidia GT 120 which is connected to my monitor, and a NVidia Quadro 4000 which is acting as my GPU processor. Because both display adapters have more than one output port, with following code, I actually get 2 Display_Device instances for GT120 and 2 for Quadro 4000. My work around of this problem is actually using the DeviceKey component (which MSDN says is not used, but it is in fact a registry key) of the DisplayDevice structure as criteria to remove the duplicate instance. Did anyone has a better, or official solution to this problem? FARPROC EnumDisplayDevices; HINSTANCE hInstUser32; DISPLAY_DEVICE DispDev; char szSaveDeviceName[32]; BOOL bRet = TRUE; hInstUser32 = LoadLibrary("User32.DLL"); if (!hInstUser32) return FALSE; // Get the address of the EnumDisplayDevices function EnumDisplayDevices = (FARPROC)GetProcAddress(hInstUser32,"EnumDisplayDevicesA"); if (!EnumDisplayDevices) { FreeLibrary(hInstUser32); return FALSE; } ZeroMemory(&DispDev, sizeof(DISPLAY_DEVICE)); DispDev.cb = sizeof(DISPLAY_DEVICE); // After the first call to EnumDisplayDevices, // DispDev.DeviceString is the adapter name while (EnumDisplayDevices(NULL, nDeviceIndex++, &DispDev, 0)) { //getdevice } FreeLibrary(hInstUser32); return bRet;
{ "language": "en", "url": "https://stackoverflow.com/questions/7599021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I test error pages in rails development environment? I want to design my 404 page in my Rails 3.0.7 app. If I request a non existing page I get the development output Routing Error No route matches "/foo" I tried the following answers in: How to test 500.html in rails development env? application_controller: def local_request? false end development.rb: config.consider_all_requests_local = false development.rb: config.action_view.debug_rjs = false and I also started my app with: RAILS_ENV=production rails s RAILS_ENV=production passenger start None of it worked.I love how rails makes complicated tasks very simple. But it's really frustrating how really simple things turn out tu be overwhelmingly difficult, impossible to debug and you end up hacking on remote servers to work around it.. Has anyone had this problem before? A: If your error pages are static you can simply go to http://localhost:3000/404.html, http://localhost:3000/500.html, etc. A: Best idea I've come up with so far is to run the server in production mode locally. rails s -e production cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: UIImage imageNamed extension I recently discovered a pretty big performance issue in my app that was due to an image not being found in [UIImage imagenamed:]. I was wondering if there is a "drop-in" solution to have this kind of 'errors' logged in some way? I started writing an extension to the UIImage class, something like this: @implementation UIImage (Debug) #ifdef DEBUG + (UIImage*) imageNamed:(NSString*) name{ UIImage* img = [UIImage imageNamed:name]; if(!img){ NSLog(@"Error: referencing non-exiting image: %@", name); } return img; } #endif @end But this causes an endless loop since [UIImage imageNamed:name] of course causes the extension method to be called again... Any suggestions? thanks Thomas A: You should never use categories to override an existing method. This will lead to unexpected results (the implementation used will depend on the order the runtime loads the binary images/modules). Instead, you may use the possibilities of the objc runtime to exchange implementations of one selector with another (sometimes called method swizzling). But I would discourage you to do this if you don't really know the implications. (call the swapped method if you want to call the original to avoid call loops, manage the use case when the method is implemented in the parent class but not the child, and much more subtleties) But if you only want to debug and be alerted when an UIImage is not found use symbol breakpoints ! (Breakpoints are not limited to be placed on a given line of code!) Breakpoints are more powerful than you can imagine (I encourage you to watch the WWDC'11 video session about "mastering debugging in Xcode"), especially you can place a breakpoint not on a specific line in your code, but on a specific method call (in your case the method -imageNamed:), and add a condition to the breakpoint so it will only be hit in certain condition (returned image nil?). You can even ask the breakpoint to log some info (or play a sound, or whatever) and/or continue execution instead of stopping your code execution. A: What you want to do is called swizzling: you swap two methods so your own method is now called instead and you can access the original method under the name of your method. Seems a little confusing at first, but here is how it works: #import <objc/runtime.h> @implementation UIImage(Debug) // Executed once on startup, before anything at UIImage is called. + (void)load { Class c = (id)self; // Use class_getInstanceMethod for "normal" methods Method m1 = class_getClassMethod(c, @selector(imageNamed:)); Method m2 = class_getClassMethod(c, @selector(swizzle_imageNamed:)); // Swap the two methods. method_exchangeImplementations(m1, m2); } + (id)swizzle_imageNamed:(NSString *)name { // Do your stuff here. By the time this is called, this method // is actually called "imageNamed:" and the original method // is now "swizzle_imageNamed:". doStuff(); // Call original method id foo = [self swizzle_imageNamed:name]; doMoreStuff(); return something; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7599030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to allow a third party to update information within an Application At the moment i am beginning to create an android and iPhone application for a third party. When the application is finished the third party would like to update information within the application like a news feed or new content. What would be the best way to create a CMS(Content Management System) for the third party so they could easily create new data which can be viewed on the application. Lets say they would just have to login to a website, give the new information, could be photos,videos, points of intrest(coordinates), text or other information. A: That's a really broad question and depends on many factors: what CMS's you are already familiar with, what sort of data you need to update, what level of user experience the third party is expecting etc. You will get a better response on SO if you ask a specific question. Having said that, I would try to decouple the iPhone implementation from the CMS implementation so you can defer choice of CMS until you are clearer about your requirements. Use something standard like an RSS feed that you can prototype and get the iPhone end working correctly then choose a CMS that can create RSS feed for you (e.g. Wordpress off the top of my head).
{ "language": "en", "url": "https://stackoverflow.com/questions/7599031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query to update rows and then create a table if it does not exist I have two different things to happen at once.., basically I need to insert two new records in a table if they are not already there... and for sure they will always have the same ID and Name (i did this) but then immediately after that i need to check if a table existst and if it does not create it.. (but if it does exist I DO NOT want to drop it just leave it alone). Please see my code below.. Can you help me with the checking of the table existing or not? and if you see a room on improvement please do.. Thank you --ADD LOCKS BEGIN TRAN IF EXISTS (SELECT myID, myName FROM myTable WHERE myID = 7 AND myName = 'Pedro') SELECT 1 ELSE INSERT INTO myTable (myID , myName) values ( 7, 'Pedro') IF EXISTS (SELECT myID, myName FROM myTable WHERE myID = 8 AND myName = 'Joseph') SELECT 1 ELSE INSERT INTO myTable (myID , myName) values ( 8, 'Joseph') COMMIT --NOW BELOW I WANT TO DO THE CREATION OF A TABLE IF IT DOES NOT EXIST NOT SURE HOW TO CHECK IT.. BUT KNOW HOW TO CREATE IT --IF TABLE DOES NOT EXIST DO THE FOLLOWING SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[myTable]( [myID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar(MAX)] NOT NULL CONSTRAINT [PK_myTable] PRIMARY KEY CLUSTERED ( [myID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO --ELSE DONT DO NOTHING A: As per my knowledge, you have check whether the table exists or not first and create it before inserting if it doesn't exist. Hope the below query might be of some use for you. IF NOT EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID(N'[dbo].[myTable]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[myTable] ( [myID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar(MAX)] NOT NULL CONSTRAINT [PK_myTable] PRIMARY KEY CLUSTERED ( [myID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY] ) ON [PRIMARY] END IF NOT EXISTS (SELECT myID, myName FROM myTable WHERE myID = 7 AND myName = 'Pedro') BEGIN INSERT INTO myTable (myID , myName) values ( 7, 'Pedro') END IF NOT EXISTS (SELECT myID, myName FROM myTable WHERE myID = 8 AND myName = 'Joseph') BEGIN INSERT INTO myTable (myID , myName) values ( 8, 'Joseph') END Edit: Should also note, this will not work without turning IDENTITY_INSERT ON. Because the myID column is an identity field, the values attempting to be inserted will fail. A: For inserting the records cleaner script would be: IF NOT EXISTS (SELECT 1 FROM myTable WHERE ...) BEGIN -- Insert record END And for checking if a table exists: Check if table exists in SQL Server IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TheSchema' AND TABLE_NAME = 'TheTable')) BEGIN -- Insert table END You might want to switch the order of these statements so you don't query a table that may not exist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Active Record accepts nested attributes for I'm having trouble getting this to work. I want to use nested attributes in a form, but before I do that I need to be able to build a person (administrator) from event, like so: @event = Event.new @event.administrator.build #=> undefined method 'build' for nil:NilClass class Event < ActiveRecord::Base #start_date, end_date, title has_one :administrator, :class_name => "Person" has_one :account_manager, :class_name => "Person" accepts_nested_attributes_for :administrator end class Person < ActiveRecord::Base #fname, lname, bday belongs_to :event end Any help? A: I think you need to use build_administrator instead... @event = Event.new @event.build_administrator This is because you have a 'has_one' association, therefore there is no association proxy created by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NullPointerException when trying to set a double array in java This is the relevant code I think class Sudoku { int[][] grid; void generateSudokuFromInput() { grid = new int[][] <--- java.lang.NullPointerException at Sudoku.generateSudokuFromInput(Sudoku.java:309) { (...) } } void solveIt() { generateSudokuFromInput(); } } Keep getting NullPointer error A: When declaring multidimensional array, you must specify all the dimensions except the last one. E.g grid = new int [3][]; This will work nicely. A: As an alternative to declaring the array size later (as described in other answers), you can also just initialize your array when declaring it: class Sudoku { int[][] grid = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0} }; void generateSudokuFromInput() { // just set the values on grid, e.g. grid[0][0] = 9 } void solveIt() { generateSudokuFromInput(); } } A: To create an array you must have to specify the subscript value. grid = new int[2][]; grid[0]=new int[2]; grid[1]=new int[5]; or grid=new int[3][3]; To learn more about arrays refer this document. A: You need to provide size for the first dimension: grid = new int[3][]; Else, how do you expect the second dimension to work? A 2-dimensions array [i][j] basically means "My array has i arrays, each of them have j values". If there's no i, it doesn't mean anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JTable Sorting and Filtering I am creating a program that filters the contents of a JTable using two columns. I have used a RowSorter and everything works fine - at least according to what I can see (the view). Each row on the table can be double clicked to open a dialog. This dialog allows you to edit information on the table. However, the information on the dialog is still of that of the original view (before filtering was used). Example: Before filtering the first row on the table is row a. After filtering the first row on the table is row b. However, when I double click to open the dialog on the first row (after filtering, which should now be row b, the dialog for row a opens.) [Hope I've explained this well enough] I think my problem is that the model isn't being updated after the filters have taken place. I've tried: for(int i = 0; i < table.getRowCount(); i++){ table.convertRowIndexToView(i); } and for(int i = 0; i < table.getRowCount(); i++){ table.convertRowIndexToModel(i); } I am also getting a similar problem when I sort the table using the column headers. How do I fix this problem? A: I think my problem is that the model isn't being updated after the filters have taken place The model is never updated. Only the view is updated to show the data from the model in a sorted/filtered order. Each row on the table can be double clicked to open a dialog. So I assume you copy the data for one row to the dialog so it can be edited and then added back to the original model. Therefore you need to use the convertRowIndexToModel(...) to get the model row number so you can access the model data to be displayed on the edit dialog. You would only do this for the row to be edited, not the entire table. A: please see tutorial about JTable, there is excelent example about Comparator and good explanations about how to use the TableModel too A: After you change data you can refresh table as below; for(int i = 0; i < table.getRowCount(); i++) { table.convertRowIndexToModel(i); } table = new jTable(myModel); or myModel.fireTableDataChanged() Hope it helps Burak
{ "language": "en", "url": "https://stackoverflow.com/questions/7599051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why am i getting _Lambda$__2 as the method name using reflection I am using reflection to get the name of a function. Everything was fine and now instead of getting the function name (e.g. SendEmail) i am getting Lambda$_2 as the function name. Nothing seems to have changed in the code that would have changed this. I have the same behaviour elsewhere in the project and that still works fine. My code: Private _sendEmailDel As Zeta.Bol.SendEmailDel (this is a delegate sub) _sendEmailDel = AddressOf Zeta.Bol.SendEmail dim methName as string = _sendEmailDel.Method.Name Zeta.Bol.SendEmail is normal function (no lambda involved). A: That's because you're trying to get the name of your delegate, not the original function. Since you declared the delegate anonymously, the compiler generates an automatic name for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DataBinding: Does not contain a property with then name '(columnName)' I just finished one thing to come up with yet another problem with databinding. I just implemented a select statement that joins 2 tables so on my asp page I can look at a column in the 2nd table and see if there is or is not an integration being made, and vary the results on that note I have looked at similar problems and tried the solutions but it has not worked for me. The exact error message is: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Integration'. The Select Statement: SELECT productid, productname, productsku, quantity, productprice, productprice * quantity AS totalprice, shoppingcartrecid, uom, packingslip, logodesignnumber, customtext, nametext, extracharge, custitem, t1.catalogtype, catalogid, relatedchargeid, upsflag FROM shoppingcart t1 INNER JOIN itemcatalogprofile t2 ON t1.catalogtype = t2.catalogtype Where Im using it: <asp:HyperLink ID="HyperLink" runat="server" style="cursor:pointer; text-decoration:none;" NavigateUrl='<%# (Eval("Integration").ToString() == "Y") ? String.Format("~integration/vendorframe.aspx?CatalogID={0}",Eval("CatalogID")) : String.Format("~/storefront.aspx?CatalogID={0}",Eval("CatalogID"))%>'> If there is any other info I you need I will try and get it, any help is appreciated. Thanks There were 2 parts to the answer: First, I completly forgot to add t2.Integration to my select this morning after I did when I ran it on a test query Second, I was using : Eval("Integration").ToString() .. after I took ToString off the page started working.. Thank you all A: There isn't a column called Integration, which would cause the error you are having. Doing an INNER JOIN is automatically not going to show the things that don't exist. You need to change your SQL statement to an OUTER JOIN, and then check for the existence of some field withi the ItemCatalogProfile table. A: There doesn't appear to be an "Integration" column in your query anywhere. A: It looks like the Integration and CatalogID columns are missing from the select statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Objectify and email as @Id I am not sure if I use the @Id in objectify the right way. Right now I am using the eMail-Address as @Id field. The email field will be set on the server-side only (OAuthService.getCurrentUser.getEmail) First question: Is this a good idea? If I create for example an Item-class which has RegistrationTO as it's parent does it make sense to use the email-address as the @Id field in my Item-class or should Item-class have it's own, auto-generated, id and Key parent to specify the relation? Objectify-Tutorial recommends to avoid @Parent - so, here I think it's not necessary either. I am right? Here my RegistrationTO: public class RegistrationTO implements Serializable { private static final long serialVersionUID = 1L; @NotNull @Size(min = 5, max = 20) private String firstname; @NotNull @Size(min = 5, max = 20) private String name; @NotNull @Size(min = 5, max = 20) private String country; @Id @NotNull @Size(min = 5, max = 20) @Pattern(regexp = "\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\b") private String email; public RegistrationTO() { } public RegistrationTO(final String firstname, final String name, final String company) { this.firstname = firstname; this.name = name; this.country = country; email = "will be set on server (Oauth)"; } public String getFirstname() { return firstname; } public String getName() { return name; } public String getCountry() { return country; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } } Sample for Item class: public class Item implements Serializable { private static final long serialVersionUID = 1L; @Id Long id //or //@Id //String email Key<RegistrationTO> parent; String itemno; } Thank you in advance! A: Regarding your question if the use of e-mail as @Id is correct or not, since the email will uniquely identify each object of the class, then you are fine! Now, regarding the @Id of your Item class, if the email uniquely identifies each object, then there is no need to create a new auto-generated Long as @Id. In general, the criterion for the selection of the @Id is to uniquely identify all the objects of the class. For the relationship between RegistrationTO and Item classes, use the @Parent annotation only if you need these entities to be the same entity group. The code for this: @Parent Key<RegistrationTO> parent; Otherwise, use a "plain" relationship (as you have it in your example) that allows RegistrationTO and Item entities to be stored in different entity groups in the GAE datastore. For more information about entity groups, take a look at: http://code.google.com/appengine/docs/java/datastore/entities.html#Entity_Groups_and_Ancestor_Paths Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7599066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: asp.net mvc3 keeping related models together? I'm trying to expand beyond the "one-to-one" mapping of models to controllers to views that most mvc(3) tutorials offer. I have models for a person (operator) and the person's picture. In the database they would correspond to Operator and OperatorPicture tables. public class Operator { public Operator() { this.OperatorPictures = new HashSet<OperatorPicture>(); } [DisplayName("Operator ID")] public int OperatorID { get; set; } [Required] [DisplayName("First name")] [StringLength(20, ErrorMessage = "The first name must be 20 characters or less.")] public string OperatorFirstName { get; set; } [Required] [DisplayName("Last name")] [StringLength(20, ErrorMessage = "The last name must be 20 characters or less.")] public string OperatorLastName { get; set; } public virtual ICollection<OperatorPicture> OperatorPictures { get; set; } // Nav } public class OperatorPicture { [DisplayName("Operator Picture ID")] public int OperatorPictureID { get; set; } [DisplayName("Operator ID")] public int OperatorID { get; set; } [DisplayName("Picture")] public byte[] Picture { get; set; } // 100x100 [DisplayName("Thumbnail")] public byte[] Thumbnail { get; set; } // 25x25 public virtual Operator theoperator { get; set; } // FK } In most views I would present them together. A list of operators would include a thumbnail picture if it exists. Another screen might show the person's detailed information along witht the full-sized picture. Is this where viewmodels come into play? What is an appropriate way to use them? Thanks, Loyd A: Definitely a time for using them. ViewModels are just a way of packaging up all the different bits that go into a view or partialview. Rather than have just the repository pattern, I have repositories and services. The service has a Get property called ViewModel, that can be called from the controller. EG: // initialise the service, then... return View(service.ViewModel) You can see a more detailed description of my approach in the accepted answer for the following SO question: MVC Patterns Note that I am using dependency injection in that code. It may not be a totally orthodox or canonical approach, but it results in very clean controller code and a easy to use pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading assets doesn't work right after turning on device, but works after. What's going on? My application loads and plays a video as an asset through the Media Player class. But I've noticed that whenever I turn off my device (a Samsung Galaxy Tab), turn it back on and run the application the video doesn't load. But if I wait a few minutes and re-run my application it works. What could be going on at the device start up that would make loading my video as an asset file fail? I say "fail", but I don't see any obvious errors in the log. I know that on start up, the device has to through steps like finding media. So maybe playback doesn't work until that's done. How do I find out that everything is finished and ready before I know I can play a video? A: You can try registering a BroadcastReceiver in the manifest with intent filter android.intent.action.BOOT_COMPLETED. It requires the permission android.permission.RECEIVE_BOOT_COMPLETED
{ "language": "en", "url": "https://stackoverflow.com/questions/7599075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GtkStatusIcon drawing issue i'm using gtk+-2.0 in C. and i have to write a digit upon my tray icon. i do it such way: static GdkPixbuf * transform_pixbuf(GdkPixbuf *pixbuf) { cairo_t *cr; int width = gdk_pixbuf_get_width(pixbuf); int height = gdk_pixbuf_get_height(pixbuf); GdkPixmap *pixmap = gdk_pixmap_new(NULL, width, height, 24); cr = gdk_cairo_create(pixmap); gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0); cairo_paint(cr); cairo_select_font_face (cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); cairo_set_font_size (cr, 15.0); cairo_set_source_rgb (cr, 1.0, 0, 0); cairo_move_to (cr, 10, 20); cairo_show_text (cr, "8"); cairo_destroy(cr); GdkPixbuf *pixbuf_new = gdk_pixbuf_get_from_drawable(NULL, pixmap, NULL, 0, 0, 0, 0, width, height); return pixbuf_new; } where GdkPixbuf *pixbuf is GdkPixbuf i want to set in tray. i can draw a digit, but the icon's background became "dancing" - . i guess the problem is in gdk_pixmap_new's depth argument, because the icon has 32bit format, but 32 isn't valid argument for this function. in such case i have followin warning and no icon in the tray: Gdk-WARNING **: Using Cairo rendering requires the drawable argument to have a specified colormap. All windows have a colormap, however, pixmaps only have colormap by default if they were created with a non-NULL window argument. Otherwise a colormap must be set on them with gdk_drawable_set_colormap Gdk-WARNING **: /build/buildd/gtk+2.0-2.24.4/gdk/gdkpixbuf-drawable.c:1249: Source drawable has no colormap; either pass in a colormap, or set the colormap on the drawable with gdk_drawable_set_colormap() Suggest me, please... A: i've solved my problem with workaround. the problem was in creating pixmap - it was "dirty" from it's "born". the solution is in to not use pixmap, but create cairo context via the functions: http://www.gtkforums.com/viewtopic.php?t=5204
{ "language": "en", "url": "https://stackoverflow.com/questions/7599081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error on Gaussian blur with convolution method in openCV2.3 i write use openCV api to create a Gaussian kernel and then pass it to the Conv2ByDFT function to do the convolution. But the program crash and i don't know why. Here is the code. void Conv2ByFFT(const Mat& f,const Mat& g,Mat& result) { result.create(abs(f.rows-g.rows+1),abs(f.cols-g.cols+1),f.type()); Size dftSize; dftSize.width = getOptimalDFTSize(f.cols + g.cols - 1); dftSize.height = getOptimalDFTSize(f.rows + g.cols -1); Mat tmpF(dftSize,f.type(),Scalar::all(0)); Mat tmpG(dftSize,g.type(),Scalar::all(0)); dft(tmpF,tmpF,0,f.rows); dft(tmpG,tmpG,0,g.rows); mulSpectrums(tmpF,tmpG,tmpF,0); dft(tmpF,tmpF,DFT_INVERSE+DFT_SCALE,result.rows); tmpF(Rect(0,0,result.cols,result.rows)).copyTo(result); } Here is some code in the main() to call the function above Mat gaussianFilter = getGaussianKernel(7,2.0,CV_64F); // create Gaussian kernel Conv2ByFFT(src,gaussianFilter,result); // do the convolution I don't know if there's something wrong with the getGaussianKernel() function or something wrong with my Conv2ByFFT() function...Can anyone help me? THANKS A LOT! A: My guess is that your src matrix is not in CV_32F or CV_64F (32 or 64 bit floating point) format. If it is an image, you might need to convert it. Reminder from OpenCV documentation: The type of matrix elements is specified in form CV_(S|U|F)C, for example: CV_8UC1 means an 8-bit unsigned single-channel matrix, CV_32SC2 means a 32-bit signed matrix with two channels. Here is a complete list of defines from the source: #define CV_16S 3 #define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) #define CV_16SC1 CV_MAKETYPE(CV_16S,1) #define CV_16SC2 CV_MAKETYPE(CV_16S,2) #define CV_16SC3 CV_MAKETYPE(CV_16S,3) #define CV_16SC4 CV_MAKETYPE(CV_16S,4) #define CV_16U 2 #define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) #define CV_16UC1 CV_MAKETYPE(CV_16U,1) #define CV_16UC2 CV_MAKETYPE(CV_16U,2) #define CV_16UC3 CV_MAKETYPE(CV_16U,3) #define CV_16UC4 CV_MAKETYPE(CV_16U,4) #define CV_32F 5 #define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) #define CV_32FC1 CV_MAKETYPE(CV_32F,1) #define CV_32FC2 CV_MAKETYPE(CV_32F,2) #define CV_32FC3 CV_MAKETYPE(CV_32F,3) #define CV_32FC4 CV_MAKETYPE(CV_32F,4) #define CV_32S 4 #define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) #define CV_32SC1 CV_MAKETYPE(CV_32S,1) #define CV_32SC2 CV_MAKETYPE(CV_32S,2) #define CV_32SC3 CV_MAKETYPE(CV_32S,3) #define CV_32SC4 CV_MAKETYPE(CV_32S,4) #define CV_64F 6 #define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) #define CV_64FC1 CV_MAKETYPE(CV_64F,1) #define CV_64FC2 CV_MAKETYPE(CV_64F,2) #define CV_64FC3 CV_MAKETYPE(CV_64F,3) #define CV_64FC4 CV_MAKETYPE(CV_64F,4) #define CV_8S 1 #define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) #define CV_8SC1 CV_MAKETYPE(CV_8S,1) #define CV_8SC2 CV_MAKETYPE(CV_8S,2) #define CV_8SC3 CV_MAKETYPE(CV_8S,3) #define CV_8SC4 CV_MAKETYPE(CV_8S,4) #define CV_8U 0 #define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) #define CV_8UC1 CV_MAKETYPE(CV_8U,1) #define CV_8UC2 CV_MAKETYPE(CV_8U,2) #define CV_8UC3 CV_MAKETYPE(CV_8U,3) #define CV_8UC4 CV_MAKETYPE(CV_8U,4)
{ "language": "en", "url": "https://stackoverflow.com/questions/7599085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't access the checkout/onepage/ in magento 1.5.0.1? Can anybody help with this , I have cloned a production site to my local server for development and testing which seems to be working ok. I have created some new app/skin packages and applied and tested them. But the checkout links are not working either from the cart or top-links or the mini sidebar cart , also the login link does not work. The url's are https://127.0.0.1/silkyliving/index.php/checkout/onepage/ https://127.0.0.1/silkyliving/index.php/customer/account/login/ I get "This webpage is not available The connection to 127.0.0.1 was interrupted".message. I've installed the default package and other packages to see if the fault lies in my package but it does it in any package. So i think the fault is in the overal configuration/install. I have also tested my local server with another install and that works ok so is not a server error. To be honest i never checked the checkout functions when i cloned the production site so not sure where the fault is, the production site is working ok ? Does anybody have any ideas ? Thanks Ledgemonkey A: I have discovered the problem it was in >configuration >web - Use Secure URLs in Frontend was set to "yes" changed it to "no" and seems to be working ok now ? thanks A: goto Magento root index.php ini_set("memory_limit","512M"); // echo ini_get("memory_limit"); //for test then all are solved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the pitfalls of adding properties to a function object within the function? I found I could use this technique to retain a sort of "state" within an event handler, w/o having to involve outside variables... I find this technique to be very clever in leveraging the fact that functions are actually objects in and of themselves, but am worried I'm doing something that could have negative implications of some sort... Example... var element = document.getElementById('button'); element.onclick = function funcName() { // attaching properties to the internally named "funcName" funcName.count = funcName.count || 0; funcName.count++; if (self.count === 3) { // do something every third time alert("Third time's the charm!"); //reset counter funcName.count = 0; } }; A: Instead of doing that, you can use a closure: element.onclick = (function() { var count = 0; return function(ev) { count++; if (count === 3) { alert("3"); count = 0; } }; })(); That setup involves an anonymous function that the code immediately calls. That function has a local variable, "count", which will be preserved over the succession of event handler calls. By the way, this: var something = function dangerous() { ... }; is "dangerous" because some browsers (guess which, though Safari has had issues too) do weird things when you include a name on a function expression like that. Kangax wrote the issue up quite thoroughly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ABPeoplePickerNavigationController in Tabbar based application I have requirement as following like showing ABPeoplePickerNavigationController in tabbar based application. I researched a lot on net and found no helpful answer but one here, to implement code as follows will help to get ABPeoplePickerNavigationController in tabbar as shown in image. First screenshot is direct result when I run the application and second screenshot is when I again click on the Contacts tab (Weird but thats true). -(void)awakeFromNib { ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init]; NSMutableArray *newControllers = [NSMutableArray arrayWithArray: [self.tabBarController viewControllers]]; int index = [newControllers indexOfObject: self]; [newControllers replaceObjectAtIndex: index withObject: nav]; [self.tabBarController setViewControllers: newControllers animated: NO]; [nav release]; } Now my problem is I am able to navigate through contacts but not able to set ABPeoplePickerNavigationController delegate. I want to override following delegate methods -(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { } -(BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person { } Which I am not able to set, as I have no idea where to set delegate. Please help me for the same as my project is on Deadline and all other features are completed. Any tricks are welcomed. I assume that I can subclass ABPeoplePickerNavigationController and do something but don't know how to do that. Edit After setting delegate I am getting following crash when I click on Contacts tab. #0 0x00f85057 in ___forwarding___ #1 0x00f84f22 in __forwarding_prep_0___ #2 0x00d4b678 in -[ABMembersViewController membersController:shouldAllowSelectingPerson:] #3 0x00d1df85 in -[ABMembersController abDataSource:shouldAllowSelectingPerson:] #4 0x00d9abb9 in -[ABMembersDataSource tableView:cellForRowAtIndexPath:] #5 0x003357fa in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] #6 0x0032b77f in -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] #7 0x00340450 in -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] #8 0x00338538 in -[UITableView layoutSubviews] #9 0x01dc8451 in -[CALayer layoutSublayers] #10 0x01dc817c in CALayerLayoutIfNeeded #11 0x01dc137c in CA::Context::commit_transaction #12 0x01dc10d0 in CA::Transaction::commit #13 0x01df17d5 in CA::Transaction::observer_callback #14 0x00ff4fbb in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ #15 0x00f8a0e7 in __CFRunLoopDoObservers #16 0x00f52bd7 in __CFRunLoopRun #17 0x00f52240 in CFRunLoopRunSpecific #18 0x00f52161 in CFRunLoopRunInMode #19 0x018b5268 in GSEventRunModal #20 0x018b532d in GSEventRun #21 0x002d042e in UIApplicationMain #22 0x00002240 in main at main.m:13 A: You need to set the ABPeoplePickerNavigationController's delegate after you have created it in awakeFromNib. Add this line: nav.peoplePickerDelegate = self; This sets your custom view controller as the people picker's delegate. Your controller will need to implement the ABPeoplePickerNavigationControllerDelegate protocol and you will need to implement the two methods you have listed in your question. A: Have you tried setting nav.peoplePickerDelegate = self; like so: -(void)awakeFromNib { ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init]; nav.peoplePickerDelegate = self; NSMutableArray *newControllers = [NSMutableArray arrayWithArray: [self.tabBarController viewControllers]]; int index = [newControllers indexOfObject: self]; [newControllers replaceObjectAtIndex: index withObject: nav]; [self.tabBarController setViewControllers: newControllers animated: NO]; [nav release]; } And in your @interface you can indicate that you are the delegate with ABPeoplePickerNavigationControllerDelegate: @interface MyCustomViewController : UIViewController <ABPeoplePickerNavigationControllerDelegate> { // .... } A: Finally We settled down with taking picker controller in application delegate and setting its delegate there only by getting viewcontroller from tabBarController array of view controllers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to design a simple keyword content delivery mechanism that functions like Adwords I'm have application that allows users to store food diary entries of approximately 140 characters in length. I am looking for a solution that will allow me to tie content modules (think tips for healthy eating) to the user's diary entries based on keywords in the entry similar to what Google does with adwords. Are there any out-of-the-box solutions that can do that in Rails? Here are the specific requirements: * *User logs food diary entry *In the user's food diary, if there's a specific tip that matches a keyword for the entry, then the tip is displayed next to the entry *Tips would be defined through an admin tool where the admin specifies the tip content and keywords that would make it appear in the diary Trying to figure out a) if there's a pre-build solution I could use for something like this or b) what the best approach would be for performance since the users's food diary might have 20 entries per page, and each entry would have to be evaluated to see if there are any corresponding tips that match entry keywords. For designing a home-grown solution, one idea I had was to make the tip associations when a new food entry is stored like this: * *user adds a food entry *after_save a callback method breaks apart the entry into keywords and searches the tips model for matches *if there's a match, it's stored in an association table when new entries are created rather then when the user's food diary is rendered in the web page. There's a performance hit on storing new entries, but it might allow the user's diary to load faster then doing all those look-ups when the diary is rendered. Does that make sense, or is there a better way? better yet, are there tools that can accomplish what I'm trying to do? Thanks! A: This is not an AdWords API question, but I'll take a shot: * *I would move the association table building into an offline task / cronjob. That would take care of the performance overhead when creating new entries, and users would be generally okay with a message like "Tips are being generated, please be patient" if they happen to view the topic too soon. *I'm not aware of any existing solutions, but this sounds like a hashtag system to me. Basically you have two lists (food dairy entries, tips), you want to assign hashtags to both lists and then pair entries with same hashtags. Googling for a hashtag system / library might be a good starting point. Cheers, Anash
{ "language": "en", "url": "https://stackoverflow.com/questions/7599093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Documentation generated by Yard and spanish accents I'm generating documentation with Yard, and all my comments have been written in Spanish. The problem is that the documentation generated by Yard contains � instead of Spanish accents. I've used "yardoc" command. I'm using ruby 1.8.7 (2011-02-18 patchlevel 334) [i386-mingw32] and Rails 3.0.7 Running on Windows 7 A: Probably your source files are encoded in ISO Latin 1 while Yard expects them to be in UTF-8. You could instruct Yard to read your files in ISO Latin 1 instead of the default UTF-8, but I strongly suggest you to re-encode your source files as UTF-8 files. Any decent text editor should be able to do that with one or two clicks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to parse XML by SAX and Create Tree list? I have learned a tutorial about SAX parser of java and now I need to create tree list of XML file like this: <course> <chapter> <title>chapter one of course one</title> <content> .... </content> </chapter> <chapter> <title>chapter two of course one</title> <content> .... </content> </chapter> </course> and then I what to create data structure like this: string lessons[][] = { {"chapter one of course one", "chapter two of course one"}, {"chapter one of course two", "chapter two of course two", "chapter tree of course two"}, .... .... } A: There is no out-of-box support in JDK for the kind of data structure you are looking for. What you need is a Multimap. Guava library provides this data structure. You can either use that library (I recommend) or build your own. Also, make sure you read my answer in this SO post if your are reading element content using SAX. JAVA SAX parser split calls to characters() A: here you go: THIS is SAX documentation, read and try to build your own parser mate A: Think in terms of a a Stack. In startElement() you push and in endElement you pop(). Depending on the element tag name you do interesting stuff with what's on the stack and perhaps also what you have in a "global" context. A: This code exactly does what you're looking for, You just need to tweak it to output the JSON structure you want. https://github.com/kasmodia/sax-tree-parser
{ "language": "en", "url": "https://stackoverflow.com/questions/7599100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use the wpf dispatcher to create a multi UI thread winforms app The second answer by Martin in this link explains how the dispatcher can be used in a winforms app. This link explains the wpf side. So my question is - can we do this in a winforms app ? If not, why ? thank you UPDATE: I have found this link also that shows the multiple app.run method mentioned by Henk below. However it does not use the wpf dispatcher. I wonder if there is a performance diff between using the wpf dispacther in winforms (my question) vs multiple app.runs A: No matter what you do, you will be limited to using 1 thread (the UI thread) to update your windows (Winforms, WPF, native code). You can spawn as many worker threads as you want to do all the data gathering and prep work you need, however you'll still have to use the UI thread to do the updates. Take a look at the Task or the BackgroundWorker classes to do this work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using ticks to measure absolute time I need to way to get a very precise measurement of current time. The tick value seems to be perfect for this, but the most common way to get it (DateTime.Now) seems to have a fairly loose tolerance (approx ~16ms from what I can tell). There are examples out there that use the StopWatch class to measure deltas using the high resolution timers, but nothing about using those same high resolution counters to measure the current time as ticks. Is there any way to get the current time as ticks that is more precise than DateTime.Now.Ticks? A: See this earlier answer: How to get timestamp of tick precision in .NET / C#? This answer uses a running StopWatch in conjunction with DateTime.Now to give hyper-accurate timing, but it has issues (see all the comments). A: After a fair bit of research, I think that I am hosed. While I can use the methods suggested to track elapsed time, it can't be compared between machines. As MusiGenesis comments, having the high precision timer doesn't really help with what time it is. Thanks for the answers all
{ "language": "en", "url": "https://stackoverflow.com/questions/7599113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Filter duplicates from mysql result depending on column value I'm having some problems working out how to return the desired rows from the following mysql table: first_name last_name collection ========================================== Bob Jones 1 Ted Jones 1 Bob Jones 1 Bob Jones 2 Ted Baker 2 I want to return the count of names based on columns 'first_name' and 'last_name'. Ordinarily it would just be a simple case of using 'group by first_name, last_name', so we would have the following result: a count of 3 for Bob Jones, 1 for Ted Jones, and 1 for Ted Baker. However, the difficulty is the third column 'collection'. I need to exclude duplicate names between collections, but not within collections. So we'd include all names in the count for the first collection, but only include names in the count from the second collection if they do NOT occur in the first collection. So, the desired result would be as follows: a count of 2 for Bob Jones, 1 for Ted Jones, and 1 for Ted Baker. first_name last_name collection included? ========================================== =============== Bob Jones 1 Yes Ted Jones 1 Yes Bob Jones 1 Yes Bob Jones 2 No Ted Baker 2 Yes I have really tried to get my head around this but I am starting to run out of ideas. Any help would be hugely appreciated... thanks! A: Perhaps SELECT first_name, last_name, COUNT( DISTINCT collection) AS cnt FROM yourtable GROUP BY first_name, last_name The COUNT DISTINCT would eliminate the duplicate Bob/Jones/1 records. A: Is this what you are expecting? SELECT u1.first_name, u1.last_name, u1.collection FROM users u1 WHERE u1.collection = (SELECT min(u2.collection) FROM users u2 WHERE u1.first_name = u2.first_name AND u1.last_name = u2.last_name); http://www.sqlfiddle.com/#!2/bd086/7
{ "language": "en", "url": "https://stackoverflow.com/questions/7599115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About DatePart in Date functions I couldn't understand the difference between SELECT DATEDIFF(D,'07/09/1978',GETDATE()) SELECT DATEDIFF(DD,'07/09/1978',GETDATE()) Both are giving the same value. Then what is the difference between D, and DD? I have the same question for * *M, MM *Q, QQ *YY, YYYY Can anybody please explain this to me? A: Here is a reference on dateparts and what they mean: * *DATEPART (Transact-SQL) (MSDN) As you can see, the examples you gave are all identical. However, I know some experts like Aaron Bertrand advocate not using any of the abbreviations, but spelling out the datepart. See his excellent post on this subject here: * *Bad Habits to Kick : Using shorthand with date/time operations
{ "language": "en", "url": "https://stackoverflow.com/questions/7599118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I always keep some static Markers in Android Map? I'm a newbie into Android programming... Here's what I'm trying to do for a small academic project: * *A google map displayed on screen: Done *Get user's current location and show on the map: Done *We've a list of Latitudes and Longitudes coming from a webservice, which forms a pre-defined path. I need to display an always-shown path on the map with static markers as per the list of Lat-Longs given. How? I tried various ways, and searched various places, but couldn't find a satisfactory code or tutorial that has achieved the same. Can someone please point me to an appropriate resource that I can use to get the above? A: Download and check for static marker.................. https://github.com/commonsguy/cw-android/tree/master/Maps/NooYawk http://android-codes-examples.blogspot.com/2011/04/google-map-example-in-android-with-info.html A: You need to implement Overlay and draw the path in the draw() method. Use this SO post to get an idea of how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change header at Included JSP with Spring MVC It is very interesting for me but I have simple Spring MVC application and JSP page. At Jsp pages which are included I would like to add a cookie to my application. However despite of setting it, It could not resolved at runtime. this is the code at my included jsp page. <% response.addCookie(new Cookie("test3","test3")); %> I prefer writing some of the parts of the our application at jsp level over writing at controller. What I can just say is that I am using Tuckey UrlRewrite and at instead of my jsp pages when I call my method, it is working fine. And at my called method I can see that the inital response object at my MVC controller is wrapped by another HttpServletResponse object. It seems that headers and cookies could not be changed after forwarded to jsp? Any help? PS: I have updated my question to make it clear regarding it is jsp included page. A: JSP is part of the response. You need to ensure that that line is exeucted before the response is been committed. Otherwise you end up with IllegalStateException: response already committed in the server logs. So put it in the very top of the JSP page, before any HTML is been sent to the response. Or, better, just put it in a Spring controller or a servlet or filter, far before the forward to JSP takes place. You also need to ensure that you aren't altering the response inside a JSP file which is included by <jsp:include>. It will be plain ignored. See also the RequestDispatcher#include() javadoc: The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementing hash table with both key and index-based access in O(1) There is a data structure called NameObjectCollectionBase in .NET which I'm trying to understand. Basically, it allows to enter arbitrary string => object key/value-pairs with both the possibility of the key and the value being null. A key may be used by multiple objects. Access is granted through both an index-based and a string-based access, whereas the string-based access returns only the first value with the specified key. What they promise, is add(string, object) O(1) if no relocation, O(n) otherwise clear O(1) get(int) O(1) corresponds to getkey(int) get(string) O(1) returns first object found with given key getallkeys O(n) if objects share a key, it is returned that many times getallvalues O(n) getallvalues(type) O(n) returns only objects of a given type getkey(int) O(1) corresponds to get(int) haskeys O(1) if there are objects with a non-null key remove(string) O(n) remove all objects of a given key removeat(int) O(n) set(int, object) O(1) set(string, object) O(1) sets the value of the first found object with given key getenumerator O(1) enumerator over keys copyto(array, int) O(n) Index-based access does have nothing to do with the insertion order. However, get(int) and getkey(int) have to line up with each other. I'm wondering how the structure may be implemented. Allowing both index and key-based access at the same time in O(1) seems not trivial to implement. They state on the MSDN page that "The underlying structure for this class is a hash table." However, the C# Hash tables don't allow multiple values per key and alo not null-keys. Implementing it as a Dictionary<string, List<object> does not seem to be the solution as get(string) would be O(1) but get(int) not since you have to traverse all keys to find out which key has how many items in it. Implementing it as two separated lists where one is a simple List<string> for the keys and a List<Object> for the values in combination of a Dictionary<string, int> which points for each key to the index of the first value would allow both types of access in O(1) but would not allow removing in an efficient way since all indices would have to be updated in the hashtable (would be possible in O(n) but doesn't seem to be the best solution). Or would there be a more efficient way to remove an entry? How could such a data structure be implemented? A: NameObjectCollectionBase uses both a Hashtable and an Arraylist to manage the entries. Have a look for yourself! Microsoft provides reference source code for .NET libraries and can be integrated into Visual Studio: http://referencesource.microsoft.com/ You can even debug the .NET library: http://msdn.microsoft.com/en-us/library/cc667410(VS.90).aspx Or you can grab a copy of dotPeek, a free decompiler: http://www.jetbrains.com/decompiler/
{ "language": "en", "url": "https://stackoverflow.com/questions/7599137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Testing if rows of a matrix or data frame are sorted in R What is an efficient way to test if rows in a matrix are sorted? [Update: see Aaron's Rcpp answer - straightforward & very fast.] I am porting some code that uses issorted(,'rows') from Matlab. As it seems that is.unsorted does not extend beyond vectors, I'm writing or looking for something else. The naive method is to check that the sorted version of the matrix (or data frame) is the same as the original, but that's obviously inefficient. NB: For sorting, a la sortrows() in Matlab, my code essentially uses SortedDF <- DF[do.call(order, DF),] (it's wrapped in a larger function that converts matrices to data frames, passes parameters to order, etc.). I wouldn't be surprised if there are faster implementations (data table comes to mind). Update 1: To clarify: I'm not testing for sorting intra-row or intra-columns. (Such sorting generally results in an algebraically different matrix.) As an example for creating an unsorted matrix: set.seed(0) x <- as.data.frame(matrix(sample(3, 60, replace = TRUE), ncol = 6, byrow = TRUE)) Its sorted version is: y <- x[do.call(order, x),] A proper test, say testSorted, would return FALSE for testSorted(x) and TRUE for testSorted(y). Update 2: The answers below are all good - they are concise and do the test. Regarding efficiency, it looks like these are sorting the data after all. I've tried these with rather large matrices, such as 1M x 10, (just changing the creation of x above) and all have about the same time and memory cost. What's peculiar is that they all consume more time for unsorted objects (about 5.5 seconds for 1Mx10) than for sorted ones (about 0.5 seconds for y). This suggests they're sorting before testing. I tested by creating a z matrix: z <- y z[,2] <- y[,1] z[,1] <- y[,2] In this case, all of the methods take about 0.85 seconds to complete. Anyway, finishing in 5.5 seconds isn't terrible (in fact, that seems to be right about the time necessary to sort the object), but knowing that a sorted matrix is 11X faster suggests that a test that doesn't sort could be even faster. In the case of the 1M row matrix, the first three rows of x are: V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 1 3 1 2 2 3 1 3 3 2 2 2 1 1 1 3 2 3 2 3 3 2 3 3 3 1 2 1 1 2 1 2 3 There's no need to look beyond row 2, though vectorization isn't a bad idea. (I've also added the byrow argument for the creation of x, so that row values don't depend on the size of x.) Update 3: Another comparison for this testing can be found with the sort -c command in Linux. If the file is already written (using write.table()), with 1M rows, then time sort -c myfile.txt takes 0.003 seconds for the unsorted data and 0.101 seconds for the sorted data. I don't intend to write out to a file, but it's a useful comparison. Update 4: Aaron's Rcpp method bested all other methods offered here and that I've tried (including the sort -c comparison above: in-memory is expected to beat on-disk). As for the ratio relative to other methods, it's hard to tell: the denominator is too small to give an accurate measurement, and I've not extensively explored microbenchmark. The speedups can be very large (4-5 orders of magnitude) for some matrices (e.g. one made with rnorm), but this is misleading - checking can terminate after only a couple of rows. I've had speedups with the example matrices of about 25-60 for the unsorted and about 1.1X for the sorted, as the competing methods were already very fast if the data is sorted. Since this does the right thing (i.e. no sorting, just testing), and does it very quickly, it's the accepted answer. A: If y is sorted then do.call(order,y) returns 1:nrow(y). testSorted = function(y){all(do.call(order,y)==1:nrow(y))} note this doesn't compare the matrices, but it doesn't dip out as soon as it finds a non-match. A: Well, why don't you use: all(do.call(order, y)==seq(nrow(y))) That avoids creating the ordered matrix, and ensures it checks your style of ordering. A: Newer: I decided I could use the Rcpp practice... library(Rcpp) library(inline) isRowSorted <- cxxfunction(signature(A="numeric"), body=' Rcpp::NumericMatrix Am(A); for(int i = 1; i < Am.nrow(); i++) { for(int j = 0; j < Am.ncol(); j++) { if( Am(i-1,j) < Am(i,j) ) { break; } if( Am(i-1,j) > Am(i,j) ) { return(wrap(false)); } } } return(wrap(true)); ', plugin="Rcpp") rownames(y) <- NULL # because as.matrix is faster without rownames isRowSorted(as.matrix(y)) New: This R-only hack is the same speed for all matrices; it's definitely faster for sorted matrices; for unsorted ones it depends on the nature of the unsortedness. iss3 <- function(x) { x2 <- sign(do.call(cbind, lapply(x, diff))) x3 <- t(x2)*(2^((ncol(x)-1):0)) all(colSums(x3)>=0) } Original: This is faster for some unsorted matrices. How much faster will depends on where the unsorted elements are; this looks at the matrix column by column so unsortedness on the left side will be noticed much faster than unsorted on the right, while top/bottomness doesn't matter nearly as much. iss2 <- function(y) { b <- c(0,nrow(y)) for(i in 1:ncol(y)) { z <- rle(y[,i]) b2 <- cumsum(z$lengths) sp <- split(z$values, cut(b2, breaks=b)) for(spi in sp) { if(is.unsorted(spi)) return(FALSE) } b <- c(0, b2) } return(TRUE) } A: Well, the brute-force approach is to loop and compare, aborting as soon as a violation is found. That approach can be implemented and tested easily in R, and then be carried over to a simple C++ function we can connect to R via inline and Rcpp (or plain C if you must) as looping is something that really benefits from an implementation in a compiled language. Otherwise, can you not use something like diff() and check if all increments are non-negative? A: You can use your do.call statement with is.unsorted: issorted.matrix <- function(A) {!is.unsorted(do.call("order",data.frame(A)))}
{ "language": "en", "url": "https://stackoverflow.com/questions/7599146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: deploy java jar remotely during maven build I have a small maven project that build a java jar file. I added a plugin (maven-antrun-plugin) in order to start it during maven's build phase. This also works in the build server (Continuum) which is good. Now I would also like to copy the artifact jar to another server. What is the best way for doing that? I saw that you can make maven execute bash script, would that be a good way? thanks! A: It depends on your server and what options you have for uploading jars there. One of the options could be to use Maven Wagon plugin, which supports number of protocols, including ssh, ftp, webdaw.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you use Google Analytics with an intranet? Can you use Google Analytics with an intranet? I'm using Liferay as my intranet. When setting up GA, you need to specify the Default URL starting with . What would I specify in there if my intranet can be accessed by http://cs22web or by ip address? A: A quick google of your question has led me to this page: How do I run Google Analytics on my intranet? Quote: In order for Google Analytics to populate reports for your intranet usage, your corporate network needs to reach the ga.js JavaScript at http://www.google-analytics.com/ga.js http://www.google-analytics.com/__utm.gif https://ssl.google-analytics.com/ga.js https://ssl.google-analytics.com/__utm.gif If you can reach the above URL using your network's internet connection, you have satisfied the first requirement. Additionally, your intranet must be accessed using a fully qualified domain name (FQDN) such as http://intranet.example.com. The ga.js JavaScript will not work if your intranet is accessed using a non-FQDN (such as http://intranet). I hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7599160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When and why should I clean the build in XCode Every once in awhile, the solution to an aggravating problem in XCode is to hit Product → Clean, and this seems to clear some cache and problems disappear. But what is it actually doing? And more importantly, WHEN should I be doing this? It seems to be necessary more often when dealing with Core Data, but I haven't really been tracking it. As a side question, WHY is this necessary? XCode seems to do a lot of stuff in the background (autosave, autocompile, etc). Why doesn't this also just happen in the background? A: It's because there are a lot difference when you are working with a very very big project with a lot of files and objects. Imagine that you need an hour to recompile a entire project, so you will think before do this. But in our world, this is a fast task. XCode use the make program. So, it compile only what was changed. I can list same cases you need do this: * *Always you will create a App for App Store. This safety thing to do. *Always you use the XCode Snapshot. I have bad time when I restore a project and build the app. XCode used old compiled files and a lot of time was lost to search it. *Maybe when you restore a old code with git. Is the same idea of the Snapshot *When you delete or rename a file in project. It don't delete the compiled file, so the program can work, but if you recompile, will see the errors. *When you see that sometime the build have a strange behavior. Or only to have certain that XCode use only your newer files. I don't remember exactly but i have seen the build use old #defines. Rebuilding can make you more safe about your program. But don't need do this all time. A: I am almost certain that XCode loses track of things and sometimes it doesn't recompile (or link, not sure) everything is needed. I have to resort to clean and build all most often than it should. Maybe it's just me, but I doubt it... XCode is the IDE with most bugs I have worked with
{ "language": "en", "url": "https://stackoverflow.com/questions/7599161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can MSBuild exclude "Hidden" Web Deploy parameters from the generated SetParameters.xml? In my Parameters.xml file, I have a couple of parameters that use the Web Deploy "variable" syntax to refer to other parameters, like this one that refers to the IIS Web Application Name parameter: <parameter name="MyParam" defaultValue="{IIS Web Application Name}/Web.config" tags="Hidden"/> My problem is that VS automatically imports this parameter into my SetParameters.xml file when I build the deployment package in spite of it being tagged as hidden. When it is passed to msdeploy via setParamFile, Web Deploy literally interprets the value of the parameter as {IIS Web Application Name}/Web.config rather than substituting the IIS application name. If I remove the parameter from the auto-generated SetParameters.xml file, the variable works as expected. Is there any way to prevent VS from including that parameter in the first place, either by name or by tag? A: This was actually far easier than I thought, given the answer to my earlier question. I just needed to add a Hidden tag in the target that follows AddIisAndContentDeclareParametersItems. This apparently sets the tag in the source manifest prior to the package being built. It ends up looking something like this: <Target Name="DeclareCustomParameters" AfterTargets="AddIisAndContentDeclareParametersItems"> <ItemGroup> <MsDeployDeclareParameters Include="Foo"> <!-- <snip> --> <!-- the following elements are the important ones: --> <Tags>Hidden</Tags> <ExcludeFromSetParameter>True</ExcludeFromSetParameter> </MsDeployDeclareParameters> </ItemGroup> </Target> That was it! A: This answer is for anyone else looking for a more complete example of substitution via targets. This example shows substituting a variable "database server name" into a connection string. The ExcludeFromSetParameter element appears to be the key to making substitution work as it keeps the param out of the SetParameters.xml file (as the OP mentioned he did manually). Unfortunately, I don't think that ExcludeFromSetParameter can be set from a parameters.xml file, so this is the only option... <Target Name="DeclareCustomParameters" BeforeTargets="Package"> <ItemGroup> <MsDeployDeclareParameters Include="DatabaseServer"> <Description>Location of the database server hosting the user database</Description> <Value>localhost</Value> <DefaultValue>localhost</DefaultValue> <Tags>DBServer, SQL</Tags> </MsDeployDeclareParameters> <MsDeployDeclareParameters Include="DB Connection String"> <Kind>XmlFile</Kind> <Scope>Web.config</Scope> <Match>/configuration/connectionStrings/add[@name='Database']/@connectionString</Match> <Description>The connection string to the Database</Description> <DefaultValue>Data Source={DatabaseServer};Initial Catalog=MyDatabase;Integrated Security=true;MultipleActiveResultSets=true;</DefaultValue> <Tags>Hidden</Tags> <ExcludeFromSetParameter>True</ExcludeFromSetParameter> </MsDeployDeclareParameters> </ItemGroup> </Target>
{ "language": "en", "url": "https://stackoverflow.com/questions/7599166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Flipped NSView mouse coordinates I have a subclass of NSView that re-implements a number of the mouse event functions. For instance in mouseDown to get the point from the NSEvent I use: NSEvent *theEvent; // <- argument to function NSPoint p = [theEvent locationInWindow]; p = [self convertPoint:p fromView:nil]; However the coordinates seem to be flipped, (0, 0) is in the bottom left of the window? EDIT: I have already overridden the isFlipped method to return TRUE, but it has only affected drawing. Sorry, can't believe I forgot to put that straight away. A: What do you mean by flipped? Mac uses a LLO (lower-left-origin) coordinate system for everything. EDIT I can't reproduce this with a simple project. I created a single NSView implemented like this: @implementation FlipView - (BOOL)isFlipped { return YES; } - (void)mouseDown:(NSEvent *)theEvent { NSPoint p = [theEvent locationInWindow]; p = [self convertPoint:p fromView:nil]; NSLog(@"%@", NSStringFromPoint(p)); } @end I received the coordinates I would expect. Removing the isFlipped switched the orientation as expected. Do you have a simple project that demonstrates your problmem? A: I found this so obnoxious - until one day I just sat down and refused to get up until I had something that worked perfectly . Here it is.. called via... -(void) mouseDown:(NSEvent *)click{ NSPoint mD = [NSScreen wtfIsTheMouse:click relativeToView:self]; } invokes a Category on NSScreen.... @implementation NSScreen (FlippingOut) + (NSPoint)wtfIsTheMouse:(NSEvent*)anyEevent relativeToView:(NSView *)view { NSScreen *now = [NSScreen currentScreenForMouseLocation]; return [now flipPoint:[now convertToScreenFromLocalPoint:event.locationInWindow relativeToView:view]]; } - (NSPoint)flipPoint:(NSPoint)aPoint { return (NSPoint) { aPoint.x, self.frame.size.height - aPoint.y }; } - (NSPoint)convertToScreenFromLocalPoint:(NSPoint)point relativeToView:(NSView *)view { NSPoint winP, scrnP, flipScrnP; if(self) { winP = [view convertPoint:point toView:nil]; scrnP = [[view window] convertBaseToScreen:winP]; flipScrnP = [self flipPoint:scrnP]; flipScrnP.y += [self frame].origin.y; return flipScrnP; } return NSZeroPoint; } @end Hope this can prevent just one minor freakout.. somewhere, someday. For the children, damnit. I beg of you.. for the children. A: This code worked for me: NSPoint location = [self convertPoint:theEvent.locationInWindow fromView:nil]; location.y = self.frame.size.height - location.y; A: This isn't "flipped", necessarily, that's just how Quartz does coordinates. An excerpt from the documentation on Quartz 2D: A point in user space is represented by a coordinate pair (x,y), where x represents the location along the horizontal axis (left and right) and y represents the vertical axis (up and down). The origin of the user coordinate space is the point (0,0). The origin is located at the lower-left corner of the page, as shown in Figure 1-4. In the default coordinate system for Quartz, the x-axis increases as it moves from the left toward the right of the page. The y-axis increases in value as it moves from the bottom toward the top of the page. I'm not sure what your question is, though. Are you looking for a way to get the "flipped" coordinates? If so, you can subclass your NSView, overriding the -(BOOL)isFlipped method to return YES.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do you include a class from /lib into your code in app/controllers I have a class sitting in /lib folder. It's in a file called mailing.rb And I would like to use this class in codes from app/controller. How do i do this? A: I believe you need to add an initializer file with the require statement in it, for example if your lib file is /lib/some_module.rb you would need to create an initialiser file in /config/initializers/require_libs.rb... # /config/initializers/require_libs.rb require 'some_module' A: Rails 3 no longer automatically loads the files from lib. In your application.rb file, you can add lib to your autoload_paths: config.autoload_paths += Dir["#{Rails.root}/lib"] This way, your mailer.rb and all other files in lib will be available to the rest of your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iPhone - How to save each view controller? When my app's “applicationWillTerminate” function is called in the app’s delegate file I need to loop through each child controller of a tab controller and save the current state it is in. Is it possible to loop through each viewController calling a custom save function? A: Get the tabBarController.viewControllers and send the makeObjectsPerformSelector:@selector(yourCustomSaveMethod) message to that array. A: Have a look at UIApplicationWillTerminateNotification and UIApplicationDidEnterBackgroundNotification. Much nicer than looping through your view controllers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Format mask a currency amount in Oracle ApEx I have a cost field in my Oracle ApEx form where the user may enter an $ amount of say 10000.00 or more or even less. My question is, how to format mask and validate this value within my ApEx form? A: Don't you just need the settings of the item? For example, when you create or edit an item of type number field, you can set the following (Edit Page Item):
{ "language": "en", "url": "https://stackoverflow.com/questions/7599178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Express & Jade, templates adding code to the layout I'm playing around with an Express site with Node.JS I have a layout file which, let's say, looks like this: html title foo body!= body From what I have been able to understand, the output of the template is inserted into a variable called body and that's added to the layout there on the 3rd line. However, if I wanted a template to add, for example, a <meta> tag in the <head> element, how would I do that? I did see the explanation of extending templates and using blocks, but I'm not sure how that ties it to using layouts. The templates themselves shouldn't be extending the layout, right? Or, does template inheritance remove the need for layouts at all? I would suspect not, but I'm not sure. Also, since I'm here, how do you specify a different layout to be used, or for no layout to be used at all. Currently, the views are being rendered like this: res.render('templateName', { myTemplateVars : 'foo' }); A: What you are asking for was released 3 days ago. http://tjholowaychuk.com/post/10695801204/jade-stylus-0-16-0-released I have personally been using it for a few weeks and love the recent additions. The block statement allows you to specify default content and any extension template can override a named block. Basically, blocks override, includes append and extends chooses your parent template. A: Try dust template engine. It is far more interesting and designer friendly. In dust you can write base.html: <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <title>kiss.js example</title> <link rel="stylesheet" href="/css/css1.css" /> <link rel="stylesheet" href="/css/css2.css" /> <script type="text/javascript" src="/js/js1.js"></script> <script type="text/javascript" src="/js/js2.js"></script> {+head/} </head> <body> <div style="height: 100%"> <div id="header"> <h1>kiss.js example - {+header}{/header}</h1> {+header_buttons}{/header_buttons} </div> <div id="content"> {+content}{/content} </div> <div id="footer"> <table> <tr> <td> &nbsp;&nbsp; </td> <td style="width: 100%; text-align: center;">made with kiss.js</td> <td>{+footer_buttons}{/footer_buttons}</td> </tr> </table> </div> </div> </body> and view.html: {>base.html/} {<content} <h2>name: {name}</h2> <h3>{foo}</h3> {#numbers} <div>{.}</div> {/numbers} {/content}
{ "language": "en", "url": "https://stackoverflow.com/questions/7599180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cell editor not exiting when row is deleted I have a JTable with a several columns, one of which is has a custom renderer to display 3 buttons in a JPanel as well as a custom editor to allow them to be clickable. One of the buttons sends a delete command to our server for that row id then reloads the table data from the server by clearing the data model and loading data again. When this happens the cell with the 3 buttons continues to display (but not the rest of the row) until I click another button in another row even though the row is gone. I've set putClientProperty("terminateEditOnFocusLost", Boolean.TRUE) but changing focus to another component does not help. I've tried deleting the row itself before refreshing the data (even deleted all the rows) and made sure to call fireTableRowsDeleted(). I've also tried calling the cancelCellEditing() and stopCellEditing() functions of the TableCellEditor and even manually setting the editing row/column to another cell. Any help would be greatly appreciated. Ok, so I figured it out. I ended up calling removeEditor() on the table and that fixed it. Thanks for the responses. A: I've set putClientProperty("terminateEditOnFocusLost", Boolean.TRUE) but changing focus to another component does not help. That method should be invoked when you create the table, not in the actionPerformed method when you click the button. A: Ok, so I figured it out. I ended up calling removeEditor() on the table just before the data refresh and that fixed it. Thanks for the responses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assign .vcproj files to Visual Studio 2008, when Visual Studio 2010 installed I have encountered a strange error. I use Windows 7 x64. Visual Studio 2010 (VS10) and Visual Studio 2008 (VS08) are both installed. Now i want to make sure that when i doubleclick open a .vcproj file it is being opened by VS8 and not VS10. Now this seems like a trivial problem, but: "righclick -> open with -> choose default program -> select devenv.exe of VS08 -> always open with" doesnt work. In fact after browsing for devenv.exe of VS08 it does not show up in the list/menue where it is supposed to be displayed. This is very strange and annoying, maybe someone already encountered this error and know a solution. A: I GOT IT! For the Express versions at least. I strongly suspect these instructions can be modified to apply to the full version. The names will change of course. I spent a lot more time on this than I will ever save by being able to click through to the correct IDE, but darn it, I just hate to give up. Here's the deal. Strangely, the associations seem to be keyed to the program file names. (Say, what?? That sure is the way it looks to me.) Both VC++ Express 2008 and 2010 are named VCExpress.exe. We'll give the 2008 version an alias. We'll also use a doppelganger to pull off something of a ruse. * *Navigate to "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE". Make a copy of VCExpress.exe, (not a shortcut), and re-name it VCExpress-2008.exe. (It would probably do just to re-name the original and use the new name in step 3.) *Open regedit.exe. Create a new key HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\VSExpress-2008.exe *Edit the (default) value in that key, to hold the string "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\VCExpress.exe" [sic] *Go through the drill with the file-association dialog again. Right-click, open with, choose default program, yada, yada, yada. Browse your way down to C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE and click on VSExpress-2008.exe. *VCExpress-2008 now shows up as a program in good standing, with its icon proudly displayed on the front page above the fold. (Don't tell the dialog, but you and I know it really points to VCExpress.exe, not the copy we made.) Click it. *Celebrate. A: Ok i finally found a way. You can use the application "default programs editor" to mess with the standard file associations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Page must refresh after seconds set in php variable I've been through the forum and tried this post (http://stackoverflow.com/questions/7128417/stop-javascript-auto-refresh-after-fix-time-for-example-1-min). I'm busy with a testing site. Different tests has different time limits, eg test A = 3600 and test B = 2400 which is stored in a table. When the test is started the time is stored in a variable. What I am trying to achieve is that the page needs to refresh after 3600 or 2400 depending on the test or run a script that checks if the time has expired and log the user out. Can someone point me in the right direction? Currently I am using <head> <meta http-equiv="refresh" content="3600"> which works but how do I change it for test B then? A: If you're calculating the time until the refresh in php, using a <meta> tag to simulate an http header seems a bit weird to me. Just send the header straight away: <?php header('Refresh: ' . $timeLimit); A: If the test A and test B are in two different variables (say, $variableA and $variableB) just use the following. <meta http-equiv="refresh" content="<?php echo $variableA; ?>"> A: If the refresh interval is in a PHP variable called $refresh, this should do: <head> <meta http-equiv="refresh" content="<?php echo $refresh?>">
{ "language": "en", "url": "https://stackoverflow.com/questions/7599189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shift bits from a byte into an (array) I solved the problem but dont know how to post it in a good manner, so I edit this post and put the solution in the end of it. Need help with following in C, trying to shift a bytes bits to reverse order. I want Step1[] = {1,0,0,1,0,0,0,0}; to become {0,0,0,0,1,0,0,1}. void Stepper(void) { static uint8_t Step1[] = {1,0,0,1,0,0,0,0}; BridgeControl(Step1); } void BridgeControl(unsigned char *value) { uint8_t tempValue; uint8_t bit = 8; uint8_t rev = 1; if (rev) // CW otherwise CCW { tempValue = *value; do{ if(tempValue) // Right-shift one tempValue = 1 >> 1; else tempValue = 0 >> 1; }while(--bit, bit); *value = tempValue; } I know the bridcontrol is totally wrong, here i could need help! Kind Regards New code: void BridgeControl(uint8_t *value) { // For example, initial value could be 1001000 then I // would like the outcome to be 00001001 uint8_t tempValue; uint8_t bit = 3; uint8_t rev = 1; if (rev) // CW otherwise CCW { tempValue = *value; //so... its 0b10010000 do{ tempValue >>=1; //1st this produce 01001000 tempValue = 0 >> 1; //1st this produce 0010 0100 //2nd time produce 0001 0010 //3d time produce 0000 1001 }while(--bit, bit); *value = tempValue; } M1BHI = value[7]; M1BLI = value[6]; M1AHI = value[5]; M1ALI = value[4]; M2BHI = value[3]; M2BLI = value[2]; M2AHI = value[1]; M2ALI = value[0]; } Solution: void BridgeControl(uint8_t value) { uint8_t tempvalue[8]; uint8_t i = 8; uint8_t cont; cont = value; do{ value = value >> i-1; value = value & 1; tempvalue[8-i] = value; value = cont; }while(--i,i); M1BHI = tempvalue[7]; M1BLI = tempvalue[6]; M1AHI = tempvalue[5]; M1ALI = tempvalue[4]; M2BHI = tempvalue[3]; M2BLI = tempvalue[2]; M2AHI = tempvalue[1]; M2ALI = tempvalue[0]; } If I want the reversed order of the bits in the array, just change tempvalue[8-i] to tempvalue[i-1]. A: Your variable names sounds like you are trying to work with hardware. So i guess you really want to shift bits in one byte variable and not in an int array. This statment reverses the bits in a byte: byte reversedVal = (byte) (val & 1 << 7 + val & 2 << 5 + val & 4 << 3 + val & 8 << 1 + val & 16 >> 1 + val & 32 >> 3 + val & 64 >> 5 + val & 128 >> 7); If you really want to reverse a int array you can use LINQs Reverse method as suggested by scottm but thats probably not the fastest option. A: Easy-cheesy with Array.Reverse(): byte[] step1 = new {0,1,0,1}; var reversed = Array.Reverse(step1); If you actually need to swap endianess, you can look at the answer here. A: void BridgeControl(unsigned char values[], int size){ unsigned char *head, *end, wk; for(head = values, end = values + size - 1; head < end; ++head, --end){ wk = *head; *head = *end; *end = wk; } } void Stepper(void){ static unsigned char Step1[] = {1,0,0,1,0,0,0,0}; BridgeControl(Step1, sizeof(Step1)); } A: // changed the parameter to suit the type of members of array void BridgeControl(uint8_t *value) { uint8_t tempvalue; // only need to loop till midway; consider the two sides as lateral images of each other from the center for (int i=0; i < 8/2; i++) { // preserve the current value temporarily tempvalue = *[value + i]; // set the current value with the value in the mirrored location // (8th position is the mirror of 1st; 7th position is the mirror of 2nd and so on) *[value + i] = *[value + (7 - i)]; // change the value in the mirrored location with the value stored temporarily *[value + (7 - i)] = tempvalue; } } // you may want to use sizeof(uint8_t) * (7 - i) instead of (7 - i) above A: //Exempel of input going to function: int value = 0b10010000; void BridgeControl(uint8_t value uint8_t dir) { uint8_t tempvalue[8]; uint8_t i = 8; uint8_t cont; cont = value; if (dir){ do{ value = value >> i-1; value = value & 1; tempvalue[8-i] = value; value = cont; }while(--i,i); } else{ do{ value = value >> i-1; value = value & 1; tempvalue[i-1] = value; value = cont; }while(--i,i); } M1BHI = tempvalue[7]; M1BLI = tempvalue[6]; M1AHI = tempvalue[5]; M1ALI = tempvalue[4]; M2BHI = tempvalue[3]; M2BLI = tempvalue[2]; M2AHI = tempvalue[1]; M2ALI = tempvalue[0]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to send Javascript/jQuery array over URL paramter to PHP? Here's my script, this works fine... send_array_to_other_page.html $(function(){ //DECLARE ARRAY var arr = new Array(); var i = 0; $('#form').submit(function(e){ e.preventDefault(); var value = $('#box').val(); var index = arr.length; var list = ''; //ADD VALUE TO ARRAY arr[index] = value; //OUTPUT VALUES IN ARRAY for (var index in arr){ list+=index+': '+arr[index]+'<br/>'; $('#arrLength').html(arr.length); } //DISPLAY ARRAY $('#display').html(list); $('#form').get(0).reset(); //RESET FORM }); $('#submit').click(function(){ window.location = 'send_array_to_other_page_2.php?list='+arr; }); }); This doesn't. It outputs Array content lost. Id also like to point out the the url of this page is send_array_to_other_page_2.php. Its missing the ?list= <?php $arr = $_GET['list']; echo 'The contents of the array are still... <br/>'; if(isset($arr)){ print_r($arr); } else { echo 'Array content lost'; } ?> A: Don't sent 'long' data over a URL. Most browsers have a length limit and it's very easy to exceed that and end up with corrupted data. For 'big' data, use a POST, which is not limited. To send the array itself, just do an AJAX request and let jquery encode the array into JSON. You then handle it in PHP with json_decode() and you'll end up with a native PHP array. A: $(function(){ //DECLARE ARRAY arr = new Array(); var i = 0; $('#form').submit(function(e){ e.preventDefault(); var value = $('#box').val(); var index = arr.length; var list = ''; //ADD VALUE TO ARRAY arr[index] = value; //OUTPUT VALUES IN ARRAY for (var index in arr){ list+=index+': '+arr[index]+'<br/>'; $('#arrLength').html(arr.length); } //DISPLAY ARRAY $('#display').html(list); $('#form').get(0).reset(); //RESET FORM }); $('#submit').click(function(){ window.location = 'send_array_to_other_page_2.php?list='+arr; }); }); Try without the var arr to make it global, I don't believe the sub functions are parsing it. A: Edit: Updated the JavaScript on jsfiddle based on your comment. On "submit", the array is saved at the "#form" element using the .data() method. On "click" of the "#submit" button, that data is retrieved and the url is build up. The click event does fire before the submit event (at least in my Firefox 7), so your array is empty when concatenated to the URL string. I put together some JavaScript on jsfiddle that might help. You do not really need to bind to the click event of the submit-button, just do the "redirect" in the submit handler function. You are building your string list there anyways. So there would no confusion what fires first, the click or the form submit event. As for the serialization of your array, I used jQuery's .each() function but there is nothing wrong doing it by hand (if done correctly). I could also imagine that the form is actually posted and this is why you do not see the "?list" search part of the URL. If you don't need a complete redirect, why don't you send the data using jQuery.get()?
{ "language": "en", "url": "https://stackoverflow.com/questions/7599196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cancel a keypressed event throught handler function (addEventListener function) I would like to create a test function which change the '.' charachter into ',' character in a text box. I cannot change the server side since it is google doc. '56.3' is considered as a number but '56,3' is (!). Let's say that I have used the code below : function changeValue(e) { e = window.event || e; var keyCode = e.charCode || e.keyCode; if (String.fromCharCode(keyCode)==='.') { event.target.value+=","; return false; } return true; } function start_up () { console.log('Start'); var tmp = document.getElementById('ss-form'); tmp = tmp.getElementsByTagName('input'); console.log(tmp); for(var i=0; i<tmp.length; i++) { tmp[i].addEventListener('keypress',changeValue, false); console.log(i, tmp[i]); } }; window.addEventListener("load",start_up, false); Then the problem is that both ',' and '.' are added to the field. How can I cancel the '.' pressed event? How can I replace the '.' pressed event by ',' pressed event? I have searched the Internet and see no solution with the 'addEventListener' function. A: Using e.preventDefault() should do it. I got a jsFiddle demo put together: http://jsfiddle.net/yrYH4/ A: It may be because you are returning true from the event handler. You can use event.preventDefault or return false to prevent default actions from being taken - you are returning false from the inner if statement of your handler, then returning true from the main function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Count Hyperlinks of a Website Possible Duplicate: How to parse HTML with PHP? i want to write a php-program that count all hyperlinks of a website, the user can enter. how to do this? is there a libary or something which i can parse and analyze the html about the hyperlinks? thanks for your help A: Like this <?php $site = file_get_contents("someurl"); $links = substr_count($site, "<a href="); print"There is {$links} in that page."; ?> A: Well, we won't be able to give you a finite answer but only pointers. I've done a search engine once out of php so the principle will be the same: * *First of all you need to code your script as a console script, a web script is not really appropriate but it's all a question of tastes *You need to understand how to work with sockets in PHP and make requests, look at the php socket library at: http://www.php.net/manual/ref.network.php *You will need to get versed in the world of HTTP requests, learn how to make your own GET/POST requests and split the headers from the returned content. *Last part will be easy with regexp, just preg_match the content for "#()*#i" (the last expression might be wrong, i didn't test it at all ok?) *Loop the list of found hrefs, compare to already visited hrefs (remember to take into account wildcard GET params in your stuff) and then repeat the process to load all the pages of a site. It IS HARD WORK... good luck A: You may have to use CURL to fetech the contents of the webpage. Store that in a variable then parse it for hyperlinks. You might need regular expression for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't understand what this code do Can anyone help me with explanation what this line do (UserList *) malloc(sizeof(UserList)); I'm new to C world. What I understand is that allocate memory for Userlist type. If so why definition is not just Userlist malloc(sizeof(UserList)) ? A: What this code is doing is allocating dynamic memory for a structure of type UserList. The previous expression, (UserList*) tells the compiler of what type to treat that value returned by malloc. As malloc is generic in C and can return a pointer to any type (effectively in C terminology, void*), you can tell the compiler what type do you expect this pointer points to. This usually happens in the context of an initialization of a variable of type UserList*: UserList* user_list = (UserList *) malloc(sizeof(UserList)); Note how the variable getting the result is a pointer to the correct type. You can access to the structure pointed by the pointer in this new allocated memory using the normal *user_list syntax. A: malloc returns a pointer (memory location) to the memory allocated. The * means a "pointer to" a UserList rather than the userlist itself. I'm not sure if this line is a declaration or a statement. If it's a statement then the brackets cause the type of the pointer returned to be cast to "pointer to UserList" rather than "void *" meaning pointer to anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: DSPACK example for converting audio sample rate on the fly? I am using DSPACK with Delphi 6 Pro. I am looking for a good sample that shows how to create a filter graph that will convert the sample rate of an audio stream to a desired format (sample rate, bit depth, and number of channels) in real time. Does anyone know of a good example project that shows how to structure the filter graph with DSPACK to do this? If not with DSPACK, then if you know of a good example or web page that discusses the general DirectX filter graph concepts involved, I can use that. I also know C/C++ and can follow a C# example well enough. A: You need a resampling filter to do this. Options include: * *implement a filter which does Audio Resampling * *using some resample code/library, see Free Resampling Software *wrapping Media Foundation Audio Resampler DSP, if you are OK with its runtime requirements *use third party filter Having such filter available, you will need to build a transcoding graph with audio source, resampler and target of your conversion (such as file). Also as far as I remember, that stock ACM Wrapper Filter is capable of converting PCM audio between standard sample rates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to disable all other rows EXCEPT in EDIT mode Possible Duplicate: Disable the Edit button on all the rows when Edit button is clicked on a particular row in GridView how to disable all other rows except the one in EDIT mode? i am trying to find a way to disable all other row while i am in edit mode of course except the edit one. here is my gridview looks like: <gridview.... <edittemplate...> ................ </edittemplate> ............ <asp:CommandField ButtonType="Link" ItemStyle-HorizontalAlign="Center" SelectText="Select" EditText="Edit" UpdateText="Save" ShowEditButton="true" /> </Columns> </asp:GridView> A: You need to handle RowEditing event of GridView to disable all rows except edit one. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; //Put binding code here.. GridView1.DataBind(); foreach (GridViewRow row in GridView1.Rows) { if (row.RowIndex != e.NewEditIndex) { row.Enabled = false; } } } EDIT: In addition to this code please verify the Page_load method's Binding code. protected void Page_load() { if(!IsPostBack) { //put GridView databinding code here } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting Hyper-V snapshot's name programmatically I'm creating an Hyper-V snapshot with a C# program: private static bool Snapshot(string vmName, string snapshotName) { var result = false; var scope = new ManagementScope(@"root\virtualization", null); var virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService"); var vm = Utility.GetTargetComputer(vmName, scope); var inParams = virtualSystemService.GetMethodParameters("CreateVirtualSystemSnapshot"); inParams["SourceSystem"] = vm.Path.Path; var outParams = virtualSystemService.InvokeMethod("CreateVirtualSystemSnapshot", inParams, null); if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started) { if (Utility.JobCompleted(outParams, scope)) { Console.WriteLine("Snapshot was created successfully."); result = true; } else { Console.WriteLine("Failed to create snapshot VM"); result = false; } } else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed) { Console.WriteLine("Snapshot was created successfully."); result = true; } else { Console.WriteLine("Create virtual system snapshot failed with error {0}", outParams["ReturnValue"]); result = false; } inParams.Dispose(); outParams.Dispose(); vm.Dispose(); virtualSystemService.Dispose(); return result; } (NOTE: This code was taken from MSDN) Is there a way to set the snapshot name through this WMI call ? Otherwise, does anyone know a working solution to rename a snapshot through WMI call? I already found this thread, but it's some kind of ambiguous and it doesn't provide any solution ... EDIT: The solution was to rename snapshot after having create it. Here's my function to rename the snapshot using Hans advice: SOLUTION: public static bool RenameSnapshot(string vmName, string snapshotName) { var result = false; var scope = new ManagementScope(@"root\virtualization", null); var vm = Utility.GetTargetComputer(vmName, scope); // load snapshot var objSnapshot = GetLastVirtualSystemSnapshot(vm); // rename snapshot objSnapshot["ElementName"] = snapshotName; // save var virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService"); var inParams = virtualSystemService.GetMethodParameters("ModifyVirtualSystem"); inParams["ComputerSystem"] = vm.Path.Path; inParams["SystemSettingData"] = objSnapshot.GetText(TextFormat.CimDtd20); var outParams = virtualSystemService.InvokeMethod("ModifyVirtualSystem", inParams, null); if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed) { result = true; } else { result = false; } inParams.Dispose(); outParams.Dispose(); vm.Dispose(); virtualSystemService.Dispose(); return result; } A: You have to use the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class to rename a hyper-v snapshot. There is a MSDN example on how to rename a hyper-v virtual machine (You have to modify the code in order to rename a snapshot). Furthermore I've found this example on how to rename a hyper-v snapshot. Hope, this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unknown character ı̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̨̨̨̨̨̨̨̨ This is a bit a silly question, but I stumbled upon this strange "character" today ı̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̸̨̨̨̨̨̨̨̨ Try to copy it in a text editor, you will see that you have to press backspace several times in order to erase it => I suppose there are actually several caracters, but I have no idea how to analyze it further. Any ideas? Thanks A: Use a hex editor for viewing the raw character data. Your example includes three multibyte characters with special meanings. Here you go: ‍̸ U+0338 COMBINING LONG SOLIDUS OVERLAY General Character Properties In Unicode since: 1.1 Unicode category: Mark, Non-Spacing Various Useful Representations UTF-8: 0xCC 0xB8 UTF-16: 0x0338 C octal escaped UTF-8: \314\270 XML decimal entity: &#824; Annotations and Cross References Alias names: • long slash overlay ---------------------- ‍̨ U+0328 COMBINING OGONEK General Character Properties In Unicode since: 1.1 Unicode category: Mark, Non-Spacing Various Useful Representations UTF-8: 0xCC 0xA8 UTF-16: 0x0328 C octal escaped UTF-8: \314\250 XML decimal entity: &#808; Annotations and Cross References Alias names: • nasal hook Notes: • Americanist: nasalization • Polish, Lithuanian See also: • U+02DB OGONEK ---------------------- ı U+0131 LATIN SMALL LETTER DOTLESS I General Character Properties In Unicode since: 1.1 Unicode category: Letter, Lowercase Various Useful Representations UTF-8: 0xC4 0xB1 UTF-16: 0x0131 C octal escaped UTF-8: \304\261 XML decimal entity: &#305; Annotations and Cross References Notes: • Turkish, Azerbaijani • uppercase is U+0049 LATIN CAPITAL LETTER I See also: • U+0069 LATIN SMALL LETTER I I found this out using a hex editor and an program for displaying a character map. Probably you could have done it yourself. The first two are overlay characters and that’s why you have to hit backspace several times (they don’t generate a space in the text; they are modifying the previous character’s appearance). What the characters are doing in your text nobody here can tell you. You have to find it out yourself. (Maybe random binary data in a text file?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7599219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: listview item text allignment I have a list layout with 9patch .png used for each item - I have a small text allignment issue as in the attached pic. Any ideas how to solve it? Here is the first entry layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/list_up" > <TextView android:id="@+id/listUp_RecipeIngredientNameTextBoxId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14dip" /> </LinearLayout> Here is the 2nd entry layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/list_middle" > <TextView android:id="@+id/listMiddle_RecipeIngredientNameTextBoxId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14dip" /> </LinearLayout> A: Assuming list_middle and list_up are 9patch drawables, the difference should be in the "padding" specified in the 9patch images. You can solve this making both 9patch have the same amount of pixels in the borders (ie the width of the "left" part of the 9patch and the height of the "top" part of the 9patch).
{ "language": "en", "url": "https://stackoverflow.com/questions/7599220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }