text
stringlengths
8
267k
meta
dict
Q: Wrap element with specific code using jQuery I'm trying to wrap div with specific html code but I'm having problem using jQuery's .before and .after because jQuery would automatically close div I added into .before. This is my html: <div class="navigation"> <a>first</a> <a>second</a> <a>third</a> </div> When I try using this code: $('.navigation').before('<div class="newNavigation"><a>Prev</a>'); $('.navigation').after('<a>Next</a></div>'); He will automatically close .newNavigation div, which is what I don't want to happen because I'm trying to close that div in .after code. Generated HTML looks like this: <div class="newNavigation"> <a>Prev</a> </div> <div class="navigation"> <a>first</a> <a>second</a> <a>third</a> </div> <a>Next</a> And I'm trying to get this: <div class="newNavigation"> <a>Prev</a> <div class="navigation"> <a>first</a> <a>second</a> <a>third</a> </div> <a>Next</a> </div> To help you little bit with this I created jsFiddle where I unsuccessfully tried using .before and .after. Thank you in advance! Solution: Although there was few good solutions I decided to go with @Andy-E suggestion because his code looks cleanest to me. $(".navigation") .wrap('<div class="newNavigation">') .before("<a>Prev</a>") .after("<a>Next</a>"); Thank you all for participating! A: Use wrap() instead. var wrapper = $('<div />').addClass('newNavigation'); $('.navigation').wrap(wrapper); $('.newNavigation').prepend('<a>Prev</a>').append('<a>Next</a>'); A: jQuery has a built-in wrap() function, use it: $(".navigation") .wrap('<div class="newNavigation">') .before("<a>Prev</a>") .after("<a>Next</a>"); Demo: Your fiddle, updated. This sample highlights how neatly jQuery methods can be chained together. Here, all three methods return the original $(".navigation") jQuery object, so there's no need to use temporary variables or break your code up. A: You could try just using .html() like this: // Get the original html from the navigation div: var navigationHtml = $('.navigation').html(); // Replace the contents of navigation with the original html surrounded by the extra elements $('.navigation').html('<div class="newNavigation"><a>Prev</a>' + navigationHtml + '<a>Next</a></div>'); A: $(".navigatioin").wrap('<div class="newNavigation"></div>'); $(".newNavigation").prepend('<a>Prev</a>').append('<a>Next</a>'); should works for you,
{ "language": "en", "url": "https://stackoverflow.com/questions/7556957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight StringFormat : remove format on focus (for edition) I have a textbox twoway bound : <TextBox Text="{Binding Path=Cost, StringFormat=\{0:N\}, Mode=TwoWay}" /> When I put an amount (like 1000.1), and then change the focus, the number is formatted like I want (i.e. 1,000.10). But when I focus on the textbox again, the text is still formatted. I'd like to be able to edit the original numeric input, not the formatted one (lose the commas in fact) How can I achieve that ? Edit : if the solution is applicable for all the textboxes, that would be better than to edit the code behind for every one of them. A: The easiest way to accomplish control enhancements like this is with a behavior. Just code up a behavior for a textbox and then give it two properties: One for the focused string format and one for the non-focused string format. Then hook into the GotFocus and LostFocus events and apply the formats to the Text property. Let me know if you need some code samples to get you started.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WebDeploy not taking changed files, only new files I'm using WebDeploy to push physical files to a target location when doing a publish from the SiteCore CMS. I'm having some problems though, * *WebDeploy only pushes newly created files, but not any files that have changed *It's using the admin agent service which requires an AD admin account to run. Is there a way to make it use the IIS agent instead? (I think that this may be related to SiteCore itself) *If it isnt possible to get it working with the IIS agent, then is it possible to make it use a local account instead of requiring an AD admin account? A: Not precisely on-topic, but have had mixe results with Web Deployment. I switched to using the Publication method, along with SlowCheetah XML Transforms (which allows you to do build transforms on any XML file for your build configuraton) and it works really well. Plus it runs under the authority of the developer running VS (or the account running the build script). Plus it has features for "replace whole directory" or "update as needed". ...just sayin... A: My experience is that you must use the admin agent service for Web Deploy in Sitecore. I have spent many hours trying to work around this, but it seems impossible. This does indeed require a local admin account to be used (which sucks..) This issue has been discussed with Sitecore on several occasions and i hope they will come up with a better solution in future releases. When properly set up, Web Deploy will also push updated files. There is a command line utility that comes with web deploy which you can use to test the installation. Try to get everything to work using that utility and then try it again in Sitecore. Make sure you test using the admin service. Can you also confirm that the date/time settings on both servers are the same?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Fully featured REST server with Ruby? Is possible to create a fully-featured REST server with Ruby (not Rails)? A: Yes, use sinatra. http://www.sinatrarb.com/ A: Yes, see Grape for a good example. A: Yes. You'll need to implement all the rest stuff yourself and there's no good reason to do all the hard work when it's already done for you. If you think Rails is too heavy for what you're doing then maybe Sinatra would be better for you. A: Yes, there are no limitations. REST is a language-agnostic architectural style. The language you choose to implement your interface doesn't affect the final result. Of course, instead of starting from scratch, you might want to use an existing Ruby framework like Sinatra. But if you want the full control of your request at a very low level, Rack itself is a good choice. A: of course, but i'd recommend considering using another web framework, e.g. Sinatra if you don't want to bloat your app with a full featured Rails stack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I cancel an edit in the Silverlight DataGrid when a validation error has occurred? I have DataGrid and during a cell edit, a validation error occurs (my binding throws an exception and the error is correctly displayed to the user). The user then chooses to just click somewhere (either to navigate to a different portion of my application or to end the edit) and I want to cancel the edit. However, when there is an active validation error, the data grid refuses to end the edit - this means I cannot manipulate the grid items in any way until the user either enters a valid value or presses the Escape key. What can I do to programmatically end the edit or is there not way to do it other than to either try and programmatically send the Escape key or programmatically orchestrate value entry to reset the value? A: For your instance of the data grid call cancel edit: dataGrid.CancelEdit()
{ "language": "en", "url": "https://stackoverflow.com/questions/7556967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: how to load injection lib in mac applications at application start? I have a dynamic library, I intent to inject in running application & newly launched applications. I can inject it in running applications with the help of a process running with root user permissions. Now I am trying that library should get loaded as soon as application is launched. I know one such library capable of doing this called, application enhancer. I am looking for similar behavior. Does anyone has an Idea how can this be achieved? A: Look at SIMBL agent code. It adds a observer to application launch notification and then injects. You can follow the same approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where have the Eclipse online javadocs gone? For as long as I've been working on Eclipse plug-ins when I have wanted to read some documentation I have always just googled it. This worked fine up until about a week ago when I started being met with this message: | Topic not found The topic that you have requested is not available. The link may be wrong, or you may not have the corresponding product feature installed. This online help only includes documentation for features that are installed. Today this has tripped me up on the following queries: http://www.google.co.uk/search?&q=ITreeContentProvider http://www.google.co.uk/search?&q=IObjectActionDelegate Sometimes trying different versions of the Eclipse docs works, sometimes it doesn't. I had assumed this was just a glitch but I'm still noticing this issue, where have the docs gone? A: Two suggestions without using Google: * *Use the Eclipse documentation directly! *Use Bkekko with my Eclipse slashtag: https://blekko.com/ws/ITreeContentProvider+/timkrueger/eclipse A: This issue is now resolved. I contacted the Eclipse web admin but didn't hear back so whether Eclipse fixed the issue or Google figured it out, i'm not sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to authenticate users through a WCF service that is connected to a database I'm getting increasingly frustrated with doing the authentication right. Usually I'm using terms that I'm not familiar with so answerers misunderstand my questions. Its not helped bu the fact that this is a case with many implementations. So now I'm going to try to explain the facts and requirements surrounding my project so that I might get a pointer towards a good solution. I will have a Database that includes the information I need. Included in this info will be the usernames and salted hash of passwords. This database will be connected to a WCF web service that supplies the data to other front end projects. One of the front end projects is a asp.net MVC 3 web site that users will use to log in and such. Now the default in such a project is some sort of SQlMembership that is not right in this case as this site is not connected to the database (it might not even be a MSQL database). Here are implementations that I looked at but couldn't quite figure how to use correctly. 1) Write my own MembershipProvider in the MVC project that would query the WebService for validation. Here I mean that it would just call some methods for all its needs. Not liking it for security issues, client side solution. 2) Validata using a service side MembershipProvider but then I would have to send userName Password with each action and I can't store password for security reasons. 3) Then I discovered something called WCF authenticationService http://msdn.microsoft.com/en-us/library/system.web.applicationservices.authenticationservice.aspx and it seemed to be what I need but I'm having problem understanding how it works. I wan't it to be part of my service but it seems to be a dedicated service. Also its not really explaining how it authenticates (I need to have a custom authentication based on my table, not some default table created for me). Here is a post Should authentication be in a separate service for wcf? with same problem that I'm not sure how got solved. Can the WCF authentication service be the right tool for me? Can you answer this for someone who doesn't know asp.net, web or service terminology? EDIT Here is one solution that I was hoping for but not sure if exists. The WCF Service exposes a MembershipProvider, RoleProvider, ProfileProvider that are defined in the service. In the MVC web.config under membership\providers\add the MembershipProvider is added along with a endpoint towards the service. Same with RoleManager etc. So when I call MembershipProvider in the MVC project to validate user it automatically calls the service and checks there and when it happens upon a Authorize attribute it as well checks the RoleProvider in the service automatically. I would however also want to restrict the service calls themselves, even if they are inside a [Authorized] attribute method it might not be so in other clients that reference the web service. Would love if when a call comes from a website the service would automatically have access to the forms.authentication cookie. A: I am not clear as to what you want to authenticate exactly, if the user login in, or the user accessing you service. Also, I am not sure how you mean for an answer about WCF Security not to use service terminology nor how you expect to solve this without knowing asp.net. I'll do my best though. * *If you are authenticating a user login in, you can implement your own MembershipProvider and have a service request credentials and return the authenticated user. *Once authenticated, you can assign each user a GUID. This GUID is the ID which will travel with each message (encoded in the message header) and validate the user to call the service method. *This doesn't involve transport security, which you should configure if you want your message to be secure over the wire, yet this is a different matter, not involving authentication. Hope this can somehow help you. I tried to make it the least technical possible and left out anything too complicated. Hope this helps somehow...
{ "language": "en", "url": "https://stackoverflow.com/questions/7556976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Regex - Finding two consecutive words with unknown number of spaces (" ") between them I am trying to create a PHP REGEX that will match if two words appear next to each other with ANY number of spaces between them. For example, match "Daniel   Baylis" (3 spaces between 'Daniel' and 'Baylis'). I tried with this but it doesn't seem to work: "/DANIEL[ ]{1,5}BAYLIS/" (this was to check up to 5 spaces which the most I expect in the data) and "/DANIEL[ ]{*}BAYLIS/" I need to extract names from within larger bodies of text and names can appear anywhere within that text. User input error is what creates the multiple spaces. Thanks all! - Dan A: /DANIEL[ ]+BAYLIS/ should do... + will glob one or more occurence of the previous character(-class), in this case, litteral space. Also, assuming you want to match regardless of the case, you'll need to adjust your regex to be case-insensitive, which I'm not sure how to do in PHP (it depends on which flavor of regex you use... Long time since I last touched that...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7556980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Container in MS VISIO If someone knows how to place one figure inside another in Visio VDX (xml) format, please provide explanation (or link) and xml code sample. Thank you. A: I found something that helps but not too much: http://blogs.msdn.com/b/visio/archive/2010/01/12/custom-containers-lists-and-callouts-in-visio-2010.aspx In short by reading User.msvStructureType element from shape element, we can at least find out which shapes are containers and which are not. But there is no hierarchy info as far I can see...
{ "language": "en", "url": "https://stackoverflow.com/questions/7556981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: High-precedence application expressions as arguments A high precedence application expression is one in which an identifier is immediately following by a left paren without intervening whitespace, e.g., f(g). Parentheses are required when passing these as function arguments: func (f(g)). Section 15.2 of the spec states the grammar and precedence rules allow the unparenthesized form -- func f(g) -- but an additional check prevents this. Why is this intentionally prohibited? It would obviate the need for excessive parentheses and piping, and generally make the code much cleaner. A common example is raise <| IndexOutOfRangeException() or raise (IndexOutOfRangeException()) could become simply raise IndexOutOfRangeException() A: I agree that the need for writing the additional parentheses is a bit annoying. I think that the main reason why it is not allowed to omit them is that adding a whitespace would then change the meaning of your code in quite a significant way: // Call 'foo' with the result of 'bar()' as an argument foo bar() // Call 'foo' with 'bar' as the first argument and '()' as the second foo bar () There are still some rough edges where adding parens changes the evaluation (see this form post), but that "just" changes the evaluation order. This would change the meaning of your code!
{ "language": "en", "url": "https://stackoverflow.com/questions/7556982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Sharepoint Activating a feature error: The resource object with key 'xxxxx' was not found After succesfully installing the SharePoint Administration Toolkit and activating the PermissionReporting.wsp, the following reports error out: Broken Inheritance Reports Jobs - "The resource object with key 'StatusPageTitle' was not found..." Check Effective Permissions - "The resource object with key 'AccountPageTitle' was not found..." Compare Permissions Sets - "The resource object with key 'TreeViewReportPageTitle' was not found..." I am relatively new to sharePoint and am not really sure what direction to go. There has not been too much information on the errors related to this toolkit so any help would be appreciated. Thanks A: Here is the solution that resolved my issue: Use cmd: stsadm -o copyappbincontent, if copy command does not work copy the .resx file(s) from the resources folder to the Global resources folder, ie. Source C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\CONFIG\Resources\test.resx Destination C:\Inetpub\wwwroot\wss\VirtualDirectories\\App_GlobalResources\test.resx After files are copied, restart IIS
{ "language": "en", "url": "https://stackoverflow.com/questions/7556983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Auto-Launch JNLP on click How do I get a JNLP file to auto-launch on click? (as opposed to clicking save or open when clicked) Is this some type of MIME association that the browser must first recognize? A: I think the other answer is outdated as of today. Try changing your link from http:// or https:// to jnlp:// or jnlps://. So your url would look something like this: jnlp://your.server/path/yourjnlp.jnlp Caveat: For me, typing this in the Chrome URL doesn't work. It needs to actually be a link inside the page that gets clicked. There may also be a Windows requirement but I haven't confirmed that. See this for more info: https://bugs.chromium.org/p/chromium/issues/detail?id=518170 A: There is a server configuration file that specifies MIME or content type by file extension. For JNLP, it should be application/x-java-jnlp-file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Using cURL to get Facebook Album jSON with PHP I found a script in Web Designer magazine that enables you to gather Album Data from a Facebook Fan Page, and put it on your site. The script utilizes PHP's file_get_contents() function, which works great on my personal server, but is not allowed on the Network Solutions hosting. In looking through their documentation, they recommended that you use a cURL session to gather the data. I have never used cURL sessions before, and so this is something of a mystery to me. Any help would be appreciated. The code I "was" using looked like this: <?php $FBid = '239319006081415'; $FBpage = file_get_contents('https://graph.facebook.com/'.$FBid.'/albums'); $photoData = json_decode($FBpage); $albumID = $photoData->data[0]->id; $albumURL = "https://graph.facebook.com/".$albumID."/photos"; $rawAlbumData = file_get_contents("https://graph.facebook.com/".$albumID."/photos"); $photoData2 = json_decode($rawAlbumData); $a = 0; foreach($photoData2->data as $data) { $photoArray[$a]["source"] = $data->source; $photoArray[$a]["width"] = $data->width; $photoArray[$a]["height"] = $data->height; $a++; } ?> The code that I am attempting to use now looks like this: <?php $FBid = '239319006081415'; $FBUrl = "https://graph.facebook.com/".$FBid."/albums"; $ch = curl_init($FBUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $contents = curl_exec($ch); curl_close($ch); $photoData = json_decode($contents); ?> When I try to echo or manipulate the contents of $photoData however, it's clear that it is empty. Any thoughts? A: Try removing curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); I'm not exactly sure what that does but I'm not using it and my code otherwise looks very similar. I'd also use: json_decode($contents,true); This should put the results in an array instead of an object. I've had better luck with this approach. Put it in the works for me category. A: Try this it could work $ch = curl_init($FBUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $contents = curl_exec($ch); $pageData = json_decode($contents); //object to array $objtoarr = get_object_vars($pageData); curl_close($ch); A: Use jquery get Json instead This tips is from FB Album downloader GreaseMonkey script
{ "language": "en", "url": "https://stackoverflow.com/questions/7556987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: While loop Repeats infinitely I have a while loop that populates a dropdown box with values from a mysql table. There are only two matching records and it is repeating them over and over. How do i only display each record once?: $query = "SELECT * FROM members, sportevents, dates, results, event, userlogin ". "INNER JOIN members AS m ON userlogin.id = m.id " . "WHERE userlogin.username = '$un' " . "AND sportevents.id = members.id " . "AND sportevents.event_id = event.id " . "AND sportevents.date_id = dates.id " . "AND sportevents.result_id = results.id"; echo "<form method='POST' action='display.php'>"; echo "Please Select Your Event<br />"; echo "<select name='event'>"; echo "<option>Select Your Event</option>"; $results = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($results)) { echo "<option>"; echo $row['eventname']; echo "</option>"; } echo "</select>"; echo "<input type='submit' value='Go'>"; echo "</form>"; A: Have you tried running that query manually in the mysql monitor? Nothing in your code would produce an infinite loop, so most likely your query is not doing joins as you expect and is doing a cross-product type thing and creating "duplicate" records. In particular, your query looks very suspect - you're using the lazy "from multiple tables" approach, instead of explicitly specifying join types, and you're using the members table twice (FROM members ... and INNER JOIN members). You don't specify a relationship between the original members table and the joined/aliased m one, so most likely you're doing a members * members cross-product fetch. give that you seem to be fetching only an event name for your dropdown list, you can try eliminating the unused tables - ditch dates and results. This will simplify things considerable, then (guessing) you can reduce the query to: SELECT event.id, event.eventname FROM event INNER JOIN sportevents ON event.id = sportevents.event_id INNER JOIN members ON sportevents.id = members.id INNER JOIN userlogins ON members.id = userlogins.id WHERE userlogins.username = '$un' I don't know if the members/userlogins join is necessary - it seems to just feed sportevents.id through to members, but without knowing your DB's schema, I've tried to recreate your original query as best as possible. A: You could always try changing the SELECT statement to a SELECT DISTINCT statement. That'll prevent duplicates of the selected fields. Either that or reading all the results before displaying them, then de-duping them with something like array_unique(). A: Checkout My Example. It will be helped for you to understand. Because this code 100% working for me. Study it and get a solution. And You Should Use DISTINCT keyword and GROUP BY Keyword. That's the Main Thing to prevent repeating values. <?php $gtid = $_GET['idvc']; if(isset($_GET['idvc'])) { $sql = mysql_query("SELECT DISTINCT gallery_types.gt_id, gallery_types_category.gtc_id, gallery_types_category.gt_category, gallery_types_category.gtc_image FROM gallery_types, gallery_types_category WHERE $_GET[idvc]=gtid GROUP BY gt_category"); mysql_select_db($database,$con); while($row = mysql_fetch_array($sql)) {?> <table> <tr> <td width="100px"><?php echo $row['gt_id'] ?></td> <td width="100px"><?php echo $row['gtc_id'] ?></td> <td width="300px"><?php echo $row['gt_category'] ?></td> <td width="150px"> <a href='view_all_images.php?idvai=<?php echo $row[gtc_id] ?>' target='_blank'> <img width='50' height='50' src='<?php echo $row[gtc_image] ?>' /> </a> </td> </tr> </table> <?php } } ?> Better Understand, Follow Following Method, $sql = mysql_query("SELECT DISTINCT table1.t1id, table2.t2id, table2.t2name FROM table1, table2 WHERE t1id=t2id GROUP BY t2name");
{ "language": "en", "url": "https://stackoverflow.com/questions/7556998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIWebView display problem I followed this tutorial http://bytedissident.theconspiracy5.com/2010/11/24/uiwebview-tutorial/ and when I run the simulation in Xcode, all that is displayed is a blank white screen. I'm wondering what could be wrong. Is there some sort of code connection to the internet that i'm missing? I really don't know what could be wrong. WebPageViewController.m #import "WebPageViewController.h" @implementation WebPageViewController @synthesize wView; // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; //a URL string NSString *urlAddress = @"http://www.nd.edu"; //create URL object from string NSURL *url = [NSURL URLWithString:urlAddress]; //URL Request Object created from your URL object NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView [wView loadRequest:requestObj]; //scale page to the device - can also be done in IB if preferred. //wView.scalesPageToFit = YES; } A: Did you connect the .xib to the WebPageViewController class you created? You can check by selecting the .xib in the editor, and use identity inspector on 'File's Owner' in the Class field under Custom Class
{ "language": "en", "url": "https://stackoverflow.com/questions/7557002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change format of existing date I am trying to format a date to look like this 2011-09-19 If I do the following : leaveDate = "09/19/11" FormatTime, fileDate, leaveDate, yyyy-MM-dd MsgBox, %fileDate% It will just pick up the current date and time because my input date format is invalid. How can I take this 09/19/11 and turn it into this 2011-09-19? I have read the docs, and I can't find a function to do this. Am I just overlooking it? A: Your date needs to be supplied in YYYYMMDDHH24MISS format. If your date format is consistent and all years are after 2000 then the following code using SubStr() to split up the date should work: leaveDate := "09/19/11" year := "20" . SubStr(leaveDate, 8, 2) month := SubStr(leaveDate, 2, 2) date := SubStr(leaveDate, 5, 2) formattedTime := year . month . date FormatTime, fileDate, %formattedTime%, yyyy-MM-dd MsgBox, %fileDate% At the bottom of the documentation page for FormatTime a link is given to a forum topic giving the code for a function titled DateParse. This function will take a date in pretty much any format and return a YYYYMMDDHH24MISS formatted string that can be used instead of SubStr() generated string. The example given is: DateParse("2:35 PM, 27 November 2007")
{ "language": "en", "url": "https://stackoverflow.com/questions/7557006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Approximate string matching using backtracking I would like to use backtracking to search for all substrings in a long string allowing for variable length matches - that is matches allowing for a maximum given number of mismatches, insertions, and deletions. I have not been able to locate any useful examples. The closest I have found is this paper here, but that is terribly complex. Anyone? Cheers, Martin A: Algorithm The function ff() below uses recursion (i.e. backtracking) to solve your problem. The basic idea is that at the start of any call to f(), we are trying to match a suffix t of the original "needle" string to a suffix s of the "haystack" string, while allowing only a certain number of each type of edit operation. // ss is the start of the haystack, used only for reporting the match endpoints. void f(char* ss, char* s, char* t, int mm, int ins, int del) { while (*s && *s == *t) ++s, ++t; // OK to always match longest segment if (!*t) printf("%d\n", s - ss); // Matched; print endpoint of match if (mm && *s && *t) f(ss, s + 1, t + 1, mm - 1, ins, del); if (ins && *s) f(ss, s + 1, t, mm, ins - 1, del); if (del && *t) f(ss, s, t + 1, mm, ins, del - 1); } // Find all occurrences of t starting at any position in s, with at most // mm mismatches, ins insertions and del deletions. void ff(char* s, char* t, int mm, int ins, int del) { for (char* ss = s; *s; ++s) { // printf("Starting from offset %d...\n", s - ss); f(ss, s, t, mm, ins, del); } } Example call: ff("xxabcydef", "abcdefg", 1, 1, 1); This outputs: 9 9 because there are two ways to find "abcdefg" in "xxabcydef" with at most 1 of each kind of change, and both of these ways end at position 9: Haystack: xxabcydef- Needle: abc-defg which has 1 insertion (of y) and 1 deletion (of g), and Haystack: xxabcyde-f Needle: abc-defg which has 1 insertion (of y), 1 deletion (of f), and 1 substitution of g to f. Dominance Relation It may not be obvious why it's actually safe to use the while loop on line 3 to greedily match as many characters as possible at the start of the two strings. In fact this may reduce the number of times that a particular end position will be reported as a match, but it will never cause an end position to be forgotten completely -- and since we're usually interested in just whether or not there is a match ending at a given position of the haystack, and without this while loop the algorithm would always take time exponential in the needle size, this seems a win-win. It is guaranteed to work because of a dominance relation. To see this, suppose the opposite -- that it is in fact unsafe (i.e. misses some matches). Then there would be some match in which an initial segment of equal characters from both strings are not aligned to each other, for example: Haystack: abbbbc Needle: a-b-bc However, any such match can be transformed into another match having the same number of operations of each type, and ending at the same position, by shunting the leftmost character following a gap to the left of the gap: Haystack: abbbbc Needle: ab--bc If you do this repeatedly until it's no longer possible to shunt characters without requiring a substitution, you will get a match in which the largest initial segment of equal characters from both strings are aligned to each other: Haystack: abbbbc Needle: abb--c My algorithm will find all such matches, so it follows that no match position will be overlooked by it. Exponential Time Like any backtracking program, this function will exhibit exponential slowdowns on certain inputs. Of course, it may be that on the inputs you happen to use, this doesn't occur, and it works out faster than particular implementations of DP algorithms. A: I would start with Levenshtein's distance algorithm, which is the standard approach when checking for string similarities via mismatch, insertion and deletion. Since the algorithm uses bottom up dynamic programming, you'll probably be able to find all substrings without having to execute the algorithm for each potential substring. A: The nicest algorithm I'm aware of for this is A Fast Bit-Vector Algorithm for Approximate String Matching Based on Dynamic Programming by Gene Myers. Given a text to search of length n, a pattern string to search for of length m and a maximum number of mismatches/insertions/deletions k, this algorithm takes time O(mn/w), where w is your computer's word size (32 or 64). If you know much about algorithms on strings, it's actually pretty incredible that an algorithm exists that takes time independent of k -- for a long time, this seemed an impossible goal. I'm not aware of an existing implementation of the above algorithm. If you want a tool, agrep may be just what you need. It uses an earlier algorithm that takes time O(mnk/w), but it's fast enough for low k -- miles ahead of a backtracking search in the worst case. agrep is based on the Shift-Or (or "Bitap") algorithm, which is a very clever dynamic programming algorithm that manages to represent its state as bits in an integer and get binary addition to do most of the work of updating the state, which is what speeds up the algorithm by a factor of 32 or 64 over a more typical implementation. :) Myers's algorithm also uses this idea to get its 1/w speed factor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript on submit button I have some question. I have the html form with one hidden input element. And I have an array in my javascript code. I want to catch pressing submit button event (by using jquery) and push the array data in the hidden input. The question is - what happens first: form date will flow to .php script or javascript's array will be pushed into hidden input and afterwords .php script will be called? And why it is so? TIA! upd (code sample): ... // process $_POST['domains'] ... <form action="registration?id=reg" method="post" enctype="multipart/form-data" id="reg_form"> ... <input type="hidden" id="domains" name="domains[]" value=""/> ... <input type="submit" name="go" value="Register"/> </form> <script type="text/javascript"> var domainlist = []; Array.prototype.indexOf = function (name) { var ind = -1; for (var i = 0; i < this.length; i++) { if (this[i].name == name) { ind = i; break; } } return ind; } $(document).ready(function() { ... }); function checkDomain() { ... req = $.ajax({ type: 'post', cache: false, url: 'ajax.php', data: ..., success: function(data) { $('#domain_list_wrap').delegate('input:checkbox', 'click', function () { var dmnName = $(this).attr('name'); domainlist.push({name: dmnName, cost: domainsArr[dmnName.split('.')[1]]}); ... }); $('#domain_cart').delegate('input:checkbox', 'click', function () { domainlist.splice(domainlist.indexOf($(this).attr('name')), 1); ... }); } }); ... } </script> A: The JavaScript submit event is fired when the form is submitted, but before the request is made to the server (as JavaScript runs on the client side this makes perfect sense). Therefore, the way you have imagined it working should be fine, and you can bind to the form submit event using jQuery as follows: $("#yourForm").submit(function() { //Submit event handler will run on form submit }); The submit event handler can also be used to cancel form submission (for example, if some validation fails) by returning false. It wouldn't really work if the data was sent to the server first! A: Put this in your body <form id="frm" method="post" action="/"> <input type="hidden" id="txtHidden" /> <input type="submit" id="btnSubmit" value="submit" /> </form> And this in your head: <script type="text/javascript"> var arr = [ "hello", "there", "world" ]; $(document).ready( function() { $("#btnSubmit").click( function(event) { var str = arr.join(","); $("#txtHidden").val(str); // make sure the value is in the field alert($("#txtHidden").val()); }); }); </script> When you click on btnSubmit, the array will be joined with commas, you'll see the alert, then the form will be submitted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Having trouble with javascript Replace() This code will replace the comma's no problem, but will leave the $ for some reason... Is it set up wrong? Trying to replace the $ also. function doValidate() { var valid = true; document.likeItemSearchForm.sup.value = document.likeItemSearchForm.sup.value.replace(/\$|,/g, "") return valid; } A: Try this: 'asd$asd,asd,asd$,asd'.replace(/[\$,]/g,''); JSFIDDLE -edit- fixed link A: try this: "$12,121.30".replace(/[\$,]/g, "");
{ "language": "en", "url": "https://stackoverflow.com/questions/7557025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read a std::wstring written in linux into windows We have a program which runs on Windows and Linux. It writes out std::wstrings in binary to a file. We need to be able to read in files written from linux into windows. We write out strings as a list of wchar_t. On linux each wchar_t occupies 4 bytes. On Windows each wchar_t occupies 2 bytes. When reading the file written by linux into Windows how can one take the four byte wchar_t and put it into the 2 byte wchar_t? Thanks, Adam A: Assuming the Linux code is writing out in UTF-32 format, you'll have to write some code to convert the string to UTF-16 which is the Unicode encoding used on Windows. wstring can't help you with this. Once you have converted to UTF-16, you can store in a wstring on Windows using wchar_t. A: You can use UTF8-CPP to easily convert the file from UTF-32 to UTF-16: #include <fstream> #include <iterator> #include <utf8.h> int main(int argc, char** argv) { std::ifstream file("source.txt"); std::string intermediate; std::wstring result; utf8::utf32to8(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), std::back_inserter(intermediate)); utf8::utf8to16(intermediate.begin(), intermediate.end(), std::back_inserter(result)); } Unfortunately there is no utf8::utf32to16, though perhaps there should be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Comparing Objects in Objective-C I am trying to compare objects in Objective-C and was just wandering how, for example, two objects (which are instances of UIView) are compared that hold two NSStrings like so: #import <Foundation/Foundation.h> @interface Notebook : UIView { NSString *nameOfBook; NSString *colourOfBook; } @property (nonatomic, retain) NSString *nameOfBook; @property (nonatomic, retain) NSString *colourOfBook; Let's assume that I have two NSMutableArrays which hold several objects of the type Notebook. One is called reality and the other theory. Reality holds two notebooks with the nameOfBook @"Lectures" and @"Recipies", but colourOfBook are all empty. Theory holds three notebooks with the nameOfBook @"Lectures", @"Recipies", @"Zoo", and colourOfBook @"red", @"yellow", @"green". I would like to compare the two arrays and adjust theory according to reality. In this case, it would mean to remove @"Zoo". I can't simply replace theory with reality as I would loose all the colours stored in theory. This is the code I've come up with: for (int i=0; i < [theory count]; i++) { Notebook *testedNotebook = [Notebook alloc]; testedNotebook = [theory objectAtIndex:i]; if ([reality indexOfObject:testedNotebook] == NSNotFound) { NSLog(@"Book is not found in reality - remove it from theory..."); [theory removeObject:testedNotebook]; } [testedNotebook release]; } Now, my big question is how the objects will be compared. Ideally, I'd like to compare ONLY their NAMES regardless of the COLOUR. But I guess this is not how my code works right now. The entire objects are compared and the object in reality which holds @"Lectures" and @"" (no colour) cannot be the same as the object in theory which holds @"Lectures" and @"red". How could I achieve to compare objects according to one of their attributes only (in this case the name)? A: If you read the documentation for indexOfObject:, you'd find that NSArray calls isEqual: for each object in the array. So, override isEqual for Notebook and implement your own comparison routine. Apropos of nothing, why are you allocating without initializing an instance of Notebook, overwriting it with an autoreleased instance, and subsequently releasing that? (Never mind you might be releasing it in your loop first!) You're destined for a crash. And why are you removing objects from an array while you're iterating through it? A: You want to implement methods like -isEqual:. Please have a look here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Whats the difference between Exception's .ToString() and .Message? I'm looking through some code and I found e.ToString() and I was wondering if there is a difference to using the ToString() method instead of .Message ? Reading below, it sounds like it returns more info. From Microsoft's Docs ToString Supported by the .NET Compact Framework. Overridden. Creates and returns a string representation of the current exception. Message Supported by the .NET Compact Framework. Gets a message that describes the current exception. A: ToString() returns the Message along with the StackTrace. ToString() will also recursively include InnerExceptions. ToString() returns a much longer string which is much more useful than Message when tracking down errors. A: You could always just try it and see: try { throw new Exception("This is a test."); } catch ( Exception ex ) { Console.WriteLine(ex); Console.WriteLine(ex.Message); } (You will find that you are correct, .ToString is more informative, including among other things the stack trace. A: If you're looking to get as much information as possible in one go, call ToString(): The default implementation of ToString obtains the name of the class that threw the current exception, the message (my emphasis), the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is Nothing, its value is not included in the returned string. It's convenient that you don't have to append all the individual elements together yourself, checking to make sure none are null, etc. It's all built in... Exception.ToString Method You can also check out the actual source code at reference.microsoft.com. A: Try using .NET Reflector or similar to see what the ToString method on System.Exception is doing: [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public override string ToString() { return this.ToString(true); } private string ToString(bool needFileLineInfo) { string className; string message = this.Message; if ((message == null) || (message.Length <= 0)) { className = this.GetClassName(); } else { className = this.GetClassName() + ": " + message; } if (this._innerException != null) { className = className + " ---> " + this._innerException.ToString(needFileLineInfo) + Environment.NewLine + " " + Environment.GetRuntimeResourceString("Exception_EndOfInnerExceptionStack"); } string stackTrace = this.GetStackTrace(needFileLineInfo); if (stackTrace != null) { className = className + Environment.NewLine + stackTrace; } return className; } A: The ToString methods returns the Message property along with information on where the error occured. The Message property is intended for a short description of the error, and only contains what the person implementing the Exception put there. The resport from ToString contains additional information that is always included. If you are running in debug mode, the error report contains more detailed information, e.g. line numbers in the call stack. A: The e.ToString() will give you a detailed Message like PrintTrace i think which Display's the Exception Name and the Line where Exception was Thrown where e.Message Output's a Readable Message Only without Specification's. You can check Exception base constructor
{ "language": "en", "url": "https://stackoverflow.com/questions/7557031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Can Xcode Use "Folder References" for Code? Like many people, I would love to have Xcode use a folder structure that mirrors the folder-structure on disk. However, I cannot get the code in "folder references" (the cyan folders) to show up in my project targets under "Compile Sources." Is there any way to do this? I have managed to even add a cyan folder to the "Compile Sources" build phase, but that does not result in the contents of that folder being added. How can I use folder references for code? A: Kevin - linked source folders, folder references, etc, are super useful for when you have a common code base shared across different IDEs, like I do for my games that I compile on Windows, Mac, iOS, Android, Linux, etc. I have 3 different IDEs all building the same shared codebase, so it's very helpful when one automatically picks up on a new file and adds it right into the project after I merely run svn update, and I svn commit from one IDE (say XCode) and my Eclipse in Windows project picks up the change. I have a different project for each because each IDE likes the project files in a certain configuration so it's easier for me to have multiple SVN directories (base-project, project-ios, project-android) that all share code in base-project than to have one mega project directory with the different IDE bits unhappily all shoved into subdirectories (which is what I tried the first time around). Furthermore - it used to work fine in XCode 3. They seemed to not like that useful of a feature so it is no longer working in XCode 4 as I've just found out. A: I just tried doing this to share code across multiple Xcode projects, and our team came to the conclusion that it's better to create an Xcode project that contains all of your shared classes, compiles them into a static/dynamic library, and then add that as a subproject to those that need the shared code. Then you can set up target dependencies and link your shared library. This will get you the "automatic updating" every time you add a new class to the shared library project. This approach also works well with submodules or even cocoapods/carthage. A: The simple (and very unfortunate) answer is that Folder References under Xcode remain broken and buggy, they don't work. Tested 04-Mar-2017 in Xcode 8.2.1 Below is an example exploration so you do not have to waste your time replicating the Xcode failure. (incidentally buggy Xcode crashed twice while I was producing this example) Per the question, the overall desire is to use a folder reference in Xcode so Xcode picks up all the files in the folder and includes them in the project, and by proxy will update automatically based upon any Finder or Xcode changes of the folder. In this way 50 projects all leveraging the same set of common source code files do not have to be individually updated when those folders get changed. Below explores how this is broken in Xcode (tested in 8.2.1) The example: ViewController.m includes NSError+Core.h so we want everything from the folder "NSError+Core" to be added to the project. NSError+Core.h is in this centrally located development folder Drag the source folder from the Finder into the Project under the "Support" group (nothing up my sleeves, simple drag) Xcode dutifully offers to add the drag to the target, note the "Create folder references" is selected, not "Create group references". Note also it is clear that Xcode is offering and is told to add this folder and files to the targets. Although everything looks like it should work, the compiler does not pick up the header file and a recompile yields the same results... can't find header. Ditching the DerivedData does not help either. So doing a double check, we check the "Compile Sources" under the project and sure enough, the source file is not there either. Remember, Xcode 'added' it to the target... So what if we drag it from the folder into the "Support" group... It offers to add them to the project again?! Note that the settings are identical to the first time they were drug in by virtue of the parent folder drag instead of files... And now the source file shows up in the "Compile Sources" list. Note the bizarre double listing of the files in the project. (Xcode crashed shortly after snapping this screen shot) And of course the compiler can now find the header file and the error clears on the import as it should have the first time we drug it in... Did it just need a little help to "find" the file? If so, the "Create folder references" does exactly what? So we try and tidy up and drag the files back from the parent "Supporting Files" group to their rightful folder. Without any confirmation, indication, notification, the files just vanish from the group and nothing happens in the NSError+Core folder. Oh by the way, it really did delete them from the project too... The Compile Sources no longer has the NSError+Core.m reference. SO to sum up, "Folder references" as implemented thus far do not seem to have any useful purpose... It would appear to be a 6+ year old dunsel on the USS Xcode. A: You can't. Why are you even trying? A folder reference's job is to embody a folder, without having entries for all the individual files in the folder. It's primary use is for copying an entire folder of resources verbatim into a project. If you want to compile the sources though, then those sources must be referenced in the Compile Sources build phase of the target, which requires having individual entries for each file. Depending on what's in the folder, it might make more sense to have a Makefile or some other external build process that builds the content in the folder into a static library. This way you can invoke that build process from a Shell Script Phase, and then just link in the resulting static library. Alternatively if you're using this folder as a way to have a shared bit of code (e.g. an svn:externals or git submodule), you could give that folder its own Xcode project and then embed that project into any of your other projects which share this folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Access file in App_Data I have stored a file HelloWorld.txt in App_Data. My application is running locally but not on Server. File Path is D:\MyProject\App_Data\HelloWorld.txt How can I access? Is this is the way? var file= File.ReadAllText(@"D:\MyProject\App_Data\HelloWorld.txt"); (File is on my disk but not on server) or is there any other way? I cannot use server.Mappath(); because my file is not on server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CodeIgniter: Language file editor? I am looking to find a good way to create an http editor to manage CI language files ... ( for a custom made CMS ) I found following project but its a bit old and buggy : http://www.mrkirkland.com/codeigniter-language-file-translator/ also it doesnt support of adding new language file and language key... /// I am thinking of a new way for making it much easier to manage CI languages with mixing mysql and CI language files ... there will be two tables ( lang / translations ) in the mysql table and a controller for http gui... each time the editor finished her/his translation job her/she will click on Finish button and it will output CI language files in different languages ( but each language in a same file ) with this way We are using native CI Language system (which is fast) and managing/searching/editing of translations are much easier than directly editing CI Language files ... also its much secure ... example : TABLE : langs = lang_id ---- lang_name 1---- English 2 --- German TABLE : translations= key --- lang_id --- translation hello --- 1 --- hello hello --- 2 ---hallo and the output will be these files /application/language/english/global_lang.php $lang['hello'] = 'hello'; /application/language/german/global_lang.php $lang['hello'] = 'hallo'; what is your opinion ? does it worth to do this ? A: I found this: http://blog.codebusters.pl/en/entry/codeigniter-frontend-language-files-editor Hope this helps :) A: For php language file editing I'm using this Firefox addon: https://addons.mozilla.org/en-US/firefox/addon/phplangeditor/ It's easy to find untranslated strings...
{ "language": "en", "url": "https://stackoverflow.com/questions/7557051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: reading log files in Python and outputing specific text I have a piece of code that reads the last line of a log file as the log is being written to. I want to print errors which occur in the logs, basically start printing when line.startswith('Error') and finish printing when line.startwith('End of Error'). My code is below, Could anybody help me with this please? log = 'C:\mylog.log' file = open(log, 'r') res = os.stat(log) size = res[6] file.seek(size) while 1: where = file.tell() line = file.readline() if not line: time.sleep(1) file.seek(where) else: if line.startswith('Error'): #print lines until you come to 'End of Error' A: Initialize a flag before the loop: in_error = False Then switch it on and off as needed: if line.startswith('Error'): in_error = True elif line.startswith('End of Error'): print(line) in_error = False if in_error: print(line) A: It may be easier to use the subprocess module to simply run tail -F (capital F, available on GNU platforms) and process the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to expand hash into argument list in function call in Perl? How to expand hash into argument list in function call in Perl? I am searching Perl equivalent of Python's syntax : somefunc(**somedict) or somefunc(*somelist). Is that possible in Perl? A: In Perl, all function arguments are passed as lists and stored in the special array variable @_. You can copy those values to some other array, or directly into a hash (as you can with any array/list). If you are writing a function, you can pass the arguments directly into an array or hash: sub hashFunc { my %args = @_; .... } sub arrayFunc { my @args = @_; ... } To call a function like that, just pass them as if they were a list or hash: hashFunc(arg1 => 'someVal', arg2 => 'someOtherVal'); arrayFunc('someVal', 'someOtherVal'); If you already have the arguments in a variable, just pass them along and Perl flattens out the array/hash into the argument list: hashFunc(%someHash); arrayFunc(@someArray); A: Hashes do expand into a list when calling a function: my %h = (a => 1, b => 2, c => 3); sub foo { # prints the key-value pairs in unsorted order print "@_\n"; } foo %h;
{ "language": "en", "url": "https://stackoverflow.com/questions/7557061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3 and jQuery Datepicker i need advice about my problem, i use jquery ui DatePicker, this work really good in my rails problem, but in the form i use with this jquery, i have a white row appear at the end of the page. When i select the field with Datepicker and choose a date, the white row disappears. my jquery are like this jQuery(function() { $(".showcal").datepicker({showOn:'both'}); } my form have a text_field <%= f.text_fields :first_date, :class => showcal %> I use jQuery min 1.6.2 My Layout head <head> <title><%= content_for?(:title) ? yield(:title) : "Cadifice" %></title> <%= stylesheet_link_tag "application" %> <%= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css", "application" %> <%= stylesheet_link_tag "jquery.fancybox-1.3.4", "application" %> <%= stylesheet_link_tag "jquery.highlight-3", "application" %> <%= stylesheet_link_tag 'bottom' %> <%= javascript_include_tag :defaults %> <%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.min.js", "application" %> <%= javascript_include_tag 'pikachoose', 'jquery.pikachoose.full' %> <%= javascript_include_tag 'cadifice', 'jquery.cadifice' %> <%= csrf_meta_tag %> <%= yield(:head) %> </head> thanks A: I also encounter that problem every now and then. For some reason (bug?) the datepicker panel sometimes does not get hidden. A simple workaround is add one more line to hide it yourself after initialising the datepickers. For exmaple, $(".showcal").datepicker({showOn:'both'}); $('#ui-datepicker-div').hide(); A: If you are loading Prototype per my comments on your question, take a look at my answer here to another question involving RoR and jQuery. It resolved that person's issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery dialog always centered How can I implement, that a jQuery modal dialog with auto width & height is always centered in the browser. Also after resizing the window of the browser. The following code doesn't work. I think the problem is the auto width & height. jQuery - code $("<div class='popupDialog'>Loading...</div>").dialog({ autoOpen: true, closeOnEscape: true, height: 'auto', modal: true, title: 'About Ricky', width: 'auto' }).bind('dialogclose', function() { jdialog.dialog('destroy'); }).load(url, function() { $(this).dialog("option", "position", ['center', 'center'] ); }); $(window).resize(function() { $(".ui-dialog-content").dialog("option", "position", ['center', 'center']); }); Thank you! A: Acutally, I think the position: ["center", "center"] not be the best solution, as it assigns an explict top: and left: css properties to the dialog based on the size of the viewport at creation. I came across this same issue when trying to have a dialog center on screen vertically. Here is my solution: In the options part of my .dialog() function, I pass position:[null, 32]. The null sets the left: value the element's style, and the 32 is just for keeping the dialog box pegged to the top of the window. Also be sure to set an explicit width. I also use the dialogClass option to assign a custom class, which is simply a margin:0 auto; css property: .myClass{ margin:0 auto; } And my dialog looks like: $('div#popup').dialog({ autoOpen: false, height: 710, modal: true, position: [null, 32], dialogClass: "myClass", resizable: false, show: 'fade', width: 1080 }); Hopefully this helps someone. A: $(window).resize(function() { $("#dialog").dialog("option", "position", "center"); }); Working jsFiddle: http://jsfiddle.net/vNB8M/ The dialog is centered with auto width & height and continues to be centered after window resize. A: None of the answers did quite what I wanted. For those that are still having problems with this, here is what worked for me. This will force the dialog to always appear in the center of the screen, and it will center the dialog as the browser is resized. $( "#ShowDialogButton" ).click(function(){ $( "#MyDialog" ).dialog({ show: 'fade' }).dialog( "option", "position", { my: "center", at: "center", of: window } ); $(window).resize(function() { $( "#MyDialog" ).dialog( "option", "position", { my: "center", at: "center", of: window } ); }); }); A: The modal window around the dialog box should allow you to place the dialog box centered with the css of: margin-left:auto;margin-right:auto; Does this not work? Do you have a 'sample' page that we can look at? A: This solution is working: $(window).resize(function () { $("#myDialog").dialog("close"); $("#myDialog").dialog("open"); }); Performance is quite bad, but you can wait for resize end: jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?. I also tried this, but I can't scroll lower or higher than position of element which opened dialog: $(window).scroll(function () { $("#myDialog").dialog("close"); $("#myDialog").dialog("open"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7557068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Not able to load Microsoft.Http dll in ASP.NET MVC3 application at runtime I created a WCF service and exposed it as REST service. I am trying to consume this service from ASP.Net MVC3 application. I added a reference to Microsoft.Http dll, to use HttpClient and get the response from a POST method of REST service, as in the code below - string uri = http://localhost:12958/Host1/RestService.svc/SubmitAdvisor; using (HttpResponseMessage response = new HttpClient().Post(uri, HttpContentExtensions.CreateDataContract(obj))) { }; I get the follwing error at runtime - Could not load file or assembly 'Microsoft.Http, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. What is it I am missing? A: Download from this link http://aspnet.codeplex.com/releases/view/24644 After, Microsoft.Http.dll's location is like this C:\Program Files (x86)\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies
{ "language": "en", "url": "https://stackoverflow.com/questions/7557077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to access my lan based postgresql db from my website We have lan based .Net application with Postgresql 8.1 , now i have task to provide interface on website to read and write two tables on LAN based database I don't know where to start Please help me to solve this problem. Lan: Windows NT 2003 .Net Postgresql 8.1 Website: PHP 5.3 Mysql A: You need to enable remote connections on Postgres. But be wary of security implications. Haven't read it all, but this should give you an idea on the steps to take on the server. For the connector, you generally just need to point the connect function at the remote IP. A: Here is how to do the trick. Copied from here: <?php // Connecting, selecting database $dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo") or die('Could not connect: ' . pg_last_error()); // Performing SQL query $query = 'SELECT * FROM authors'; $result = pg_query($query) or die('Query failed: ' . pg_last_error()); // Printing results in HTML echo "<table>\n"; while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) { echo "\t<tr>\n"; foreach ($line as $col_value) { echo "\t\t<td>$col_value</td>\n"; } echo "\t</tr>\n"; } echo "</table>\n"; // Free resultset pg_free_result($result); // Closing connection pg_close($dbconn); ?> in the above code, replace localhost by the IP-address of your Postgres host. A: On Linux, two files need to be modified to allow connections other than from localhost: postgresql.conf, change the listen_addresses = "*" to accept connections from anywhere. Then add a line to the pg_hba.conf file to allow access to the database from a particular IP or network. If you are not worried about security, entering: host all all 192.168.1.0/24 trust will allow anyone on the 192.168.1.0/24 network access to any database. Obviously this should only be used to test you can reach the database. Constrain this to the web servers IP address and use md5 so encrypted password authentication is used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure web.xml for multiple login in a Struts2 web application? I would like to develop a small test multi-login application using Struts2 and JSP. Basically: * *The application should have welcome page (i.e. index.jsp) anyone can access. *This welcome page would have two login boxes: one for users and one for administrators. *The web application should have two sub-applications, one for users, one for administrator. In other words, it is not a single application where logged-in users would have different privileges. Each sub-application would have their own secluded set of pages. Struts2 uses the MVC pattern and I am wondering how I should use the filter pattern to organize this. I could have all requests under /userapp/* go to the user application and all requests under /adminapp/* go to the admin application. My questions are: * *Is this the right strategy (i.e. best practice)? If yes, how should I implement this in my web.xml? *Should I implement two filters and two mappings (if yes why?) or should I implement one filter and two mappings? UPDATE After doing a lot of reading, I get to understand that Struts2 multi-login is an over-engineered and too heavy solution for what I need. I have decided to implement my own Servlet 3.0 and use JQuery + Ajax. A: Consider a case where there are 2 different users 'Admin'(Highest Privileges) and 'Customer(Less Privileges compared to Admin)'. In Struts,you can implement like this 1.Make a Business Logic like User class which basically does the following tasks a.)Gets the username,password as input. b.)Checks whether this 'username' exists in database. c.)If exits, gets the type of user(either Admin or Customer) and checking its corresponding password. 2.Use this 'User' object from within 'Action' class.So,you pass the 'ActionForm' values(username,password) into this business method,validate the user and get a specific usertype(Storing in session). 3.On subsequent requests made by this 'User',check the usertype and forward accordingly.Create a custom 'Action' class which always validates the usertype(and other validations) on each action received from a usertype. All your other 'Action' class should extend this custom 'Action' class. This is how i implemented in one of the my Struts web-application where more than 3 types of users with different rights.I never seen a separate url pattern for each user type.So it is better to show, http://www.yoursite.com/Process.action instead of http://www.yoursite.com/adminapp/Process.action
{ "language": "en", "url": "https://stackoverflow.com/questions/7557083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Suggest a text editor or IDE for chapel programming language I want to write some short numerical programs in chapel. Can somebody just tell an IDE, or text editor which supports code highlighting for chapel (chapel-aware), is there an elisp-file for emacs? I don't prefer vim, even if a script for vim exists. I tried searching, but I couldn't find anything. I neither know emacs-lisp nor am completely aware of chapel's syntax to configure it to make this chapel-aware. A: the elisp files and .vimrc files ship along with chapel tar.gz file , so after extracting the tar.gz file in a folder chapel-version/highlight/vim or chapel-version/highlight/emacs there the vimrc or elisp files are present and in the README , instructions are also given how to add to init files ~/.emacs or ~/.vim. A: I have just come across a plugin for the Atom Editor that does Chapel Highlighting A: There is an Emacs mode for Chapel at MELPA. So if you are using an Emacs with package management you can just install chapel-mode. https://melpa.org/#/chapel-mode
{ "language": "en", "url": "https://stackoverflow.com/questions/7557091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to loop chained calls elegantly in JavaScript/CoffeeScript? I'm using Soda to write Selenium tests in Node.js and I have a situation where I have to press the down key several times. The code currently looks like this: browser .chain .setSpeed(200) .session() .open('/') .click("id=save") .focus(editor) .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') .keyDown(editor, '\\40') ... How could I DRY this up? Just using a loop like this does not work with this lib: var b = browser.chain() for (var i = 0; i < 10; i++) { b.keyDown(editor, '\\40') } Awesome ideas? I could use the async API in Soda and for example async-lib to help me out, but that's not what I'm asking here. It makes some other things ugly. A: Did you try replacing the b variable in your loop? var b = browser.chain() for (var i = 0; i < 10; i++) { b = b.keyDown(editor, '\\40') } A: There is a method called and for doing complicated things in the middle of a command chain: browser .chain .setSpeed(200) .session() .open('/') .click("id=save") .focus(editor) .and(function (browser) { for (var i = 0; i < 10; i++) { browser.keyDown(editor, '\\40') } }) ... See the README for more information: https://github.com/learnboost/soda A: You're close. You just have to change b in the loop so it chains correctly. var b = browser.chain() for (var i = 0; i < 10; i++) { b = b.keyDown(editor, '\\40') }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: matplotlib interactive mode: determine if figure window is still displayed I am using matplotlib in interactive mode to show the user a plot that will help them enter a range of variables. They have the option of hitting "?" to show this plot, and the prompt for variables will then be repeated. How do I know to not re-draw this plot if it's still being displayed? Superficially, I have this clunky (pseudo-ish) code: answer = None done_plot = False while answer == None: answer = get_answer() if answer == '?': if done_plot: have_closed = True ##user's already requested a plot - has s/he closed it? ## some check here needed: have_closed = ????? if have_closed == False: print 'You already have the plot on display, will not re-draw' answer = None continue plt.ion() fig = plt.figure() ### plotting stuff done_plot = True answer = None else: ###have an answer from the user... what can I use (in terms of plt.gca(), fig etc...) to determine if I need to re-plot? Is there a status somewhere I can check? Many thanks, David A: In the same vein as unutbu's answer, you can also check whether a given figure is still opened with import matplotlib.pyplot as plt if plt.fignum_exists(<figure number>): # Figure is still opened else: # Figure is closed The figure number of a figure is in fig.number. PS: Note that the "number" in figure(num=…) can actually be a string: it is displayed in the window title. However, the figure still has a number attribute which is numeric: the original string num value cannot be used with fignum_exists(). PPS: That said, subplots(…, num=<string num>) properly recovers the existing figure with the given string number. Thus, figures are still known by their string number in some parts of Matplotlib (but fignum_exists() doesn't use such strings). A: import matplotlib.pyplot as plt if plt.get_fignums(): # window(s) open else: # no windows
{ "language": "en", "url": "https://stackoverflow.com/questions/7557098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: how to create database in blackberry os 5.0 using javascript I need to create the database in blackberry os 5.0 using javascript for phonegap application. var mydb=false; function onLoad() { try { if (!window.openDatabase) { alert('not supported'); } else { var shortName = 'phonegap'; var version = '0.9.4'; var displayName = 'PhoneGap Test Database'; var maxSize = 65536; // in bytes mydb = openDatabase(shortName, version, displayName, maxSize); } } } It is moving to if condition and only the alert is displayed.But the database is not getting created.Please tell me what's wrong in this code. Thanks in advance! A: You have your answer, no? If it's moving to the if and only the alert is being displayed, it's never going to go to the else and create the database, but there's a good reason for that. The if tests for support. Apparently, BlackBerry OS 5.0 doesn't support databases. You can check this page for a list of polyfills to support HTML5 features in less capable browsers. A: BlackBerry 5 is not supported by PhoneGap's openDatabase API. http://docs.phonegap.com/phonegap_storage_storage.md.html Supported Platforms * *Android *BlackBerry WebWorks (OS 6.0 and higher) *iPhone A: HI Recently I had the same problem and I found a cool solution :D BB5 have a "Google Gear" Iternaly in the browser to do that if (window.openDatabase){ //HTML5 }else{ //try google GEARS if (window.google || google.gears){ _DB = google.gears.factory.create('beta.database', '1.0'); _DB.open('MyLocalDB'); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Possible hacking attempt. How to tell if my db has been compromised I have the following in my log file with seconds apart. I'm assuming something was trying to find my database or an admin page or something, but i'm not sure. Should I be worried about this and how can I tell if my db has been compromised? ERROR - 2011-09-23 20:51:42 --> 404 Page Not Found --> muieblackcat ERROR - 2011-09-23 20:51:46 --> 404 Page Not Found --> PMA ERROR - 2011-09-23 20:51:46 --> 404 Page Not Found --> admin ERROR - 2011-09-23 20:51:47 --> 404 Page Not Found --> dbadmin ERROR - 2011-09-23 20:51:48 --> 404 Page Not Found --> mysql ERROR - 2011-09-23 20:51:48 --> 404 Page Not Found --> myadmin ERROR - 2011-09-23 20:51:48 --> 404 Page Not Found --> phpmyadmin2 ERROR - 2011-09-23 20:51:49 --> 404 Page Not Found --> phpMyAdmin2 ERROR - 2011-09-23 20:51:49 --> 404 Page Not Found --> phpMyAdmin-2 ERROR - 2011-09-23 20:51:50 --> 404 Page Not Found --> php-my-admin ERROR - 2011-09-23 20:51:50 --> 404 Page Not Found --> phpMyAdmin-2.2.3 ERROR - 2011-09-23 20:51:51 --> 404 Page Not Found --> phpMyAdmin-2.2.6 ERROR - 2011-09-23 20:51:52 --> 404 Page Not Found --> phpMyAdmin-2.5.1 ERROR - 2011-09-23 20:51:52 --> 404 Page Not Found --> phpMyAdmin-2.5.4 ERROR - 2011-09-23 20:51:53 --> 404 Page Not Found --> phpMyAdmin-2.5.5-rc1 ERROR - 2011-09-23 20:51:53 --> 404 Page Not Found --> phpMyAdmin-2.5.5-rc2 ERROR - 2011-09-23 20:51:54 --> 404 Page Not Found --> phpMyAdmin-2.5.5 ERROR - 2011-09-23 20:51:54 --> 404 Page Not Found --> phpMyAdmin-2.5.5-pl1 ERROR - 2011-09-23 20:51:55 --> 404 Page Not Found --> phpMyAdmin-2.5.6-rc1 ERROR - 2011-09-23 20:51:58 --> 404 Page Not Found --> phpMyAdmin-2.5.6 ERROR - 2011-09-23 20:51:59 --> 404 Page Not Found --> phpMyAdmin-2.5.7 ERROR - 2011-09-23 20:51:59 --> 404 Page Not Found --> phpMyAdmin-2.5.7-pl1 ERROR - 2011-09-23 20:52:00 --> 404 Page Not Found --> phpMyAdmin-2.6.0-alpha ERROR - 2011-09-23 20:52:00 --> 404 Page Not Found --> phpMyAdmin-2.6.0-alpha2 ERROR - 2011-09-23 20:52:04 --> 404 Page Not Found --> phpMyAdmin-2.6.0-beta2 ERROR - 2011-09-23 20:52:04 --> 404 Page Not Found --> phpMyAdmin-2.6.0-rc1 ERROR - 2011-09-23 20:52:05 --> 404 Page Not Found --> phpMyAdmin-2.6.0-rc2 ERROR - 2011-09-23 20:52:05 --> 404 Page Not Found --> phpMyAdmin-2.6.0-rc3 ERROR - 2011-09-23 20:52:09 --> 404 Page Not Found --> phpMyAdmin-2.6.0-pl1 ERROR - 2011-09-23 20:52:09 --> 404 Page Not Found --> phpMyAdmin-2.6.0-pl2 ERROR - 2011-09-23 20:52:10 --> 404 Page Not Found --> phpMyAdmin-2.6.0-pl3 ERROR - 2011-09-23 20:52:10 --> 404 Page Not Found --> phpMyAdmin-2.6.1-rc1 ERROR - 2011-09-23 20:52:11 --> 404 Page Not Found --> phpMyAdmin-2.6.1-rc2 ERROR - 2011-09-23 20:52:11 --> 404 Page Not Found --> phpMyAdmin-2.6.1 ERROR - 2011-09-23 20:52:15 --> 404 Page Not Found --> phpMyAdmin-2.6.1-pl2 ERROR - 2011-09-23 20:52:15 --> 404 Page Not Found --> phpMyAdmin-2.6.1-pl3 ERROR - 2011-09-23 20:52:16 --> 404 Page Not Found --> phpMyAdmin-2.6.2-rc1 ERROR - 2011-09-23 20:52:16 --> 404 Page Not Found --> phpMyAdmin-2.6.2-beta1 ERROR - 2011-09-23 20:52:17 --> 404 Page Not Found --> phpMyAdmin-2.6.2-rc1 ERROR - 2011-09-23 20:52:17 --> 404 Page Not Found --> phpMyAdmin-2.6.2 ERROR - 2011-09-23 20:52:18 --> 404 Page Not Found --> phpMyAdmin-2.6.2-pl1 ERROR - 2011-09-23 20:52:18 --> 404 Page Not Found --> phpMyAdmin-2.6.3 ERROR - 2011-09-23 20:52:19 --> 404 Page Not Found --> phpMyAdmin-2.6.3-rc1 ERROR - 2011-09-23 20:52:19 --> 404 Page Not Found --> phpMyAdmin-2.6.3 ERROR - 2011-09-23 20:52:20 --> 404 Page Not Found --> phpMyAdmin-2.6.3-pl1 ERROR - 2011-09-23 20:52:20 --> 404 Page Not Found --> phpMyAdmin-2.6.4-rc1 ERROR - 2011-09-23 20:52:21 --> 404 Page Not Found --> phpMyAdmin-2.6.4-pl1 ERROR - 2011-09-23 20:52:21 --> 404 Page Not Found --> phpMyAdmin-2.6.4-pl2 ERROR - 2011-09-23 20:52:22 --> 404 Page Not Found --> phpMyAdmin-2.6.4-pl3 ERROR - 2011-09-23 20:52:22 --> 404 Page Not Found --> phpMyAdmin-2.6.4-pl4 ERROR - 2011-09-23 20:52:23 --> 404 Page Not Found --> phpMyAdmin-2.6.4 ERROR - 2011-09-23 20:52:23 --> 404 Page Not Found --> phpMyAdmin-2.7.0-beta1 ERROR - 2011-09-23 20:52:24 --> 404 Page Not Found --> phpMyAdmin-2.7.0-rc1 ERROR - 2011-09-23 20:52:24 --> 404 Page Not Found --> phpMyAdmin-2.7.0-pl1 ERROR - 2011-09-23 20:52:25 --> 404 Page Not Found --> phpMyAdmin-2.7.0-pl2 ERROR - 2011-09-23 20:52:25 --> 404 Page Not Found --> phpMyAdmin-2.7.0 ERROR - 2011-09-23 20:52:26 --> 404 Page Not Found --> phpMyAdmin-2.8.0-beta1 ERROR - 2011-09-23 20:52:26 --> 404 Page Not Found --> phpMyAdmin-2.8.0-rc1 ERROR - 2011-09-23 20:52:27 --> 404 Page Not Found --> phpMyAdmin-2.8.0-rc2 ERROR - 2011-09-23 20:52:27 --> 404 Page Not Found --> phpMyAdmin-2.8.0 ERROR - 2011-09-23 20:52:28 --> 404 Page Not Found --> phpMyAdmin-2.8.0.1 ERROR - 2011-09-23 20:52:34 --> 404 Page Not Found --> phpMyAdmin-2.8.0.4 ERROR - 2011-09-23 20:52:35 --> 404 Page Not Found --> phpMyAdmin-2.8.1-rc1 ERROR - 2011-09-23 20:52:35 --> 404 Page Not Found --> phpMyAdmin-2.8.1 ERROR - 2011-09-23 20:52:36 --> 404 Page Not Found --> phpMyAdmin-2.8.2 ERROR - 2011-09-23 20:52:36 --> 404 Page Not Found --> sqlmanager ERROR - 2011-09-23 20:52:38 --> 404 Page Not Found --> mysqlmanager ERROR - 2011-09-23 20:52:38 --> 404 Page Not Found --> p ERROR - 2011-09-23 20:52:39 --> 404 Page Not Found --> PMA2005 ERROR - 2011-09-23 20:52:39 --> 404 Page Not Found --> pma2005 ERROR - 2011-09-23 20:52:40 --> 404 Page Not Found --> phpmanager ERROR - 2011-09-23 20:52:40 --> 404 Page Not Found --> php-myadmin ERROR - 2011-09-23 20:52:41 --> 404 Page Not Found --> phpmy-admin ERROR - 2011-09-23 20:52:41 --> 404 Page Not Found --> webadmin ERROR - 2011-09-23 20:52:42 --> 404 Page Not Found --> sqlweb ERROR - 2011-09-23 20:52:42 --> 404 Page Not Found --> websql ERROR - 2011-09-23 20:52:42 --> 404 Page Not Found --> webdb ERROR - 2011-09-23 20:52:43 --> 404 Page Not Found --> mysqladmin ERROR - 2011-09-23 20:52:43 --> 404 Page Not Found --> mysql-admin ERROR - 2011-09-23 20:52:50 --> 404 Page Not Found --> dbadmin ERROR - 2011-09-23 20:52:50 --> 404 Page Not Found --> myadmin ERROR - 2011-09-23 20:52:54 --> 404 Page Not Found --> mysqladmin ERROR - 2011-09-23 20:52:54 --> 404 Page Not Found --> phpadmin ERROR - 2011-09-23 20:52:55 --> 404 Page Not Found --> phpMyAdmin ERROR - 2011-09-23 20:52:55 --> 404 Page Not Found --> phpmyadmin ERROR - 2011-09-23 20:52:56 --> 404 Page Not Found --> phpmyadmin1 ERROR - 2011-09-23 20:52:56 --> 404 Page Not Found --> phpmyadmin2 ERROR - 2011-09-23 20:52:57 --> 404 Page Not Found --> pma ERROR - 2011-09-23 20:52:57 --> 404 Page Not Found --> databaseadmin ERROR - 2011-09-23 20:52:58 --> 404 Page Not Found --> admm ERROR - 2011-09-23 20:52:58 --> 404 Page Not Found --> admn ERROR - 2011-09-23 20:52:59 --> 404 Page Not Found --> _myadmin ERROR - 2011-09-23 20:52:59 --> 404 Page Not Found --> phpMyA ERROR - 2011-09-23 20:53:03 --> 404 Page Not Found --> admin ERROR - 2011-09-23 20:53:04 --> 404 Page Not Found --> mysql2 ERROR - 2011-09-23 20:53:04 --> 404 Page Not Found --> phpmyadm ERROR - 2011-09-23 20:53:05 --> 404 Page Not Found --> php1 ERROR - 2011-09-23 20:53:05 --> 404 Page Not Found --> php2 ERROR - 2011-09-23 20:53:09 --> 404 Page Not Found --> sqladm ERROR - 2011-09-23 20:53:09 --> 404 Page Not Found --> myAdmin ERROR - 2011-09-23 20:53:10 --> 404 Page Not Found --> pmabd ERROR - 2011-09-23 20:53:10 --> 404 Page Not Found --> mydb ERROR - 2011-09-23 20:53:11 --> 404 Page Not Found --> mysql_administrator ERROR - 2011-09-23 20:53:11 --> 404 Page Not Found --> pma_mydb ERROR - 2011-09-23 20:53:12 --> 404 Page Not Found --> webmail2 ERROR - 2011-09-23 20:53:12 --> 404 Page Not Found --> myphp ERROR - 2011-09-23 20:53:16 --> 404 Page Not Found --> phpas ERROR - 2011-09-23 20:53:16 --> 404 Page Not Found --> _pma ERROR - 2011-09-23 20:53:17 --> 404 Page Not Found --> /scripts ERROR - 2011-09-23 20:53:20 --> 404 Page Not Found --> _dbadmin ERROR - 2011-09-23 20:53:24 --> 404 Page Not Found --> _admin ERROR - 2011-09-23 20:53:27 --> 404 Page Not Found --> _phpMyAdmin ERROR - 2011-09-23 20:53:34 --> 404 Page Not Found --> sql ERROR - 2011-09-23 20:53:34 --> 404 Page Not Found --> _sql ERROR - 2011-09-23 20:53:35 --> 404 Page Not Found --> my-php ERROR - 2011-09-23 20:53:35 --> 404 Page Not Found --> My-php A: Something (probably a bot) is scanning your web server for those pages, which do not exist since they are receiving 404 errors. The scanning is very common -- usually scripts are looking for vulnerabilities. We can't tell if your database has been compromised. Although the log contents you posted do not indicate that you have been compromised, just scanned. A: This is a common attempt at finding out if there is an administrative web interface installed at the site. It's normal for any web site to receive such attempts from time to time. If this is a traffic log, this particular attempt rendered no success at all as all requests resulted in a HTTP 404. If this is just a report of error messages, you should look at the traffic log to see if any request from that IP resulted in a non-404 response. Still, just because such an attemt would find a web interface it was looking for doesn't mean that it has been hacked. It only means that someone knows what web interface you are using, and could try to find a security weakness in it. Generally there is very little risk for that if the system is properly updated and patched.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MyBatis 3.0.5 and mappers loading problem I'm using MyBatis 3.0.5 and I have problems about the loading of mappers as resources. I'm on Windows 7 64, I use Eclipse Indigo 64bit and jdk7 64. MyBatis is initialized in a Grizzly Web Container (where are implemented rest services with jersey framework) standalone instance. <mappers> <mapper url="file:///C:/Users/andrea/workspace/soap2rest/src/main/java/com/izs/mybatis/FormMapper.xml" /> <mapper resource="src/main/java/com/izs/mybatis/FormMapper.xml" /> </mappers> I have the same mappers only for testing, the first is loaded, the second doesn't work. Errors: org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in src/main/java/com/izs/mybatis/FormMapper.xml ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource src/main/java/com/izs/mybatis/FormMapper.xml at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:8) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:32) at com.izs.Main.initMyBatis(Main.java:114) at com.izs.Main.main(Main.java:80) Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource src/main/java/com/izs/mybatis/FormMapper.xml at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:85) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:69) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:30) ... 2 more Caused by: java.io.IOException: Could not find resource src/main/java/com/izs/mybatis/FormMapper.xml at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:89) at org.apache.ibatis.io.Resources.getResourceAsStream(Resources.java:76) at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:253) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:83) ... 4 more Exception in thread "main" java.lang.NullPointerException at com.izs.Main.initMyBatis(Main.java:122) at com.izs.Main.main(Main.java:80) Sorry for my english. SOLUTION: Maven projects want resources into src/main/resources and src/test/resources for tests. So the solution is to put the xml mappers into these folders. A: Do not use absolute paths. It makes your code unportable and unused on another environment. Just relative acceptable. For your example, I guess you can use the following relative path: <mapper resource="com/izs/mybatis/FormMapper.xml" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7557111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: asp .net Application performance I have an asp .net 4.0 application. I have an mdf file in my app_data folder that i store some data. There is a "User" table with 15 fields and an "Answers" table with about 30 fields. In most of the scenarios in my website, the user retrieves some data from "User" table and writes some data to "Answers" table. I want to test the performance of my application when about 10000 users uses the system.What will happen if 10000 users login and use the system at the same time and how will the performance is affected ? What is the best practice to test my system performance of asp .net pages in general? Any help will be appreciated. Thanks in advanced. A: It reads like performance testing/engineering is not your core discipline. I would recommend hiring someone to either run this effort or assist you with it. Performance testing is a specialized development practice with specific requirement sets, tool expertise and analytical methods. It takes quite a while to become effective in the discipline even in the best case conditions. In short, you begin with your load profile. You progress to definitions of the business process in your load profile. You then select a tool that can exercise the interfaces appropriately. You will need to set a defined initial condition for your testing efforts. You will need to set specific, objective measures to determine system performance related to your requirements. Here's a document which can provide some insight as a benchmark on the level of effort often required, http://www.tpc.org/tpcc/spec/tpcc_current.pdf Something which disturbs me greatly is your use case of "at the same time," which is a practical impossibility for systems where the user agent is not synchronized to a clock tick. Users can be close, concurrent within a defined window, but true simultaneity is exceedingly rare.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help me optimize this query I have this query for an application that I am designing. There is a table of references, an authors table and a reference_authors table. There is a sub query to return all authors for a given reference which I then display formatted in php. The subquery and query run individually are both nice and speedy. However as soon as the subquery is put into the main query the whole thing takes over 120s to run. I would apprecaite some fresh eyes on this one. Thanks. SELECT rf.reference_id, rf.reference_type_id, rf.article_title, rf.publication, rf.annotation, rf.publication_year, (SELECT GROUP_CONCAT(a.author_name) FROM authors_final AS a INNER JOIN reference_authors AS ra2 ON ra2.author_id = a.author_id WHERE ra2.reference_id = rf.reference_id GROUP BY ra2.reference_id) AS authors FROM references_final AS rf INNER JOIN reference_authors AS ra ON rf.reference_id = ra.reference_id LEFT JOIN reference_institutes AS ri ON rf.reference_id = ri.reference_id; Here is the fixed query. Thanks guys for the recommendations. SELECT rf.reference_id, rf.reference_type_id, rf.article_title, rf.publication, rf.annotation, rf.publication_year, GROUP_CONCAT(a.author_name) AS authors FROM references_final as rf INNER JOIN (reference_authors AS ra INNER JOIN authors_final AS a ON ra.author_id = a.author_id) ON rf.reference_id = ra.reference_id LEFT JOIN reference_institutes AS ri ON rf.reference_id = ri.reference_id GROUP BY rf.reference_id A: You say the subquery is nice and speedy in isolation but its now obviously running for every single row - 100 rows = 100 sub queries. Assuming you have indexes on all your foreign keys that's as good as it gets as a sub query. One option is to left join authors and create a Cartesian product - you'll have a lot more rows returned and will need some code to get to the same end result but it will put less strain on the db and will run quicker. If you've got paging on and say are returning 10 rows, issung 10 individual calls to get the authors in isolation would also be be pretty quick. A: Although not every subquery can be rewritten as an inner join, I think yours can. From 120 seconds to 78 milliseconds is not a bad improvement--about three orders of magnitude. Take the rest of the day off. When you come back tomorrow, start looking for other subqueries in your source code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server: calculate field data from fields in same table but different set of data I was looking around and found no solution to this. I´d be glad if someone could help me out here: I have a table, e.g. that has among others, following columns: Vehicle_No, Stop1_depTime, Segment_TravelTime, Stop_arrTime, Stop_Sequence The data might look something like this: Vehicle_No Stop1_DepTime Segment_TravelTime Stop_Sequence Stop_arrTime 201 13000 60 1 201 13000 45 2 201 13000 120 3 201 13000 4 202 13300 240 1 202 13300 60 2 ... and I need to calculate the arrival time at each stop from the departure time at the first stop and the travel times in between for each vehicle. What I need in this case would look like this: Vehicle_No Stop1_DepTime Segment_TravelTime Stop_Sequence Stop_arrTime 201 13000 60 1 201 13000 45 2 13060 201 13000 120 3 13105 201 13000 4 13225 202 13300 240 1 202 13300 60 2 13540 ... I have tried to find a solution for some time but was not successful - Thanks for any help you can give me! Here is the query that still does not work - I am sure I did something wrong with getting the table from the database into this but dont know where. Sorry if this is a really simple error, I have just begun working with MSSQL. Also, I have implemented the solution provided below and it works. At this point I mainly want to understand what went wrong here to learn about it. If it takes too much time, please do not bother with my question for too long. Otherwise - thanks a lot :) ;WITH recCTE AS ( SELECT ZAEHL_2011.dbo.L32.Zaehl_Fahrt_Id, ZAEHL_2011.dbo.L32.PlanAbfahrtStart, ZAEHL_2011.dbo.L32.Fahrzeit, ZAEHL_2011.dbo.L32.Sequenz, ZAEHL_2011.dbo.L32.PlanAbfahrtStart AS Stop_arrTime FROM ZAEHL_2011.dbo.L32 WHERE ZAEHL_2011.dbo.L32.Sequenz = 1 UNION ALL SELECT t. ZAEHL_2011.dbo.L32.Zaehl_Fahrt_Id, t. ZAEHL_2011.dbo.L32.PlanAbfahrtStart, t. ZAEHL_2011.dbo.L32.Fahrzeit,t. ZAEHL_2011.dbo.L32.Sequenz, r.Stop_arrTime + r. ZAEHL_2011.dbo.L32.Fahrzeit AS Stop_arrTime FROM recCTE AS r JOIN ZAEHL_2011.dbo.L32 AS t ON t. ZAEHL_2011.dbo.L32.Zaehl_Fahrt_Id = r. ZAEHL_2011.dbo.L32.Zaehl_Fahrt_Id AND t. ZAEHL_2011.dbo.L32.Sequenz = r. ZAEHL_2011.dbo.L32.Sequenz + 1 ) SELECT ZAEHL_2011.dbo.L32.Zaehl_Fahrt_Id, ZAEHL_2011.dbo.L32.PlanAbfahrtStart, ZAEHL_2011.dbo.L32.Fahrzeit, ZAEHL_2011.dbo.L32.Sequenz, ZAEHL_2011.dbo.L32.PlanAbfahrtStart, CASE WHEN Stop_arrTime = ZAEHL_2011.dbo.L32.PlanAbfahrtStart THEN NULL ELSE Stop_arrTime END AS Stop_arrTime FROM recCTE ORDER BY ZAEHL_2011.dbo.L32.Zaehl_Fahrt_Id, ZAEHL_2011.dbo.L32.Sequenz A: A recursive CTE solution - assumes that each Vehicle_No appears in the table only once: DECLARE @t TABLE (Vehicle_No INT ,Stop1_DepTime INT ,Segment_TravelTime INT ,Stop_Sequence INT ,Stop_arrTime INT ) INSERT @t (Vehicle_No,Stop1_DepTime,Segment_TravelTime,Stop_Sequence) VALUES(201,13000,60,1), (201,13000,45,2), (201,13000,120,3), (201,13000,NULL,4), (202,13300,240,1), (202,13300,60,2) ;WITH recCTE AS ( SELECT Vehicle_No, Stop1_DepTime, Segment_TravelTime,Stop_Sequence, Stop1_DepTime AS Stop_arrTime FROM @t WHERE Stop_Sequence = 1 UNION ALL SELECT t.Vehicle_No, t.Stop1_DepTime, t.Segment_TravelTime,t.Stop_Sequence, r.Stop_arrTime + r.Segment_TravelTime AS Stop_arrTime FROM recCTE AS r JOIN @t AS t ON t.Vehicle_No = r.Vehicle_No AND t.Stop_Sequence = r.Stop_Sequence + 1 ) SELECT Vehicle_No, Stop1_DepTime, Segment_TravelTime,Stop_Sequence, Stop1_DepTime, CASE WHEN Stop_arrTime = Stop1_DepTime THEN NULL ELSE Stop_arrTime END AS Stop_arrTime FROM recCTE ORDER BY Vehicle_No, Stop_Sequence EDIT Corrected version of OP's query - note that it's not necessary to fully qualify the column names: ;WITH recCTE AS ( SELECT Zaehl_Fahrt_Id, PlanAbfahrtStart, Fahrzeit, L32.Sequenz, PlanAbfahrtStart AS Stop_arrTime FROM ZAEHL_2011.dbo.L32 WHERE Sequenz = 1 UNION ALL SELECT t.Zaehl_Fahrt_Id, t.PlanAbfahrtStart, t.Fahrzeit,t.Sequenz, r.Stop_arrTime + r.Fahrzeit AS Stop_arrTime FROM recCTE AS r JOIN ZAEHL_2011.dbo.L32 AS t ON t.Zaehl_Fahrt_Id = r.Zaehl_Fahrt_Id AND t.Sequenz = r.Sequenz + 1 ) SELECT Zaehl_Fahrt_Id, PlanAbfahrtStart, Fahrzeit, Sequenz, PlanAbfahrtStart, CASE WHEN Stop_arrTime = PlanAbfahrtStart THEN NULL ELSE Stop_arrTime END AS Stop_arrTime FROM recCTE ORDER BY Zaehl_Fahrt_Id, Sequenz A: I'm quite sure this works: SELECT a.Vehicle_No, a.Stop1_DepTime, a.Segment_TravelTime, a.Stop_Sequence, a.Stop1_DepTime + (SELECT SUM(b.Segment_TravelTime) FROM your_table b WHERE b.Vehicle_No = a.Vehicle_No AND b.Stop_Sequence < a.Stop_Sequence) FROM your_table a ORDER BY a.Vehicle_No
{ "language": "en", "url": "https://stackoverflow.com/questions/7557119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do any of Apple's devices support iOS 4.0 but not multitasking? Do any of Apple's devices support iOS 4.0 but not multitasking? If not, I don't understand the [UIDevice isMultitaskingSupported] API (which was only introduced in iOS 4.0). Thanks A: Yes. * *Iphone 3G *Ipod Touch 2 Due to hardware limitations, they can run iOS4 but not actually make use of things like multitasking. On my old iPod touch, running iOS4 added a significant delay to the device's operation, even without multitasking. A: iPhone 3G doesn't support multitasking A: iPod touch 2g and iPhone 3g don't support native mustitasking. Multitasking can be disactivated on jailbroken devices, this is aswell recognizable using isMultitaskingSupported.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using One-to-Many associations with H2, JPA annotations and Hibernate Problem We're using a combination of H2, JPA annotations, Spring and Hibernate to develop our webapp. We're using H2 in compatiability mode with MODE=Oracle. We have an ItSystem class that has an one-to-many association with an ItSystemAka class as follows: @Entity @Table(name="ITSYSTEM") public class ItSystem implements Serializable { private static final long serialVersionUID = 1L; private static final String SEQ_NAME = "SeqName"; private static final String SEQUENCE = "sequence"; @Id @GeneratedValue(generator = SEQ_NAME) @GenericGenerator(name = SEQ_NAME,strategy = SEQUENCE, parameters = { @Parameter(name = SEQUENCE, value = "IT_SYSTEM_SEQ") }) @Column(name="ITSYSTEM_EDW_ID") private BigDecimal itSystemEdwId; @Column(name="ITSYSTEM_VERSION_ID") private BigDecimal itSystemVersionId; @OneToMany(fetch = FetchType.EAGER, cascade={CascadeType.ALL}) @JoinColumn(name="ITSYSTEM_EDW_ID") private Set<ItsystemAka> itSystemAkas; ..... } @Entity @Table(name="ITSYSTEM_AKA") public class ItSystemAka implements Serializable { private static final long serialVersionUID = 1L; private static final String SEQ_NAME = "SeqName"; private static final String SEQUENCE = "sequence"; @Id @GeneratedValue(generator = SEQ_NAME) @GenericGenerator(name = SEQ_NAME,strategy = SEQUENCE, parameters = { @Parameter(name = SEQUENCE, value = "IT_SYSTEM_AKA_SEQ") }) @Column(name="AKA_EDW_ID") private BigDecimal akaEdwId; private String aka; @Column(name="ITSYSTEM_EDW_ID") private BigDecimal itSystemEdwId; .... } We're using the following connection properties: myDataSource.driverClassName=org.h2.Driver myDataSource.url=jdbc:h2:~/test;MODE=Oracle;DB_CLOSE_DELAY=-1 myDataSource.username=sa myDataSource.password= sessionFactory.hibernateProperties[hibernate.dialect]=org.hibernate.dialect­.H2Dialect sessionFactory.hibernateProperties[hibernate.hbm2ddl.auto]=create sessionFactory.hibernateProperties[hibernate.show_sql]=false sessionFactory.hibernateProperties[hibernate.connection.autocommit]=false sessionFactory.hibernateProperties[hibernate.format_sql]=true If we have an instance of ItSystem with a number of ItSystemAka instances and we try and update the ItSystem instance to the database, then it is losing the reference to all the associated ItSystemAkas. Looking at the database with the H2 Console, I can see that the foregin key (IT_SYSTEM_EDW_ID) for the corresponding rows in the ITSYSTEM_AKA table are getting set to null. I've tried using the Oracle Dialect instead of the native H2 Dialect as advised on the H2 website, but it produces the same results. I've also tried using an actual Oracle database instead of H2, in which case everything seems to work fine. Any idea as to what is going wrong? Any help would be much appreciated. Regards, Priyesh A: Dialect does not matter in this case. You have unidirectional relation between tables if you use this mapping. The easy way to reorganize your mapping like this @Entity @Table(name="ITSYSTEM") public class ItSystem implements Serializable { .... @Id @GeneratedValue(generator = SEQ_NAME) @GenericGenerator(name = SEQ_NAME,strategy = SEQUENCE, parameters = { @Parameter(name = SEQUENCE, value = "IT_SYSTEM_SEQ") }) @Column(name="ITSYSTEM_EDW_ID") private BigDecimal itSystemEdwId; @OneToMany(fetch = FetchType.EAGER, mappedBy="itSystemEdwId", cascade={CascadeType.ALL}) private Set<ItsystemAka> itSystemAkas; ..... } @Entity @Table(name="ITSYSTEM_AKA") public class ItSystemAka implements Serializable { ... @Id @GeneratedValue(generator = SEQ_NAME) @GenericGenerator(name = SEQ_NAME,strategy = SEQUENCE, parameters = { @Parameter(name = SEQUENCE, value = "IT_SYSTEM_AKA_SEQ") }) @Column(name="AKA_EDW_ID") private BigDecimal akaEdwId; ... @Parent private ItSystem itSystemEdwId; .... } mappedBy always create bidirectional relation
{ "language": "en", "url": "https://stackoverflow.com/questions/7557124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SVN Change a file during branch Let's say I have script.py. When I'm branching this using svn copy I want to append a line to the top of the file. Is this possible to do? Or can it not be done? So svn copy -rHEAD file:///svn/repo/trunk/script.py file:///svn/repo/branches/script.py (Add line to the top of the branched file) svn commit -m "Branching script.py" Should be easy! A: You want to prepend when adding lines to the beginning of a file. From http://www.cyberciti.biz/faq/bash-prepend-text-lines-to-file/: echo "My New Line"|cat - yourfile > /tmp/out && mv /tmp/out yourfile A: The flavour of svn copy you have chosen will do the copy from one repository location to another repository location atomically. In that case your svn commit is not necessary. You have two choices: * *Branch, checkout (or switch) modify the script, checkin, OR *Modify script in your workingcopy and do svn copy . $DEST_URL. This will take the state of your working copy and create a new branch for you. More automation is not possible in a clean way, because modifying hook scripts on the repository/server side are considered evil by the Subversion developers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ExceptionHandler shared by multiple controllers Is it possible to declare ExceptionHandlers in a class and use them in more than one controller, because copy-pasting the exception handlers in every controller would be redundant. -Class declaring the exception handlers: @ExceptionHandler(IdentifiersNotMatchingException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) def @ResponseBody String handleIdentifiersNotMatchingException(IdentifiersNotMatchingException e) { logger.error("Identifiers Not Matching Error", e) return "Identifiers Not Matching Error: " + e.message } @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) def @ResponseBody String handleResourceNotFoundException(ResourceNotFoundException e) { logger.error("Resource Not Found Error", e) return "Resource Not Found Error: " + e.message } -ContactController @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(value = "contact/{publicId}", method = RequestMethod.DELETE) def @ResponseBody void deleteContact(@PathVariable("publicId") String publicId) throws ResourceNotFoundException, IdentifiersNotMatchingException {...} -LendingController @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) @RequestMapping(value = "lending/{publicId}", method = RequestMethod.PUT) def @ResponseBody void updateLending(@PathVariable("publicId") String publicId, InputStream is) throws ResourceNotFoundException {...} A: One way to do this is to have a base class that your controllers extend (could be abstract). The base class can then hold all of the "common" things, including exception handlers, as well as loading common model data, such as user data. A: You can declare a HandlerExceptionResolver as a bean which would be used on every controller. You would just check the type and handle it as you wish. A: Or you can create an interface for exception handling and inject that in your controller class. A: Or you can use a class with @ControllerAdvice annotation. @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(IdentifiersNotMatchingException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public String handleIdentifiersNotMatchingException(IdentifiersNotMatchingException e) { logger.error("Identifiers Not Matching Error", e) return "Identifiers Not Matching Error: " + e.message } @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) @ResponseBody public String handleResourceNotFoundException(ResourceNotFoundException e) { logger.error("Resource Not Found Error", e) return "Resource Not Found Error: " + e.message } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to convert integer to decimal point in PROLOG? How to convert integer to decimal point in PROLOG? Example, imagine I assign Integer = 10 How do I change integer's value to turn to 1.0 (1 decimal point) ? A: It's not an assignment but Integer is unified with 10 and can't be changed thereafter. You could write Integer2 is 1.0 * Integer or Integer2 is float(Integer) at least in some Prolog implementations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to put the ID of Google Analytics on my Android App? I have this ID for my GA account: "UA 25832113-1" ok, but... how I have to put it on my app? Which format? A -> "UA 25832113-1" B -> "UA-25832113-1" C -> "25832113-1" A: B is correct. (ie. 'UA-10876-1') Official docs: http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty A: B if you are using the "Google Analytics SDK for Android" you shuld use something like this: tracker = GoogleAnalyticsTracker.getInstance(); tracker.startNewSession("UA-25832113-1", this);
{ "language": "en", "url": "https://stackoverflow.com/questions/7557149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLite: Downsides of ANALYZE Does the ANALYZE command have any downsides (except a slighty larger db)? If not, why is not executed by default? A: There is another downside. The ANALYZE results may cause the query planner to ignore indexes that you really want to use. For example suppose you have a table with a boolean column "isSpecial". Most of the rows have isSpecial = 0 but there are a few with isSpecial = 1. When you do a query SELECT * FROM MyTable WHERE isSpecial = 1, in the absence of ANALYZE data the query planner will assume the index on isSpecial is good and will use it. In this case it will happen to be right. If you were to do isSpecial = 0 then it would still use the index, which would be inefficient, so don't do that. After you have run ANALYZE, the query planner will know that isSpecial has only two values, so the selectivity of the index is bad. So it won't use it, even in the isSpecial = 1 case above. For it to know that the isSpecial values are very unevenly distributed it would need data that it only gathers when compiled with the SQLITE_ENABLE_STAT4 option. That option is not enabled by default and it has a big downside of its own: it makes the query plan for a prepared statement depend on its bound values, so sqlite will re-prepare the statement much more often. (Possibly every time it's executed, I don't know the details) tl;dr: running ANALYZE makes it almost impossible to use indexes on boolean fields, even when you know they would be helpful. A: Short answer: it may take more time to calculate than time saved. Unlike indices the ANALYZE-statistics are not kept up-to-date automatically when data is added or updated. You should rerun ANALYZE any time a significant amount of data has been added of updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Defining an object without calling its constructor in C++ In C++, I want to define an object as a member of a class like this: Object myObject; However doing this will try to call it's parameterless constructor, which doesn't exist. However I need the constructor to be called after the containing class has done some initialising. Something like this. class Program { public: Object myObject; //Should not try to call the constructor or do any initializing Program() { ... //Now call the constructor myObject = Object(...); } } A: You can fully control the object construction and destruction by this trick: template<typename T> struct DefferedObject { DefferedObject(){} ~DefferedObject(){ value.~T(); } template<typename...TArgs> void Construct(TArgs&&...args) { new (&value) T(std::forward<TArgs>(args)...); } public: union { T value; }; }; Apply on your sample: class Program { public: DefferedObject<Object> myObject; //Should not try to call the constructor or do any initializing Program() { ... //Now call the constructor myObject.Construct(....); } } Big advantage of this solution, is that it does not require any additional allocations, and object memory allocated as normal, but you have control when call to constructor. Another sample link A: If you have access to boost, there is a handy object that is provided called boost::optional<> - this avoids the need for dynamic allocation, e.g. class foo { foo() // default std::string ctor is not called.. { bar = boost::in_place<std::string>("foo"); // using in place construction (avoid temporary) } private: boost::optional<std::string> bar; }; A: You may also be able to rewrite your code to use the constructor initializer list, if you can move off the other initialization into constructors: class MyClass { MyObject myObject; // MyObject doesn't have a default constructor public: MyClass() : /* Make sure that any other initialization needed goes before myObject in other initializers*/ , myObject(/*non-default parameters go here*/) { ... } }; You need to be aware that following such a pattern will lead you to a path where you do a lot of work in constructors, which in turn leads to needing to grasp exception handling and safety (as the canonical way to return an error from a constructor is to throw an exception). A: Store a pointer to an Object rather than an actual Object thus: class Program { public: Object* myObject; // Will not try to call the constructor or do any initializing Program() { //Do initialization myObject = new Object(...); // Initialised now } } Don't forget to delete it in the destructor. Modern C++ helps you there, in that you could use an auto_ptr shared_ptr rather than a raw memory pointer. A: Others have posted solutions using raw pointers, but a smart pointer would be a better idea: class MyClass { std::unique_ptr<Object> pObj; // use boost::scoped_ptr for older compilers; std::unique_ptr is a C++0x feature public: MyClass() { // ... pObj.reset(new Object(...)); pObj->foo(); } // Don't need a destructor }; This avoids the need to add a destructor, and implicitly forbids copying (unless you write your own operator= and MyClass(const MyClass &). If you want to avoid a separate heap allocation, this can be done with boost's aligned_storage and placement new. Untested: template<typename T> class DelayedAlloc : boost::noncopyable { boost::aligned_storage<sizeof(T)> storage; bool valid; public: T &get() { assert(valid); return *(T *)storage.address(); } const T &get() const { assert(valid); return *(const T *)storage.address(); } DelayedAlloc() { valid = false; } // Note: Variadic templates require C++0x support template<typename Args...> void construct(Args&&... args) { assert(!valid); new(storage.address()) T(std::forward<Args>(args)...); valid = true; } void destruct() { assert(valid); valid = false; get().~T(); } ~DelayedAlloc() { if (valid) destruct(); } }; class MyClass { DelayedAlloc<Object> obj; public: MyClass() { // ... obj.construct(...); obj.get().foo(); } } Or, if Object is copyable (or movable), you can use boost::optional: class MyClass { boost::optional<Object> obj; public: MyClass() { // ... obj = Object(...); obj->foo(); } }; A: You can use a pointer (or a smart pointer) to do that. If you do not use a smart pointer, do make sure that your code free memory when the object is deleted. If you use a smart pointer, do not worry about it. class Program { public: Object * myObject; Program(): myObject(new Object()) { } ~Program() { delete myObject; } // WARNING: Create copy constructor and = operator to obey rule of three. } A: A trick that involves anonymous union and placement new this is similar to jenkas' answer but more direct class Program { public: union{ Object myObject; }; //being a union member in this case prevents the compiler from attempting to call the (undefined) default constructor Program() { ... //Now call the constructor new (&myObject) Object(...); } ~Program() { myobject.~Object(); //also make sure you explicitly call the object's destructor } } however the catch is that now you must explicitly define all the special member functions as the compiler will delete them by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: AtomicXXX.lazySet(...) in terms of happens before edges What does mean AtomicXXX.lazySet(value) method in terms of happens-before edges, used in most of JMM reasoning? The javadocs is pure on it, and Sun bug 6275329 states: The semantics are that the write is guaranteed not to be re-ordered with any previous write, but may be reordered with subsequent operations (or equivalently, might not be visible to other threads) until some other volatile write or synchronizing action occurs). But this not a reasoning about HB edges, so it confuses me. Does it mean what lazySet() semantics can't be expressed in terms of HB edges? UPDATE: I'll try to concretize my question. I can use ordinary volatile field in following scenario: //thread 1: producer ...fill some data structure myVolatileFlag = 1; //thread 2: consumer while(myVolatileFlag!=1){ //spin-wait } ...use data structure... In this scenario use of "data structure" in consumer is correct, since volatile flag write-read make HB edge, giving guarantee what all writes to "data structure" by producer will be completed, and visible by consumer. But what if I'll use AtomicInteger.lazySet/get instead of volatile write/read in this scenario? //thread 1: producer ...fill some data structure myAtomicFlag.lazySet(1); //thread 2: consumer while(myAtomicFlag.get()!=1){ //spin-wait } ...use data structure... will it be still correct? Can I still really on "data structure" values visibility in consumer thread? It is not "from air" question -- I've seen such method in LMAX Disruptor code in exactly this scenario, and I don't understand how to prove it is correct... A: Based on the Javadoc of Unsafe (the putOrderedInt is used in the AtomicInteger.lazySet) /** * Version of {@link #putObjectVolatile(Object, long, Object)} * that does not guarantee immediate visibility of the store to * other threads. This method is generally only useful if the * underlying field is a Java volatile (or if an array cell, one * that is otherwise only accessed using volatile accesses). */ public native void putOrderedObject(Object o, long offset, Object x); /** Ordered/Lazy version of {@link #putIntVolatile(Object, long, int)} */ public native void putOrderedInt(Object o, long offset, int x); The backing fields in the AtomicXXX classes are volatile. The lazySet seems to write to these fields as if they are not volatile, which would remove the happens-before edges you are expecting. As noted in your link this would be useful for nulling values to be eligible for GC without having to incur the volatile write. Edit: This is to answer your update. If you take a look at the quote you provided from the link then you lose any memory guarantees you had with the volatile write. The lazySet will not be ordered above where it is being written to, but without any other actual synchronization you lose the guarantee that the consumer will see any changes that were written before it. It is perfectly legal to delay the write of the myAtomicFlag and there for any writes before it until some other form of synchronization occurs. A: The lazySet operations do not create happens-before edges and are therefore not guaranteed to be immediately visible. This is a low-level optimization that has only a few use-cases, which are mostly in concurrent data structures. The garbage collection example of nulling out linked list pointers has no user-visible side effects. The nulling is preferred so that if nodes in the list are in different generations, it doesn't force a more expensive collection to be performed to discard the link chain. The use of lazySet maintains hygenic semantics without incurring volatile write overhead. Another example is the usage of volatile fields guarded by a lock, such as in ConcurrentHashMap. The fields are volatile to allow lock-free reads, but writes must be performed under a lock to ensure strict consistency. As the lock guarantees the happens-before edge on release, an optimization is to use lazySet when writing to the fields and flushing all of the updates when unlocking. This helps keep the critical section short by avoiding unnecessary stalls and bus traffic. If you write a concurrent data structure then lazySet is a good trick to be aware of. Its a low-level optimization so its only worth considering when performance tuning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: JSF Controller Bean - Scoping WI have a question about the "Best Practice" Design for controller beans. I was reading this very good question and the linking article: Question "JSF backing bean structure (best practices)" Scoping Best Practice Online Article Distinctions between different kinds of JSF Managed-beans My question is concerning the controller bean. I'm using JSF / Spring and was wondering why I would want to use request scope for Controller beans? The controller logic being defined as "...execute some kind of business logic and return navigation outcome.." I would think doesn't require a request scope but either session/application scope. Why keep creating those controller objects on every request? In my case I would create the controller bean in the faces-config obviously and inject it with my managed properties through spring. Thoughts please around the scoping? Thanks. Clarification: Using JSF 1.2, Spring 3. Using faces-config.xml to declare my beans. Not through annotations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SharePoint 2007 onchange event not unbinding in ie6 Im confident that this isnt a sharepoint 2007 issue, but id rather cover all of my bases. I am consulting at a large company, developing a sharepoint solution for their intranet. One of my tasks is to switch the regular dropdownlist in the sharepoint 2007 listview with something that has type ahead and filtering. So i chose a jquery combobox. Now, in everything but ie6 this combobox works, and the onchange event also works. My process is this: function diidFilterLinkTitleNoMenuOnChange() { FilterField("{9232EB4D-2E5D-40D3-A1C0-818CC21AC839}","LinkTitleNoMenu",this._selOption.value, this.selectedIndex); } $(document).ready(function(){ window.dhx_globalImgPath='../_layouts/Intranet.Portal.Custom/PeopleChangesFiles/imgs/'; var y = document.getElementById('diidFilterLinkTitleNoMenu'); if(y != null) { $('#diidFilterLinkTitleNoMenu').change(function(){}).attr('onchange',function(){}); var z = dhtmlXComboFromSelect('diidFilterLinkTitleNoMenu'); z.enableFilteringMode(true); z.attachEvent("onchange",diidFilterLinkTitleNoMenuOnChange); y.parentNode.removeChild(y); } }) I am removing the current onchange event before turning the select list into a combobox, then reassigning a different onchange event. What is happening as far as i can tell in ie6, is that the old onchange event is still there, still attached, and firing first as it breaks the code and my event doesnt run. Is there a special way in removing events in ie6? Or am i doing this wrong? A: Thats because change() method is a shortcut for .bind('change', handler). And .bind attaches event handler not removes or overrides. Quote from bind() page: When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. Use unbind to remove event handlers: $('#diidFilterLinkTitleNoMenu').unbind('change');
{ "language": "en", "url": "https://stackoverflow.com/questions/7557161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Broadcast receiver registered from code I register receiver from the onCreate from my activity like this IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadcastReceiver mReceiver = new ScreenOnOffReceiver(); registerReceiver(mReceiver, filter); And everything works good and the receiver get the intents, and everything is working good until, i close the activity. When I close the activity the method doesn't receive intents any more... Does someone one know how can I register for receiver . . . Note : I do not unregistered the receiver , but it happens somehow magically it just stop working properly . . . A: The idea of registering a broadcast receiver in an activity is to get notified of some event while the activity is on (register the receiver in onResume, unregister it in onPause). If you need a broadcast receiver to handle the event while the activity isn't showing, then register your broadcast receiver in your manifest. If you need to handle both cases in a different way, then use a ordered broadcast. A: If you want to receive messages all the time than you will need to create your own service and do your intent filter in onStartCommand method and unregister in onDestroy. More details here http://developer.android.com/reference/android/app/Service.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7557163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Image instead of title in navigation bar of TTLauncherView I use the TTLauncherView in my project. To have a custom navigation bar background I have subclassed the UINavigationBar in my app delegate. This works fine and all navigation bar's now have this custom style. @implementation UINavigationBar (CustomNavBarBG) -(void)drawRect:(CGRect)rect{ UIImage *image = [UIImage imageNamed:@"navbar_s.png"]; [image drawInRect:self.bounds]; } @end When navigating through the views the title appears in the middle of the bar. But on the navigation bar of the main screen, the launcher, I want to have an image instead of the title. Is this possible? How to implement it? A: you can override the default title view when you load your controller with a custom UIView, such as a UIButton: /////////////////////////////////////////////////////////////////////////////////////////////////// - (void)viewDidLoad { [super viewDidLoad]; UIButton *logoView = [[[UIButton alloc] initWithFrame:CGRectMake(0,0,85,40)] autorelease]; [logoView setBackgroundImage:[UIImage imageNamed:@"navBarLogo.png"] forState:UIControlStateNormal]; [logoView setUserInteractionEnabled:NO]; self.navigationItem.titleView = logoView; } I'm actually not sure why I used UIButton here :-) maybe you can use a UIImageView instead, but this code works fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: regex websphere file with php i'm trying to create a regular expression for this kind of log: [9/23/11 11:09:53:632 CEST] 0000005b FormLoginExte 3 Form based login: userid/password present in the form. User is: user1 i've created this: preg_match("/^[\d+/\d+/\d+\ \d+:\d+:\d+:\d+\ CEST]\ \w{8}\ \w+?\ +\w+?\ +.+?$", $line, $matches); // pattern to format the line and get this error: [9/21/11 12:11:03:126 CEST] 0000004d FormLoginExte 3 Form based login: userid/password present in the form. User is: user1 Warning: preg_match() [function.preg-match]: Unknown modifier '\' in C:\AppServ\www\logWebsphere\logWebspere.php on line 79 A: Regular expressions (preg_match) are slower than running a simple: <?php $data = explode(" ","[9/23/11 11:09:53:632 CEST] 0000005b FormLoginExte 3 Form based login: userid/password present in the form. User is: user1"); //data now contains all the info that you need var_dump($data); ?> POC here: http://codepad.org/nmo90QlI A: You are using forward slashes as your delimeter but are also including unescaped forward slashes in your regex. You should escape them first by preceding them with a two backslashes. Two backslashes are required because the backslash is itself a meta character and must be escaped by using a second backslash. This in effect creates one backslash which can be used to escape the delimeter. So your regex becomes: preg_match("/^[\d+\\/\d+\\/\d+\ \d+:\d+:\d+:\d+\ CEST]\ \w{8}\ \w+?\ +\w+?\ +.+?$/", $line, $matches); Please note you were also missing a delimiter. Additionally, you could simply change delimters, like so: preg_match("~^[\d+\/\d+\/\d+\ \d+:\d+:\d+:\d+\ CEST]\ \w{8}\ \w+?\ +\w+?\ +.+?$~", $line, $matches); Edit I've just noticed that you are trying to match [ and ] as literals. These, however, are meta characters (character classes) and should, I believe, also be escaped( \[ and \]).
{ "language": "en", "url": "https://stackoverflow.com/questions/7557165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: capture url in href tag I have an exit page that informs users that they are leaving my site. How do I capture the intended url from the referring page and send the user to it once they've acknowledged on the exit page that they're aware they're leaving my site and wish to continue to their destination? My current setup works with an absolute link but not with a relative path. this works: href="http://acme.com/company/brand/leaving/?url=http://www.about.info/choices/ this doesn't: href="../COMPANY/BRAND/leaving/?url=http://www.about.info/choices/" the continue button triggers the following function: function gbye(){ var url = window.location.toString(); var url_arr= url.split("?url="); if(url_arr.length>1) { try { window.location = url_arr[1]; } catch (e) { } } return false; } can anyone explain why the href with the relative path doesn't work (returns a directory list) and how I can make the relative path work? A: Most servers are running under a Linux environment, where the filesystem is case-sensitive, ie file names with different cases are treated different. If the first link worked correctly, use ../company/brand/leaving/?url=.... I recommend using a / (absolute root) instead of ../, because you won't have to edit your files when you move the files to a different directory, when using /.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery issue in IE, Chrome but not in FF Having some problems with a piece of Jquery code, well that's where I think the problem is - On FF when the page loads after 2 seconds it animates panels from the left of the screen to the right. It looks fine without any issues but in Chrome and IE it jumps back and continues moving across. Here is the code - <script type="text/javascript" language="javascript"> $(function() { // Display div slowly $('#one').delay(2000).show('slow'); $("#one").animate({ left: '+=159' }, 3000); $('#two').delay(3000).show('slow'); $("#two").animate({ left: '+=159' }, 3000); $('#three').delay(4000).show('slow'); $("#three").animate({ left: '+=159' }, 3000); $('#four').delay(5000).show('slow'); $("#four").animate({ left: '+=159' }, 3000); }); </script> Here is a preview of the page - http://www.visrez.com/preview/och-group/ P.S I'm not ruling out it's a css issue... Thanks in advance for any help! Gearóid A: i prepared a demo with your code and it works. http://jsfiddle.net/AjDLS/2/ i don't have your problem, so that makes me think you must have some other javascript issue, or css issue, could you post more code? A: The problem stems from the fact that Chrome isn't taking into account the position (relative to the offset parent) that div has on the page before you start moving it. So, once animated, it has a value of left: 159px which is relative to the body. Firefox is taking the original position into account and ends with left: 256px. I haven't looked into why this happens yet but here are a few things that you could do (workarounds): * *Before animating figure out the position relative to the offset parent and set the CSS top and left attributes. Then, hopefully, the final value will be the value that you set plus 159px. Something like: var offset = $("#one").offset(); $("#one").css({"top": offset.top, "left": offset.left}); // animate *Wrap #oneTop and #one and each other pair in a div that is position: relative. This will set the offset parent of the animated div to the position: relative div. This way the +159px is relative to where the div would be in the document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling method X from each parent what i'm trying to do is call each method "init" from current class's parents. I'm doing that to avoid programmers to have to call init method (parent::init()) each time they create an init method in a new controller. Example: class Aspic\Controller { } // main controller class ControllerA extends Aspic\Controller { public function init() {/* do something 1 */} class ControllerB extends ControllerA {} class ControllerC extends ControllerB { public function init() { /* do something 2 */ } class ControllerD extends ControllerC {} As you can see the init methods do not call parent init method but i want my app (there is an option) do it. Thus when I'm loading ControllerD, before calling it's init method (there isn't in the example but the app test it), i want to call each parent init method. sound like this: parent::init(); // Controller C init parent::parent::parent::init(); // Controller A init So i did : if($this->_autoCallParentsInit) { // Aspic\Controller is the main controller, which is the mother of all others $aspicControllerRc = new \ReflectionClass('Aspic\\Controller'); $rc = new \ReflectionClass($this); // We are in D $currPrefix = ''; // Calling each init methods of current class parent // Avoid using parent::init() in each controller while(($parentClass = $rc->getParentClass()) AND $aspicControllerRc->isInstance($parentClass)) { /* $aspicControllerRc->isInstance($parentClass) => because Aspic\Controller extends a "Base class". Thus, we stopped at Aspic\Controller */ $currPrefix .= 'parent::'; // Must have explicit method (not inherited from parent) BUT actually hasMethod does not care if($parentClass->hasMethod('init')) { call_user_func($currPrefix.'init'); } } } This is not working because ReflectionClass::isInstance does not accept others argument than the object we want to test (and the not a ReflectionClass object representing it as in the example) ** Simply: I have an object $x, and i want to call the init method of each parent of the class of $x. ** Is it possible ? I hope i was clear :) Thanks A: ControllerB has an init() method by virtue of extending ControllerA, so you shouldn't have to call parent::parent::init() to get to A's from C. You should be fine to call parent::init() from ControllerD, which will call ControllerC's init() method. If ControllerC calls parent::init() it will be calling ControllerA's init() method. If you're trying to skip the Controller's specific init() code when being called by a subclass, you could add a flag function init($call_parent = false) and then, from lower controllers, call parent::init(true); A: If you're not using the classes statically (which, from your code not stating static function, I assume you're not), have you tried using the __construct() method? It gets automatically called when you instantiate the class, for example: class MyClass { public function __construct() { echo 'Hello!'; } } $class = new MyClass(); That will automatically output 'Hello!', however if you extend the class and that child class contains a __construct() method you will have to put parent::__construct() inside the childs construct method, however you wont have to do it for every parent, just the once, for example: class MyClassB extends MyClass { public function __construct() { parent::__construct(); echo 'World!'; } } class MyOtherClass extends MyClassB public function __construct() { parent::__construct(); echo 'How\'s it going!'; } } $class = new MyOtherClass(); That will output "Hello! World! How's it going!"
{ "language": "en", "url": "https://stackoverflow.com/questions/7557170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to shorten a java.security.MessageDigest generated value? If I generate a message digest (for a security feature in my app) using this Java code: java.security.MessageDigest saltDigest = MessageDigest.getInstance("SHA-256"); saltDigest.update(UUID.randomUUID().toString().getBytes("UTF-8")); String digest = String.valueOf(Hex.encode(saltDigest.digest())); I end up with a really long string like the following: 29bcf49cbd57bbc41e601b399a93218ef99c6e36bae3598b5a5a64ac66d9c254 Not the nicest thing to pass on a URL! Is there a way to shorten this? A: Well, that's the expected size of a SHA-256 hash, right? You could always do String sha256 = yourSha256Calculation(); sha256.substring(0,10); To get a shorter string, but that would not be SHA-256. What are you really trying to achieve? SHA-256 is not the shortest hash out there, look at http://www.fileformat.info/tool/hash.htm?text=hello for a comparison.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS spacing problem. need fresh eyes.(should be easy) okay so this minor yet MASSIVE annoyace is that, i have a site im working on, and a panel in particular is behaving oddly. i have a generic box div which will hold 2 images, one ontop of the other and i want absolutely no spacing inbetween them. problem is that no matter what i do, when on dev mode it behaves normally, but when i publish, i see space inbetween the images. normally, i dont set widths/height etc depending on what im doing but for this...its been SUCH the major pain that i declared heights on everything to make sure im not missing a few digits here or there, and still nothing. heres an example of what is happening. (on my server) http://somdowprod.net/4testing/erase if you look there, theres about a 5px space between the pic on top and the tst pic on bottom no matter the browser (ff/ie/chrome) ...thing is behaving like tables....... heres the code for the inline css im testing/isolated: <style type="text/css"> body{ margin:0px; padding:0px;} .nospacedammit{ margin:0px; padding:0px;} #portS_mainW{ width:400px; height:500px; padding:0px; margin:0px;} #portS_mainW img{ margin:0px; padding:0px; } </style> and heres the basic html for this panel: <div id="portS_mainW"> <span class="nospacedammit"><img src="images/xrodemo.jpg" alt="xro" width="400" height="300"/></span> <span class="nospacedammit"><img src="images/erase.png" alt="xro" width="400" height="200"/></span> </div> ive added heights to make 100% sure about the #s, ive added margins/paddings to zero out on every element to again make sure theres no spacing. ive also wrapped each image in a span tag, then added an overall everything to zero style to it ....trying to force zero spacing in every way i can thing of. and still nothing. any ideas, insight i gladly appreciate. thank you in advance. A: Try adding float:left to your images. Just tested this in Firefox 3.6 and it works for me :-) I'm not 100% sure why this happens but my guess would be because none of your elements have any positioning applied to them, leaving it up to the browser to decide. A: Try this: <img class="nospacedammit" src="images/xrodemo.jpg" alt="xro" width="400" height="300"/> <img class="nospacedammit" src="images/erase.png" alt="xro" width="400" height="200"/> And add a property of display: block; to .nospacedammit A: You could set the line-height: 0; on the nospacedammit class. That is the reason that the space is inserted in between the 2 images. Edit: you need to set the display to display: block as well
{ "language": "en", "url": "https://stackoverflow.com/questions/7557174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I toggle a calendar or datepicker in an overlay when clicking a link? I'm trying to attach the jQuery datepicker to a hyperlink vs the conventional input element. I know this has already been talked about here and there which led me to this implementation: $(document).ready(function() { var picker_link_id = "datepicker_link" var picker_div_id = "datepicker" var picker_div = $("#" + picker_div_id) // initialize the datepicker picker_div.datepicker({ onSelect: function(dateText, picker) { picker_div.hide(); // custom work } }); // position & toggle the datepicker on link click $("#" + picker_link_id).click(function() { var $this = $(this) // position the datepicker picker_div.css('position', 'absolute'); picker_div.css('left', $this.position().left - (picker_div.width() - $this.width())); picker_div.toggle() return false; }); // pressing ESC or clicking outside the datepicker should close it $(document) .bind("keypress", function(e) { if ( e.keyCode == 27 ) picker_div.hide(); }) .bind("mousedown", function(e) { if ( e.target.id == $("#" + picker_link_id)[0].id ) return; if ( e.target.id != picker_div_id && $(e.target).parents('#' + picker_div_id).length == 0 ) picker_div.hide(); }); }); In my view, I have the following HTML: <a href="#" id="datepicker_link">September 26, 2011</a> <div id="datepicker"></div> Even though the above works, it seems like I'm re-creating some jQuery logic. Is there a better way to do this? A: One alternative is to use an input element, instead of a div one, and position the input element out of the sight of the screen. Then you will be able to make use of the .datepicker('show') and .datepicker('hide'). Then you can position the datepicker div with a css rule, such as the following one: #ui-datepicker-div { top: 50px !important; left: 50px !important; } Note the !important keyword needs to be used, to effectively override the dynamic position. See an example here: http://jsfiddle.net/william/VCQsk/. A: $('#datepicker').datepicker('show');
{ "language": "en", "url": "https://stackoverflow.com/questions/7557175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery form not being submitted. Firebug no errors This jQuery isn't working. When i click Vote nothing happens. The div ratecontainer should disappear and nothing is inserted into MySQL when i check. In Firebug i get no errors. What did i do wrong? echo "<div class='ratecontainer'> <form id='rateform' action=''> <input type='hidden' id='rateid' value='$stackid' /> <input type='hidden' id='type' value='1' /> <a class='vote'>Vote</a> </form> </div>"; $(function() { $('.vote').click(function() { var rate= $("#rateid").val(); var type= $("#type").val(); var vote = "0"; var dataString = 'id=' + rate + '&type=' + type + '&v=' + vote; //alert (dataString);return false; $.ajax({ type: "POST", url: "/rate.php", data: dataString, success: function() { $('.ratecontainer').hide(); } }); return false; }); }); A: I'm assuming that your jquery code is inside <script type="text/javascript"> </script> ? A: I don't see it right away. But I know there is a really nice jQuery plugin to make this easier for you: http://jquery.malsup.com/form/ You should have rate.php do some debugging... for example print_r($_POST); A: Your code should probably be like this: <div class='ratecontainer'> <form id='rateform' action=''> <input type='hidden' id='rateid' value='<?php echo $stackid ?>' /> <input type='hidden' id='type' value='1' /> <a class='vote'>Vote</a> </form> </div> <script> $(function() { $('.vote').click(function() { var rate= $("#rateid").val(); var type= $("#type").val(); var vote = "0"; var dataString = 'id=' + rate + '&type=' + type + '&v=' + vote; //alert (dataString);return false; $.ajax({ type: "POST", url: "/rate.php", data: dataString, success: function() { $('.ratecontainer').hide(); } }); return false; }); }); </script> And don't have that wrapped in a big <?php ?> tag. Assuming your rate.php is written correctly (which is a stretch) this should work. (jsFiddle)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Move constructor for std::mutex Many classes in the c++ standard library now have move constructors, for example - thread::thread(thread&& t) But it appears that std::mutex does not. I understand that they can't be copied, but it seems to make sense to be able to return one from a "make_mutex" function for example. (Not saying it's useful, just that it makes sense) Is there any reason why std::mutex doesn't have a move constructor? A: Well... mainly because I don't think they should move. Literally. In some OS-es a mutex might be modeled as a handle (so you could copy them) but IIRC a pthreads mutex is manipulated in-place. If you are going to relocate that, any threadsafety is going fly right out of the window (how would the other threads know that the mutex had just changed it's memory address...)? A: Remember that C++ takes the "don't pay for what you don't use" philosophy to heart. Let's consider for instance an imaginary platform that uses an opaque type to represent a mutex; let's call that type mutex_t. If the interface to operate on that mutex uses mutex_t* as arguments, for instance like void mutex_init(mutex_t* mutex); to 'construct' a mutex, it might very well the case that the address of the mutex is what's used to uniquely identify a mutex. If this is the case, then that means that mutex_t is not copyable: mutex_t kaboom() { mutex_t mutex; mutex_init(&mutex); return mutex; // disaster } There is no guarantee here when doing mutex_t mutex = kaboom(); that &mutex is the same value as &mutex in the function block. When the day comes that an implementor wants to write an std::mutex for that platform, if the requirements are that type be movable, then that means the internal mutex_t must be placed in dynamically-allocated memory, with all the associated penalties. On the other hand, while right now std::mutex is not movable, it is very easy to 'return' one from a function: return an std::unique_ptr<std::mutex> instead. This still pays the costs of dynamic allocation but only in one spot. All the other code that doesn't need to move an std::mutex doesn't have to pay this. In other words, since moving a mutex isn't a core operation of what a mutex is about, not requiring std::mutex to be movable doesn't remove any functionality (thanks to the non-movable T => movable std::unique_ptr<T> transformation) and will incur minimal overhead costs over using the native type directly. std::thread could have been similarly specified to not be movable, which would have made the typical lifetime as such: running (associated to a thread of execution), after the call to the valued constructor; and detached/joined (associated with no thread of execution), after a call to join or detach. As I understand it an std::vector<std::thread> would still have been usable since the type would have been EmplaceConstructible. edit: Incorrect! The type would still need to be movable (when reallocating after all). So to me that's rationale enough: it's typical to put std::thread into containers like std::vector and std::deque, so the functionality is welcome for that type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Validating Users Authenticated with Oauth I've got Oauth support in place for an app I'm working on. What I'm trying to work through is the logic for associating Oauth accounts. Example: Let's say a user has logged in before. They authenticated using Facebook. I now have an email address which I can safely assume will always be unique to that user. However, Twitter does not provide email addresses through its Oauth implementation, so if someone signs in with Twitter, and then Facebook, how do I correctly associate their account? I can't use user name, or handler, because obviously that could vary per provider. Is there any other way I could do this? Do I require the user to enter their email address if they use an Oauth provider which omits it? I'm trying to put together the best user experience and the most stable system - so your help is highly appreciated. A: If you're looking at working with multiple identity providers then your best solution would be to use an internal ID unique to your system and then associate the external accounts with that ID when the external authentication takes place. Additionally users in FB can change their primary email address so it would be safe to assume it's unique it's probably not safe to assume that it's current.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: get most active users in a facebook page How do I get the most active users in a facebook page for a certain time period? Is is possible to do it with the graph api? Thank you! A: There is no built in way but you could pull down all posts via the Graph API and loop through the posts, comments, and likes and make your own ranking algorithm from that data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can SQL Server Report Services Designer be rehosted? I would like to be able to edit and create at run time reports based on SQL Server Reporting Services from my application. Can SQL Server Report Services Designer control be rehosted in a custom .Net application outside Visual Studio, in a similar manner to how the WF workflow designer does? Is there any code sample for this? A: Use Report Builder for designing reports outside of Business Intelligence Development Studio. If you want to launch report builder from a hyperlink, make sure at least SQL Server 2008 SP1 is installed on the report server and use this URL: http://<servername>/reportserver/reportbuilder/ReportBuilder_2_0_0_0.application
{ "language": "en", "url": "https://stackoverflow.com/questions/7557190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RegEx - HTML between two values I am looking to get the html that is included between the following text: <ul type="square"> </ul> What's the most efficient way? A: I always use XPath to do things like that. Use an XPath that will extract the node and then you can fetch the InnerHTML from that node. Very clean, and the right tool for the job. Additional details: The HAP Explorer is a nice tool for getting the XPath you need. Copy/paste the HTML into HAP Explorer, navigate to the node of interest, copy/paste the XPath for that node. Put that XPath string in a string resource, fetch it at runtime, apply it to the HTML document to extract the node, fetch the desired information from the node. A: Regular expressions should not be used to parse HTML! This will definitely not work: <ul type="square">(.*)</ul> A: I agree that an HTML parser is the correct way to solve this problem. But, to humor you and answer your original question purely for academic interest, I propose this: /<[Uu][Ll] +type=("square"|square) *>((.*?(<ul[^>]*>.*</ul>)?)*)<\/[Uu][Ll]>/s I'm sure there are cases where this will fail, but I can't think of any so please suggest /* them */ more. Let me restate that I don't recommend you use this in your project. I am merely doing this out of academic interest, and as a demonstration of WHY a regex that parses html is bad and complicated. A: If you really want one: @<ul type="square">(.*?)</ul>@im
{ "language": "en", "url": "https://stackoverflow.com/questions/7557191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to rewrite a form action on the "Help Page" of an ASP.NET web service For normal .aspx pages I can just put a Form.browser file into the App_Browsers directory like the following. <browsers> <browser refID="Default"> <controlAdapters> <adapter controlType="System.Web.UI.HtmlControls.HtmlForm" adapterType="MyProject.FormRewriterControlAdapter" /> </controlAdapters> </browser> </browsers> And in that class I can rewrite the action attribute of the form. However in the case of web service help pages, this file is not considered and the form is written with the default action (using an absolute URL). This doesn't let me use a reverse proxy (Ionic's ISAPI Rewrite Filter - IIRF) to access my web service. How can I accomplish this and rewrite the form action on the help page correctly? A: If you need to change the help page, use the <wsdlHelpGenerator> element in the web.config. You can find the default help page at C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\DefaultWsdlHelpGenerator.as‌​px. Note that this will only help you when testing the service through the help page. It has nothing to do with how clients will access the service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WYSIWYG editor component for GWT I'm looking for a WYSIWYG editor component for GWT or which is easy to use in a GWT generated page. Any clue? I took a look at CKEditor, but I don't know if it's easy to integrate with GWT. If you have done something like this, I'm interested in your feedback. A: CKEditor has been integrated with GWT (gwt-ckeditor, vaadin-ckeditor), as has TinyMCE (tinymce-gwt, gwt-tinymce) and several other WYSIWYG editors (gwt-html-editor, etc...). A: gdbe Google-Docs Base Editor The Google-Docs Base Editor (GDBE) is a web based text editor built to model the existing Google-Docs editors. It integrates with Google-Docs via the GData API. The purpose of GDBE is to give developers a starting point for building editors for different document types that can be integrated into Google's editor suite. GDBE is written in Java and makes use of the GData API to communicate with Google Docs. The client side is implemented GWT and the server side is built with AppEngine in mind. http://code.google.com/p/gdbe/
{ "language": "en", "url": "https://stackoverflow.com/questions/7557196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to change datatype from xs:string to strongly types in Biztalk schema? I need to have a datatype of Amount (reference) for my Amount field. How to change that? Now I just get the normal datatypes (xs:string, xs:double, etc), but the existing fields are strongly typed like this - Datatype : Amount (Reference). How to do that? A: seems like you need to import your reference schema and set the data type to the Amount field defined within it. If that's the case, you can do that by; a) selecting you the node b) Selecting the Import property in the Property Window c) Leave the 2Import new schema as:" option as XSD Import and click "Add..." d) Point to your reference schema. You should be able to set the data type of your amount field to the refernce type now. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7557202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLITE: PRAGMA temp_store = MEMORY In all optimization guides people talk about pragma's like JOURNAL_MODE or SYNCHRONOUS, but I never read anything about the TEMP_STORE pragma? I would expect it has a large impact, so why is it never mentioned? It's purpose is to move all SQLite's internal temporary tables from disk (temp directory) to memory, which seems a lot faster than hitting the disk on every SELECT? A: SQLite locks the entire database when doing writes, so I would imagine that it is better to get the data onto the platters before proceeding with your next task. Putting the data in memory is most likely reserved for those occasions when you would only want a temporary data store (as the TEMP_STORE name implies); you would still need to provide a method for periodically flushing the data to disk (if you want to save it), and since the locking is not granular, you would have to flush the entire database. In other words, TEMP_STORE is not a caching mechanism.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Image upload doesnt work in IE? But it's fine in other browsers So I'm facing this issue, one I've never had before in over 4 years of development, HTML code <fieldset id="step_3" style="display:none;"> <legend>3. Add Photos</legend> <ol> <li> <label for="main_image">Main Image..</label> <input type="file" name="extra_img0" size="35"/> </li> <li> <label for="extra_img1">Extra Images</label> <input type="file" name="extra_img1" size="35"/> </li> <li> <label for="extra_img2"> </label> <input type="file" name="extra_img2" size="35" /> </li> <li> <label for="extra_img3"> </label> <input type="file" name="extra_img3" size="35"/> </li> <li> <input type="submit" name="add" value="Add Listing"/> </li> </ol> </fieldset> And the PHP code... $i = 0; while($i < 4) { if(!empty($_FILES['extra_img'.$i]['name'])) { if($_FILES['extra_img'.$i]['type'] == "image/gif" OR $_FILES['extra_img'.$i]['type'] == "image/png" OR $_FILES['extra_img'.$i]['type'] == "image/jpeg") { $img = md5(microtime()).'.jpg'; $image = New SimpleImage(); $image->load($_FILES['extra_img'.$i][tmp_name]); if($image->getWidth() < $image->getHeight()) { $image->resizeToWidth("300"); $image->cutHeight("300"); } else { $image->resizeToHeight("300"); $image->cutWidth("300"); } $image->save('uploads/listings/large/'.$img); $db->query("INSERT INTO `images_to_listing` (`listing_id` ,`name`) VALUES ('{$listing_id}', '{$img}');"); } } $i++; } Code works just fine in all browsers apart from IE? It doesn't even get inserted into MYSQl, any ideas? A: See if this works: // List of allowable file extensions $allowedExtensions = array ( 'jpg', 'jpeg', 'gif', 'png' ); for ($i = 0; $i < 4; $i++) { // Loop 0-3 if (!empty($_FILES["extra_img$i"]['name']) && in_array(strtolower(pathinfo($_FILES["extra_img$i"]['name'],PATHINFO_EXTENSION),$allowedExtensions))) { // If you get here, the image is set and has a file extension specified as allowable above $img = md5(microtime()).'.jpg'; $image = New SimpleImage(); $image->load($_FILES["extra_img$i"]['tmp_name']); if ($image->getWidth() < $image->getHeight()) { $image->resizeToWidth("300"); $image->cutHeight("300"); } else { $image->resizeToHeight("300"); $image->cutWidth("300"); } $image->save("uploads/listings/large/$img"); $db->query("INSERT INTO `images_to_listing` (`listing_id` ,`name`) VALUES ('{$listing_id}', '{$img}');"); } else { // You may want to add error handling here } } The key difference is that is uses the file's extension, rather than it's MIME type (which relies on the browser being sensible).
{ "language": "en", "url": "https://stackoverflow.com/questions/7557206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I handle multiple CheckBoxes in the MVVM pattern? Binding checkbox in WPF is common issue, but I am still not finding example code which is easy to follow for beginners. I have check box list in WPF to select favorite sports’ name. The number of checkboxes is static in my case. Can anyone show me how to implement ViewModel for this issue? FavoriteSportsView.xaml: <StackPanel Height="50" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"> <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Football" Content="Football" Margin="5" /> <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Hockey" Content="Hockey" Margin="5" /> <CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Golf" Content="Golf" Margin="5" /> </StackPanel> FavoriteSportsViewModel.cs public class FavoriteSportsViewModel.cs { //Since I am using the same IsChecked in all check box options, I found all check //boxes gets either checked or unchecked when I just check or uncheck one option. //How do i resolve this issue? I don't think i need seprate IsChecked for each //check box option. private bool _isChecked; public bool IsChecked{ get { return _isChecked; } set { if (value != _isChecked) _isChecked = value; this.OnPropertyChanged("IsChecked"); } } //How do i detect parameter in this method? private ICommand _sportsResponseCommand; public ICommand SportsResponseCommand { get { if (_sportsResponseCommand== null) _sportsResponseCommand= new RelayCommand(a => DoCollectSelectedGames(), p => true); return _sportsResponseCommand; } set { _sportsResponseCommand= value; } } private void DoCollectSelectedGames(){ //Here i push all selected games in an array } public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } I'm not sure how to do the following in above ViewModel: 1. How do I implement single method to handle all my options? 2. how do I detect each one of the checkboxes to see whether checked or not 3. How do i utlize CommandParameter? 4. How do i implement SportsResponseCommand correctly A: Your view model should look something like this: public class MyViewModel : INotifyPropertyChanged { //INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } //bindable property private bool _football; public bool Football { get { return _football; } set { if (value != _football) { _football = value; this.OnPropertyChanged("Football"); } } } //... and the same for Golf and Hockey } Then you associate your view model with the view by setting the DataContext property (this will most likely be in the Window or UserControl code behind, though there are a lot of ways to achieve this). Finally, update your bindings so that they look like: <CheckBox IsChecked="{Binding Football, Mode=TwoWay}" Content="Football" Margin="5" /> <CheckBox IsChecked="{Binding Golf, Mode=TwoWay}" Content="Football" Margin="5" /> As a final comment, you shouldn't really need to bind the Command property - you can just write whatever code you need to run in the property setter on the view model. A: I highly recommend you to read this http://msdn.microsoft.com/en-us/magazine/dd419663.aspx I describe a solution below I tried to not modify your XAML code but it is not the only way (or the best approach) but contains all necessary elements! At first step you need your model I call it Model_Sport public class Model_Sport : INotifyPropertyChanged { #region Constructor public Model_Sport(string name, ICommand command) { Name = name; SportsResponseCommand = command; } #endregion static readonly PropertyChangedEventArgs _NameEventArgs = new PropertyChangedEventArgs("Name"); private string _Name = null; public string Name { get { return _Name; } set { _Name = value; OnPropertyChanged(_NameEventArgs); } } static readonly PropertyChangedEventArgs _SportsResponseCommandEventArgs = new PropertyChangedEventArgs("SportsResponseCommand"); private ICommand _SportsResponseCommand = null; public ICommand SportsResponseCommand { get { return _SportsResponseCommand; } set { _SportsResponseCommand = value; OnPropertyChanged(_SportsResponseCommandEventArgs); } } static readonly PropertyChangedEventArgs _IsCheckedEventArgs = new PropertyChangedEventArgs("IsChecked"); private bool _IsChecked = false; public bool IsChecked { get { return _IsChecked; } set { _IsChecked = value; OnPropertyChanged(_IsCheckedEventArgs); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(PropertyChangedEventArgs eventArgs) { if (PropertyChanged != null) { PropertyChanged(this, eventArgs); } } #endregion } Now you need a way to delegate your command “SportsResponseCommand”, DelegateCommand object will help you to do that public class DelegateCommand : ICommand { private readonly Action<object> _ExecuteMethod; private readonly Func< object, bool> _CanExecuteMethod; #region Constructors public DelegateCommand(Action<object>executeMethod, Func<object, bool> canExecuteMethod) { if (null == executeMethod) { throw new ArgumentNullException("executeMethod", "Delegate Command Delegates Cannot Be Null"); } _ExecuteMethod = executeMethod; _CanExecuteMethod = canExecuteMethod; } public DelegateCommand(Action<object>executeMethod) : this(executeMethod, null) { } #endregion #region Methods public bool CanExecute(object parameter) { if (_CanExecuteMethod == null) return true; return _CanExecuteMethod(parameter); } public void Execute(object parameter) { if (_ExecuteMethod == null) return; _ExecuteMethod(parameter); } bool ICommand.CanExecute(object parameter) { return CanExecute(parameter); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } void ICommand.Execute(object parameter) { Execute(parameter); } #endregion } Now “ViewModel” public class ViewModel { #region property public Dictionary<string, Model_Sport> Sports { get; set; } public DelegateCommand SportsResponseCommand { get; set; } #endregion public ViewModel() { Sports = new Dictionary<string, Model_Sport>(); SportsResponseCommand = new DelegateCommand(p => execute_SportsResponseCommand(p)); buildSports(); } private void buildSports() { Model_Sport football = new Model_Sport("Football", SportsResponseCommand); Model_Sport golf = new Model_Sport("Golf", SportsResponseCommand); Model_Sport hockey = new Model_Sport("Hockey", SportsResponseCommand); football.IsChecked = true; // just for test Sports.Add(football.Name, football); Sports.Add(golf.Name, golf); Sports.Add(hockey.Name, hockey); } private void execute_SportsResponseCommand(object p) { // TODO :what ever you want MessageBox.Show(p.ToString()); } } Now View Remember to set datacontext for your Window public MainWindow() { InitializeComponent(); this.DataContext = new ViewModel(); } Then in XAML <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" > <CheckBox DataContext="{Binding Path=Sports[Football]}" IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Football" Content="Football" Margin="5" /> <CheckBox DataContext="{Binding Path=Sports[Hockey]}" IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Hockey" Content="Hockey" Margin="5" /> <CheckBox DataContext="{Binding Path=Sports[Golf]}" IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Golf" Content="Golf" Margin="5" /> </StackPanel> A: If you just want a property in your ViewModel to get updated when the IsChecked changes, replace the Binding for IsChecked to a boolean property in your ViewModel that raises NotifyPropertyChanged on its "set". Now if you want to perform an action everytime IsChecked changes for one of the 3 CheckBoxes: First of all, replace your CommandParameter with "{Binding RelativeSource={RelativeSource Mode=Self}}" In your ViewModel (that should implement INotifyPropertyChanged), create an ICommand (SportsResponseCommand) that takes a CheckBox in parameter. In the command's method, check for the Content of your CheckBox, and for the "IsChecked" property then do your stuff with them. If you have further questions let me know. A: You can assign a view model by using this //for the view partial class MainView:Window { InitializeComponent(); this.DataContext=new MainViewModel(); } //ViewModel Code public class MainViewModel: INotifyPropertyChanged { //INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } //bindable property private bool _football; public bool Football { get { return _football; } set { if (value != _football) { _football = value; this.OnPropertyChanged("Football"); } } } //... and the same for Golf and Hockey }` and then you can implement Binding in XAML as <CheckBox IsChecked="{Binding Football, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Football" Content="Football" Margin="5" /> <CheckBox IsChecked="{Binding Golf, Mode=TwoWay}" Command="{Binding Path=SportsResponseCommand}" CommandParameter="Football" Content="Football" Margin="5" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7557209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visual studio for c++? I have installed visual studio express 2010 c++. However when trying to follow a beginners book and make the hello world program, visual studio opens up a project with this in it: #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { Console::WriteLine(L"Hello World"); return 0; } The thing is, this looks nothing like the c++ in the book i have just started reading (C++ Without Fear). In fact, if i type 'cout',even after entering using namespace std, cout is not found. This is the books example: #include "stdafx.h" #include <iostream> using namespace std; int main() { cout << "Never fear, C++ is here!"; return 0; } Am i missing something here? A: Create Windows (or Win32, don't remember exactly) C++ Console Application project, don't select C++/CLI project type. C++/CLI is very special language, which is used only for interoperability between managed and unmanaged code. It is better to forget about C+++/CLI at this stage... A: As Alex said start with C++ Win32 console project, but select empty project so that the IDE don't fill things out automatically! Go to Source Files in your Solution Explorer, right click on it and add new item and choose C++ file (call it main.cpp for example). At that point you should be ready to go. Try this sample code that I prepared for you... #include <iostream> using namespace std; int main(char *argv[], int argc) { cout << "Hello World!" << endl; return 0; } It should print out Hello World! in the console. A: You want to start with a Visual C++ Win32 Console Application. If you want to create your own files completely (i.e. no stub file with a main defined), you can check "Empty Project" in the options of the Win32 Application Wizard. A: This is not C++. This is so called "managed" C++. Basically, a totally different language by Microsoft that is compatible with their .NET platform. For example, you can mix C# code and managed C++ code in single binary. This technology is very Microsoft specific and is not portable to any other compiler/OS (even Mono, which is C# for Linux, doesn't have it). See Managed Extensions for C++ for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ nested preprocessor directions I'm using preprocessor directives to de-bloat some templated operator definitions. E.g. #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ template <typename T, typename U> \ vector<decltype(T() optype U())> operator optype (const vector<T>& A, const vector<U>& B){ \ vector<decltype(T()*U())> C; \ C.reserve(A.size()); \ typename vector<T>::const_iterator a = A.begin(); \ typename vector<U>::const_iterator b = B.begin(); \ while (a!=A.end()){ \ C.push_back((*a) optype (*b)); \ ++a; ++b; \ } \ return C; \ } \ BINARY_VECTOR_RETURN_OPERATOR(*); BINARY_VECTOR_RETURN_OPERATOR(+); BINARY_VECTOR_RETURN_OPERATOR(-); BINARY_VECTOR_RETURN_OPERATOR(%); So that works fine. What I want to do now is to have two modes of operation, "debug" and "not debug" which I set via a #define DEBUG command earlier. I would like to do something like this: #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ template <typename T, typename U> \ vector<decltype(T() optype U())> operator optype (const vector<T>& A, const vector<U>& B){ \ #ifdef DEBUG uint n = A.size(); \ if (n != B.size()){ \ char buf[BUFFLEN]; \ sprintf(buf, "Size mismatch in operator+(%s,%s), sizes: (%d, %d), crashing!", \ typeid(A).name(), typeid(B).name(), (int) A.size(), (int) B.size()); \ cout << buf << endl; \ throw("Size Mismatch Error"); \ } \ #endif vector<decltype(T()*U())> C; \ C.reserve(A.size()); \ typename vector<T>::const_iterator a = A.begin(); \ typename vector<U>::const_iterator b = B.begin(); \ while (a!=A.end()){ \ C.push_back((*a) optype (*b)); \ ++a; ++b; \ } \ return C; \ } \ but the compiler doesn't seem to like that. I could redefine the entire BINARY_VECTOR_RETURN_OPERATOR for each case using #ifdef DEBUG around the whole thing, but that's not very elegant. Is there a way to implement the code in the spirit of my second example? A: Ugh, try not to ever use the preprocessor for actual code. It's almost always a really bad idea. I had a go at restructuring the macro as a template function. I had some fun with the decltypes, so much so that I pulled out a traits class just to reduce the complexity of the function definition! I don't really see a way of getting rid of the macro completely, just for sanity in the declaration of the actual operator overloads. Now, however, it's just a simple pass-through to the template function operator_impl() and in that you should be able to use #ifdefs for your debug code. template <typename T, typename U, typename Op> struct op_result { typedef vector<decltype( (*((Op*)nullptr)) (*(T*)nullptr, *(U*)nullptr) ) > type; }; template <typename T, typename U, typename Op> inline typename op_result<T, U, Op>::type operator_impl(const vector<T>& A, const vector<U>& B, Op op) { op_result<T, U, Op>::type C; C.reserve(A.size()); typename vector<T>::const_iterator a = A.begin(); typename vector<U>::const_iterator b = B.begin(); while (a!=A.end()) { C.push_back(op(*a, *b)); ++a; ++b; } return C; } #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ template <class T, class U> \ inline vector<decltype( *(const T*)nullptr optype *(const U*)nullptr)> \ operator optype (const vector<T>& A, const vector<U>& B) \ { \ return operator_impl(A, B, [](const T& t, const U& u) {return t optype u;}); \ } A: You can't have a #if inside a #define, but you can have a #define inside the code controlled by a #if. For example: #ifdef DEBUG #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ first-part \ debug-code \ last-part #else #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ first-part \ last-part #endif If first-part and last-part are big enough, you might want to define macros for them. I'm not saying this is a good idea, but it does do what you were trying to do. EDIT: Thanks to @okorz001 for suggesting a cleaner alternative in a comment: #ifdef DEBUG #define DEBUG_CODE (blah, blah) #else #define DEBUG_CODE /* nothing */ #endif #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ first-part \ DEBUG_CODE; last-part Obviously the real code would use better names. A: Does an assert or BOOST_ASSERT do the job? (Got to admit I have never put an assert in a macro before - so behind the scenes this might just be reproducing your problem) So, instead of #ifdef DEBUG uint n = A.size(); if (n != B.size()){ char buf[BUFFLEN]; sprintf(buf, "Size mismatch in operator+(%s,%s), sizes: (%d, %d), crashing!", typeid(A).name(), typeid(B).name(), (int) A.size(), (int) B.size()); cout << buf << endl; throw("Size Mismatch Error"); } #endif just write BOOST_ASSERT(A.size() == B.size()); //include <boost/assert.hpp> or assert(A.size() == B.size()); //include <assert.h> (Here are some explanitary links for boost assert and assert.h) A: May be there is a way to implement the code in the spirit of your second example. You can use if() instead of #ifdef like this // May not be useful but still... #ifdef DEBUG #define DEBUG 1 #else #define DEBUG 0 #endif #define BINARY_VECTOR_RETURN_OPERATOR(optype) \ template <typename T, typename U> \ // Code within #ifdef......... \ if(DEBUG) { \ uint n = A.size(); \ // ............. \ }// end if \ // Code after #ifdef.................. \ vector<decltype(T()*U())> C;\ return C; \ } \ Please test and see if this works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass parameters to HXT arrows and how to use -<< my question is the following. I have this xml file to parse : <DATAS LANG="en"> <SCENARIO ID="19864"> <ORIGIN ID="329"> <SCENARIO_S ERR="0"></SCENARIO_S> <SCENARIO_S ERR="2"></SCENARIO_S> </ORIGIN> </SCENARIO> <ERRORS> <ERROR ID="0" LABEL="Aggregated Major Errors" /> <ERROR ID="2" LABEL="Banner error" /> </ERRORS> </DATAS> and I would like to have the following output: [("19864","329",[0,2], ["Aggregated Major Errors", "Banner error"])] that is [(Scenario ID, Origin ID, [ERR],[Errors label])] But the code below gives me : [("19864","329",[0,2],["","*** Exception: Maybe.fromJust: Nothing I would like to parse only once the XML to retrieve the "ERRORS label" and the ERR. I think my problem is in the function errToLab but no obvious solution comes to me. thanks for your help. Here is the code {-# LANGUAGE Arrows, NoMonomorphismRestriction #-} import Text.XML.HXT.Core import Data.Maybe dataURL = "test.xml" parseXML file = readDocument [ withValidate no , withRemoveWS yes -- throw away formating WS ] file atTag tag = deep (isElem >>> hasName tag) getErrLab2 = atTag "ERRORS" >>> proc l -> do error <- atTag "ERROR" -< l errID <- getAttrValue "ID" -< error desc <- getAttrValue "LABEL" -< error returnA -< (errID,desc) getErr = atTag "SCENARIO_S" >>> proc p -> do err <- getAttrValue "ERR" -< p returnA -< read err::Int getScenar2' errlab = atTag "SCENARIO" >>> proc l -> do scenarTag <- atTag "SCENARIO" -< l scenName <- getAttrValue "ID" -< l site <- atTag "ORIGIN" -< l siteName <- getAttrValue "ID" -< site errs <- listA getErr -< site errlab <- listA (errToLab errlab) -< site returnA -< (scenName,siteName,errs,errlab) getData= atTag "DATAS" >>> proc p -> do errlab <- getErrLab2 -< p datascen <- getScenar2' [errlab] -<< p returnA -< datascen errToLab errlab = atTag "SCENARIO_S" >>> proc p -> do err <- getAttrValue "ERR" -< p returnA -< chercheErr err errlab where chercheErr "0" _ = "" chercheErr err taberr = fromJust.lookup err $ taberr main = do site <- runX (parseXML dataURL >>> getData) print site A: Just feed Errors list to arrows input. Here is a slightly edited version: {-# LANGUAGE Arrows #-} import Text.XML.HXT.Core import Data.Maybe dataURL = "test.xml" parseXML file = readDocument [ withValidate no , withRemoveWS yes -- throw away formating WS ] file atTag tag = deep (isElem >>> hasName tag) getErrLab2 = atTag "ERRORS" >>> proc l -> do error <- atTag "ERROR" -< l errID <- getAttrValue "ID" -< error desc <- getAttrValue "LABEL" -< error returnA -< (errID,desc) getErr = atTag "SCENARIO_S" >>> proc p -> do err <- getAttrValue "ERR" -< p returnA -< read err::Int getScenar2' = proc (p,errlab) -> do l <- atTag "SCENARIO" -< p scenarTag <- atTag "SCENARIO" -< l scenName <- getAttrValue "ID" -< l site <- atTag "ORIGIN" -< l siteName <- getAttrValue "ID" -< site errs <- listA getErr -< site elab <- listA errToLab -< (site,errlab) returnA -< (scenName,siteName,errs,elab) getData= atTag "DATAS" >>> proc p -> do errlab <- listA getErrLab2 -< p getScenar2' -< (p, errlab) errToLab = proc (s,errlab) -> do p <- atTag "SCENARIO_S" -< s err <- getAttrValue "ERR" -< p returnA -< chercheErr err errlab where -- chercheErr "0" _ = "" chercheErr err taberr = fromJust.lookup err $ taberr main = do site <- runX (parseXML dataURL >>> getData) print site
{ "language": "en", "url": "https://stackoverflow.com/questions/7557223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Style TextAppearance.Holo not found I have been building this app for a while now and have not had any trouble with the themes until I updated to the latest platform tools today. Now it's telling me error: Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Light.Medium.Inverse'. error: Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Light.Medium'. error: Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Light.Large'. This is the part of my styles.xml that is causing the problem but, as I said, it hasn't changed in months and worked fine until today! <style name="BD.TextAppearance.Medium.Inverse" parent="@android:style/TextAppearance.Holo.Light.Medium.Inverse"> <item name="android:textColor">#FFF</item> <item name="android:textStyle">bold</item> </style> <style name="BD.TextAppearance.Medium" parent="@android:style/TextAppearance.Holo.Light.Medium"> <item name="android:textColor">#666666</item> <item name="android:textSize">16sp</item> </style> <style name="BD.TextAppearance.Large" parent="@android:style/TextAppearance.Holo.Light.Large"> <item name="android:textColor">#666666</item> <item name="android:textSize">20sp</item> </style> -= EDIT =- I started messing around with the values and it turns out that it does find these styles: <style name="BD.TextAppearance" parent="@android:style/TextAppearance"> <item name="android:textColor">#FFF</item> <item name="android:textStyle">bold</item> </style> <style name="BD.TextAppearance.Medium.Inverse" parent="@android:style/TextAppearance.Medium.Inverse"> <item name="android:textColor">#FFF</item> <item name="android:textStyle">bold</item> </style> But not these: <style name="BD.TextAppearance" parent="@android:style/TextAppearance.Holo"> <item name="android:textColor">#FFF</item> <item name="android:textStyle">bold</item> </style> <style name="BD.TextAppearance.Medium.Inverse" parent="@android:style/TextAppearance.Light.Medium.Inverse"> <item name="android:textColor">#FFF</item> <item name="android:textStyle">bold</item> </style> A: I still don't know why this happened but I have found a way around it. I copied the styles.xml file from the Android SDK and pasted it into my project and took out all of the styles that I wasn't using. The I changed all of the 'parent' declarations to include the '@android:' prefix and added 'android:' after the '?' for all attributes. This allows it to compile and run. But like I said I would really like to find out why it broke in the first place! A: error: Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Light.Medium.Inverse'. I too face the Same problem what i did is that just i removed the parent="@android:style/TextAppearance.Holo.Light.Medium.Inverse" attribute. It will works check it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Webinject - Parse content of a cookie I have a Webinject testcase that needs to set an additional header with the content of a previously received cookie. My first testcase logs into a web application and gets a token for identification. Parts of the content of the cookie need to be set as additional header. How can I achieve this? The Cookie which will be set looks like this: login=user%40myurl.com; __utma=1.748102029.1314655544.1314657537.1316179965.3; __utmz=1.1316179965.3.2.utmcsr=myurl.com|utmccn=(referral)|utmcmd=referral|utmcct=/subpage; __utma=1.748102029.1314655544.1314657537.1316179965.3; __utmz=1.1316179965.3.2.utmcsr=murul.com|utmccn=(referral)|utmcmd=referral|utmcct=/subpage; JSESSIONID=E976943F6BA0D6FDCC7567BAA5988F77; __utmb=1.3.10.1317046713; __utmc=1; token=44962ede5de74d45b1162a935ee18fbf; identifier=""; login=user%40myurl.com The testcases look like the following. <case id="2" description1="Logging into Login Page" method="post" url="http://myurl.com" postbody="name=user%40myurl.com&password=12345&fragment=}" verifynegative="^.*The user name and/or password is incorrect!.*$" verifyresponsecode="302" errormessage="Could not login (wrong credentials?)" parseresponse="token=|;" logresponse="yes" logrequest="yes" /> This is where I want to parse the cookie but I think it is only parsing the response. <case id="3" description1="Open Subpage" method="get" url="http://myurl.com/subpage" addheader="x-subpage-id:{PARSEDRESULT}" verifyresponsecode="200" verifypositive="^.*Title: foo bar.*$" errormessage="Unable to open View" logresponse="yes" logrequest="yes" /> This is where I want to add the addition header. It must be the parts from the cookie I want to parse. A: enable http.log, and look at the result from your first test; you should see a 'Set-Cookie:' line. This is visible to the parser, i.e. it gets considered. Like so: Set-Cookie: sessionid=5c028a746958eef2126dd397c20449a4; expires=Sat, 21-Jul-2012 15:40:03 GMT; httponly; Max-Age=1209600; Path=/ The cookie should be more informative in your case. Then, parseresponse allows to use regular expressions, so if you can make out the delimiter around what you need, you are settled. The webinject mailing list answers questions in a more timely manner. https://groups.google.com/forum/?fromgroups#!forum/webinject
{ "language": "en", "url": "https://stackoverflow.com/questions/7557226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: example to build groovy json and with groovy builder needed empData1.groovy def empMap[] = [1:2, 2:2, 3:[1:2,3:3,4:890,A:B], //Map inside Map 4:4, 6:7 ] empData2.groovy def empMap1[] = [91:21, 92:22, 93:[81:82,83:3,84:890,A:B], ////Map inside Map 94:4, 96:7 ] emp3.groovy - - Q1: how can i build a builder for like empMap/empMap1 - Q2: if i want to do in emp3.grrovy like empData1.include(empMap1) map data copies to map2 is the same thing is achievavle vis groovy json how ? is this possible to do def json = new JsonBuilder() def result = json { 1 2 //build a map with 1 as key 2 value without sinlge quaote is this possible 3 33 //build a map with 3 as key 33 value without sinlge quaote is this possible } println result **Answer def json = new JsonBuilder() def result = json { '1' '2' '3' '33' } println result My output [1:2, 3:33] but i try to build something like this def json = new JsonBuilder() def result = json { '1' '2' '3' '33' '4' ( '1' '3' '4' '5' ) } println result it gives me compilation error any clue to resolve it A: Anish, I suggest you try this instead to make it compile: import groovy.json.JsonBuilder def json = new JsonBuilder() def result = json { '1' '2' '3' '33' '4' { '1' '3' '4' '5' } } println json
{ "language": "en", "url": "https://stackoverflow.com/questions/7557227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R.string.value showing up as a number For the below code I intended to get the system date and display it as per the formatting of the current locale, it's just that for the R.string.date. In emulator it always shows up as a long number (something like 821302314) instead of "Date: " which I has already externalized in the string.xml. Can anyone help to have a look why this is so? final TextView mTimeText = (TextView)findViewById(R.id.mTimeText); //get system date Date date = new Date(); java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext()); mTimeText.setText(R.string.date + " " + dateFormat.format(date)); layout.xml <TextView android:id="@+id/mTimeText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/date" /> strings.xml <string name="date">Date:</string> A: Yes, you will get the ID of the String if you use R.string.date. As stated in the docs You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string. Example: this.getString(R.string.date); Read about it here: getString A: To get string value from xml, you should call this.getString(R.id.nameOfString). In your case this would be mTimeText.setText(this.getString(R.string.date) + " " + dateFormat.format(date)); A: R.string.date is indeed an int, you're missing the call to getText() or getString(): mTimeText.setText(getText(R.string.date) + " " + dateFormat.format(date)); Even better, don't build the string in your code, but use a template with getString(int resId, Object... formatArgs): mTimeText.setText(getString(R.string.date, dateFormat.format(date))); and in your string.xml: <string name="date">Date: %s</string> A: To override all "R.string.*" to "getString(R.string.)"* i wrote a little regex. This regex also ignores the strings who already have a "getString" in front. ((?!getString\() R\.string\.[a-zA-Z1-9_]+) You just have to press Strg+Shift+R in Android Studio to open the replace terminal and insert the regex above as "Find" and as "Replacement" the regex below. getString\( $1 \) Don't forget to set "regular expression" checkbox. For me this worked perfectly. But the "Find Regex" got one problem it only finds R.string when it starts with a whitespace. I don't know how to solve this because if i delete the whitespace ill find also the R.string that allready have the "getString". May some can help to improve the regex or has a better way to achieve this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: get xml root attribute as String in JSP Anyone have a quick and simple way to get an attribute from the root node of an xml document as a String? I want to then be able to use this string to run through an if statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select * from n tables Is there a way to write a query like: select * from <some number of tables> ...where the number of tables is unknown? I would like to avoid using dynamic SQL. I would like to select all rows from all the tables that (the tables) have a specific prefix: select * from t1 select * from t2 select * from t3 ... I don't know how many t(n) might there be (might be 1, might be 20, etc.) The t table column structures are not the same. Some of them have 2 columns, some of them 3 or 4. It would not be hard using dynamic SQL, but I wanted to know if there is a way to do this using something like sys.tables. UPDATE Basic database design explained N companies will register/log in to my application Each company will set up ONE table with x columns (x depends on the type of business the company is, can be different, for example think of two companies: one is a Carpenter and the other is a Newspaper) Each company will fill his own table using an API built by me What I do with the data: I have a "processor", that will be SQL or C# or whatever. If there is at least one row for one company, I will generate a record in a COMMON table. So the final results will be all in one table. Anybody from any of those N companies will log in and will see the COMMON table filtered for his own company. A: to list ALL tables you could try : EXEC sp_msforeachtable 'SELECT * FROM ?' you can programmability include/exclude table by doing something like: EXEC sp_msforeachtable 'IF LEFT(''?'',9)=''[dbo].[xy'' BEGIN SELECT * FROM ? END ELSE PRINT LEFT(''?'',9)' A: There would be no way to do that without Dynamic SQL. And having different table structures does not help that at all. Update There would be no easy way to return the desired output in one single result set (result set would have at least the same # of columns of the table with most columns and don't even get me started on data types compatibility). However, you should check @KM.'s answer. That will bring multiple result sets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Migrate a repo not always using the trunk/branches/tags structure from SVN to GIT I'm looking for a way to permanently (i.e. no git-svn will be used after the import and the repo will be cloned again to get rid of all git-svn remainders) migrate one of my SVN repositories to git. Usually this would be an easy thing - just doing the steps explained at http://www.jonmaddox.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/. However, in the SVN repository I switched to the trunk/branches/tags structure after some time, so about half of the ~2000 commits are working with the actual trunk being in / while the other half have it in /trunk/ (i.e. there's one big commit moving everything) so neither using -s nor not using it when performing the git svn initialization will work properly. I'm now looking for a way to import the repository to git properly, i.e. preserving the branch information (no tags, I never created any) while not messing up old commits. In case that's not possible I'd like to know if there's a way to rewrite the old commits to change the repo so it uses the trunk/branches/tags structure - then I could simply use -s in git-svn. A: TL,DR: It is possible to fix a messy up repository like the one described in the question when some manual work is acceptable. The easiest way is doing it with the SVN dump file and then simply importing it using git-svn with the stdlayout option. I managed to do it by rewriting the svndump of the repository to include the proper structure from the beginning: svnadmin dump orig/ --incremental > repo.svndump Then I used a small inline Perl script to change the folders: perl -pe 's/^Node-path: (?!trunk|branches|tags)(.+)$/Node-path: trunk\/$1/g' repo.svndump > repo2.svndump Since the dump was now invalid - the trunk folder needed to be created in r0 and the commit moving everything from / to /trunk needed to be obliterated - I edited the dump file manually (luckily all metadata are plaintext) and added the following at the beginning of the changes for r0: Node-path: trunk Node-kind: dir Node-action: add Prop-content-length: 10 Content-length: 10 PROPS-END In the commit moving all the files I removed all actions and added the following to create the branches folder (likewise for the tags folder if I had used it) Node-path: branches Node-kind: dir Node-action: add Prop-content-length: 10 Content-length: 10 PROPS-END The edited dumpfile could now be loaded using svnadmin load, giving me a repository that could be imported by git-svn without any issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Running shell script command after executing an application I have written a shell script to execute a series of commands. One of the commands in the shell script is to launch an application. However, I do not know how to continue running the shell script after I have launched the application. For example: ... cp somedir/somefile . ./application rm -rf somefile Once I launched the application with "./application" I am no longer able to continue running the "rm -rf somefile" command, but I really need to remove the file from the directory. Anyone have any ideas how to compete running the "rm -rf" command after launching the application? Thanks A: As pointed out by others, you can background the application (man bash 'job control', e.g.). Also, you can use the wait builtin to explicitely await the background jobs later: ./application & echo doing some more work wait # wait for background jobs to complete echo application has finished You should really read the man pages and bash help for more details, as always: * *http://unixhelp.ed.ac.uk/CGI/man-cgi?sh *http://www.gnu.org/s/bash/manual/bash.html#Job-Control-Builtins A: Start the application in the background, this way the shell is not going to wait for it to terminate and will execute the consequent commands right after starting the application: ./application & In the meantime, you can check the background jobs by using the jobs command and wait on them via wait and their ID. For example: $ sleep 100 & [1] 2098 $ jobs [1]+ Running sleep 100 & $ wait %1 A: You need to start the command in the background using '&' and maybe even nohup. nohup ./application > log.out 2>&1 A: put the started process to background: ./application &
{ "language": "en", "url": "https://stackoverflow.com/questions/7557237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jsoncpp formatting problems I'm using jsoncpp and I'm having a problem with how the json messages are formatted when they are written using one of the Writers. For example: root["name"] = "monkey"; std::cout << writer.write(root) << "\n"; Gives me something formatted like this { "name" : "monkey" } While I actually want: {"name":"monkey"} I've looked at the documentation and there are mentions of setIndentLength() but they don't appear in the source files, so maybe they are deprecated or something. Anyway anyone knows how to do this? A: As an extension of cdunn2001's answer, there is no need to re-write default settings (.settings_). You can just override 'indentation' value of StreamWriterBuilder builder: Json::Value json = ... Json::StreamWriterBuilder builder; builder["commentStyle"] = "None"; builder["indentation"] = ""; //The JSON document is written in a single line std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); writer->write(json, &std::cout); A: If you use Jsoncpp version 1.1, you can use Json::FastWriter instead of Json::StyledWriter or Json::Writer : The JSON document is written in a single line. It is not intended for 'human' consumption, but may be usefull to support feature such as RPC where bandwith is limited. A: FastWriter, StyledWriter, StyledStreamWriter, and Writer are deprecated. Use StreamWriterBuilder, which creates a StreamWriter with a slightly different API. Use it this way: Json::StreamWriterBuilder builder; builder.settings_["indentation"] = ""; std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); writer->write(root, &std::cout);
{ "language": "en", "url": "https://stackoverflow.com/questions/7557258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: convert images from python to c# - Image sizes are way too different I am trying to convert images from python to c#, the images which python has created are much smaller in size and images which .net is creating are much larger in size. I do not want to reduce the quality of images, not sure why it is happening. here is the python code. if img.mode != "RGB": img = img.convert("RGB") img = img.resize((width,height), Image.ANTIALIAS) resampled_image_name = os.path.splitext(resampled_image_name)[0] + "." + format img.save(resampled_image_name) and this is my c# code Bitmap bitmap = new Bitmap(width, height); using (Graphics gr = Graphics.FromImage(bitmap)) { gr.DrawImage(srcImage, new Rectangle(0, 0, width, height)); } FileInfo info = new FileInfo(resampledImageName); resampledImageName = resampledImageName.Replace(info.Extension, "." + format); bitmap.Save(@resampledImageName);
{ "language": "en", "url": "https://stackoverflow.com/questions/7557263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent dialog dismissal on screen rotation in Android I am trying to prevent dialogs built with Alert builder from being dismissed when the Activity is restarted. If I overload the onConfigurationChanged method I can successfully do this and reset the layout to correct orientation but I lose sticky text feature of edittext. So in solving the dialog problem I have created this edittext problem. If I save the strings from the edittext and reassign them in the onCofiguration change they still seem to default to initial value not what was entered before rotation. Even if I force an invalidate does seem to update them. I really need to solve either the dialog problem or the edittext problem. Thanks for the help. A: If you're changing the layout on orientation change I wouldn't put android:configChanges="orientation" in your manifest because you're recreating the views anyway. Save the current state of your activity (like text entered, shown dialog, data displayed etc.) using these methods: @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } That way the activity goes through onCreate again and afterwards calls the onRestoreInstanceState method where you can set your EditText value again. If you want to store more complex Objects you can use @Override public Object onRetainNonConfigurationInstance() { } Here you can store any object and in onCreate you just have to call getLastNonConfigurationInstance(); to get the Object. A: // Prevent dialog dismiss when orientation changes private static void doKeepDialog(Dialog dialog){ WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.WRAP_CONTENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; dialog.getWindow().setAttributes(lp); } public static void doLogout(final Context context){ final AlertDialog dialog = new AlertDialog.Builder(context) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(R.string.titlelogout) .setMessage(R.string.logoutconfirm) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ... } }) .setNegativeButton("No", null) .show(); doKeepDialog(dialog); } A: Just add android:configChanges="orientation" with your activity element in AndroidManifest.xml Example: <activity android:name=".YourActivity" android:configChanges="orientation" android:label="@string/app_name"></activity> A: The best way to avoid this problem nowadays is by using a DialogFragment. Create a new class which extends DialogFragment. Override onCreateDialog and return your old Dialog or an AlertDialog. Then you can show it with DialogFragment.show(fragmentManager, tag). Here's an example with a Listener: public class MyDialogFragment extends DialogFragment { public interface YesNoListener { void onYes(); void onNo(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof YesNoListener)) { throw new ClassCastException(activity.toString() + " must implement YesNoListener"); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setTitle(R.string.dialog_my_title) .setMessage(R.string.dialog_my_message) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((YesNoListener) getActivity()).onYes(); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((YesNoListener) getActivity()).onNo(); } }) .create(); } } And in the Activity you call: new MyDialogFragment().show(getSupportFragmentManager(), "tag"); // or getFragmentManager() in API 11+ This answer helps explain these other three questions (and their answers): * *Android Best way of avoid Dialogs to dismiss after a device rotation *Android DialogFragment vs Dialog *How can I show a DialogFragment using compatibility package? A: A very easy approach is to create the dialogs from the method onCreateDialog() (see note below). You show them through showDialog(). This way, Android handles the rotation for you and you do not have to call dismiss() in onPause() to avoid a WindowLeak and then you neither have to restore the dialog. From the docs: Show a dialog managed by this activity. A call to onCreateDialog(int, Bundle) will be made with the same id the first time this is called for a given id. From thereafter, the dialog will be automatically saved and restored. See Android docs showDialog() for more info. Hope it helps somebody! Note: If using AlertDialog.Builder, do not call show() from onCreateDialog(), call create() instead. If using ProgressDialog, just create the object, set the parameters you need and return it. In conclusion, show() inside onCreateDialog() causes problems, just create de Dialog instance and return it. This should work! (I have experienced issues using showDialog() from onCreate() -actually not showing the dialog-, but if you use it in onResume() or in a listener callback it works well). A: This question was answered a long time ago. Yet this is non-hacky and simple solution I use for myself. I did this helper class for myself, so you can use it in your application too. Usage is: PersistentDialogFragment.newInstance( getBaseContext(), RC_REQUEST_CODE, R.string.message_text, R.string.positive_btn_text, R.string.negative_btn_text) .show(getSupportFragmentManager(), PersistentDialogFragment.TAG); Or PersistentDialogFragment.newInstance( getBaseContext(), RC_EXPLAIN_LOCATION, "Dialog title", "Dialog Message", "Positive Button", "Negative Button", false) .show(getSupportFragmentManager(), PersistentDialogFragment.TAG); public class ExampleActivity extends Activity implements PersistentDialogListener{ @Override void onDialogPositiveClicked(int requestCode) { switch(requestCode) { case RC_REQUEST_CODE: break; } } @Override void onDialogNegativeClicked(int requestCode) { switch(requestCode) { case RC_REQUEST_CODE: break; } } } A: Definitely, the best approach is by using DialogFragment. Here is mine solution of wrapper class that helps to prevent different dialogs from being dismissed within one Fragment (or Activity with small refactoring). Also, it helps to avoid massive code refactoring if for some reasons there are a lot of AlertDialogs scattered among the code with slight differences between them in terms of actions, appearance or something else. public class DialogWrapper extends DialogFragment { private static final String ARG_DIALOG_ID = "ARG_DIALOG_ID"; private int mDialogId; /** * Display dialog fragment. * @param invoker The fragment which will serve as {@link AlertDialog} alert dialog provider * @param dialogId The ID of dialog that should be shown */ public static <T extends Fragment & DialogProvider> void show(T invoker, int dialogId) { Bundle args = new Bundle(); args.putInt(ARG_DIALOG_ID, dialogId); DialogWrapper dialogWrapper = new DialogWrapper(); dialogWrapper.setArguments(args); dialogWrapper.setTargetFragment(invoker, 0); dialogWrapper.show(invoker.getActivity().getSupportFragmentManager(), null); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDialogId = getArguments().getInt(ARG_DIALOG_ID); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return getDialogProvider().getDialog(mDialogId); } private DialogProvider getDialogProvider() { return (DialogProvider) getTargetFragment(); } public interface DialogProvider { Dialog getDialog(int dialogId); } } When it comes to Activity you can invoke getContext() inside onCreateDialog(), cast it to the DialogProvider interface and request a specific dialog by mDialogId. All logic to dealing with a target fragment should be deleted. Usage from fragment: public class MainFragment extends Fragment implements DialogWrapper.DialogProvider { private static final int ID_CONFIRMATION_DIALOG = 0; @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { Button btnHello = (Button) view.findViewById(R.id.btnConfirm); btnHello.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogWrapper.show(MainFragment.this, ID_CONFIRMATION_DIALOG); } }); } @Override public Dialog getDialog(int dialogId) { switch (dialogId) { case ID_CONFIRMATION_DIALOG: return createConfirmationDialog(); //Your AlertDialog default: throw new IllegalArgumentException("Unknown dialog id: " + dialogId); } } } You can read the complete article on my blog How to prevent Dialog being dismissed? and play with the source code. A: It seems that this is still an issue, even when "doing everything right" and using DialogFragment etc. There is a thread on Google Issue Tracker which claims that it is due to an old dismiss message being left in the message queue. The provided workaround is quite simple: @Override public void onDestroyView() { /* Bugfix: https://issuetracker.google.com/issues/36929400 */ if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } Incredible that this is still needed 7 years after that issue was first reported. A: You can combine the Dialog's onSave/onRestore methods with the Activity's onSave/onRestore methods to keep the state of the Dialog. Note: This method works for those "simple" Dialogs, such as displaying an alert message. It won't reproduce the contents of a WebView embedded in a Dialog. If you really want to prevent a complex dialog from dismissal during rotation, try Chung IW's method. @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); myDialog.onRestoreInstanceState(savedInstanceState.getBundle("DIALOG")); // Put your codes to retrieve the EditText contents and // assign them to the EditText here. } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Put your codes to save the EditText contents and put them // to the outState Bundle here. outState.putBundle("DIALOG", myDialog.onSaveInstanceState()); } A: I had a similar problem: when the screen orientation changed, the dialog's onDismiss listener was called even though the user didn't dismiss the dialog. I was able to work around this by instead using the onCancel listener, which triggered both when the user pressed the back button and when the user touched outside of the dialog. A: In case nothing helps, and you need a solution that works, you can go on the safe side, and each time you open a dialog save its basic info to the activity ViewModel (and remove it from this list when you dismiss dialog). This basic info could be dialog type and some id (the information you need in order to open this dialog). This ViewModel is not destroyed during changes of Activity lifecycle. Let's say user opens a dialog to leave a reference to a restaurant. So dialog type would be LeaveReferenceDialog and the id would be the restaurant id. When opening this dialog, you save this information in an Object that you can call DialogInfo, and add this object to the ViewModel of the Activity. This information will allow you to reopen the dialog when the activity onResume() is being called: // On resume in Activity override fun onResume() { super.onResume() // Restore dialogs that were open before activity went to background restoreDialogs() } Which calls: fun restoreDialogs() { mainActivityViewModel.setIsRestoringDialogs(true) // lock list in view model for (dialogInfo in mainActivityViewModel.openDialogs) openDialog(dialogInfo) mainActivityViewModel.setIsRestoringDialogs(false) // open lock } When IsRestoringDialogs in ViewModel is set to true, dialog info will not be added to the list in view model, and it's important because we're now restoring dialogs which are already in that list. Otherwise, changing the list while using it would cause an exception. So: // Create new dialog override fun openLeaveReferenceDialog(restaurantId: String) { var dialog = LeaveReferenceDialog() // Add id to dialog in bundle val bundle = Bundle() bundle.putString(Constants.RESTAURANT_ID, restaurantId) dialog.arguments = bundle dialog.show(supportFragmentManager, "") // Add dialog info to list of open dialogs addOpenDialogInfo(DialogInfo(LEAVE_REFERENCE_DIALOG, restaurantId)) } Then remove dialog info when dismissing it: // Dismiss dialog override fun dismissLeaveReferenceDialog(Dialog dialog, id: String) { if (dialog?.isAdded()){ dialog.dismiss() mainActivityViewModel.removeOpenDialog(LEAVE_REFERENCE_DIALOG, id) } } And in the ViewModel of the Activity: fun addOpenDialogInfo(dialogInfo: DialogInfo){ if (!isRestoringDialogs){ val dialogWasInList = removeOpenDialog(dialogInfo.type, dialogInfo.id) openDialogs.add(dialogInfo) } } fun removeOpenDialog(type: Int, id: String) { if (!isRestoringDialogs) for (dialogInfo in openDialogs) if (dialogInfo.type == type && dialogInfo.id == id) openDialogs.remove(dialogInfo) } You actually reopen all the dialogs that were open before, in the same order. But how do they retain their information? Each dialog has a ViewModel of its own, which is also not destroyed during the activity lifecycle. So when you open the dialog, you get the ViewModel and init the UI using this ViewModel of the dialog as always. A: Just use ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize and app will know how to handle rotation and screen size. A: Yes, I agree with the solution of using DialogFragment given by @Brais Gabin, just want to suggest some changes to the solution given by him. While defining our custom class that extends DialogFragment, we require some interfaces to manage the actions ultimately by the activity or the fragment that has invoked the dialog. But setting these listener interfaces in the onAttach(Context context) method may sometimes cause ClassCastException that may crash the app. So to avoid this exception, we can create a method to set the listener interfaces and call just it after creating the object of the dialog fragment. Here is a sample code that could help you understand more- AlertRetryDialog.class public class AlertRetryDialog extends DialogFragment { public interface Listener{ void onRetry(); } Listener listener; public void setListener(Listener listener) { this.listener=listener; } @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { AlertDialog.Builder builder=new AlertDialog.Builder(getActivity()); builder.setMessage("Please Check Your Network Connection").setPositiveButton("Retry", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Screen rotation will cause the listener to be null //Always do a null check of your interface listener before calling its method if(listener!=null&&listener instanceof HomeFragment) listener.onRetry(); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return builder.create(); } } And in the Activity or in the Fragment you call- AlertRetryDialog alertRetryDialog = new AlertRetryDialog(); alertRetryDialog.setListener(HomeFragment.this); alertRetryDialog.show(getFragmentManager(), "tag"); And implement the methods of your listener interface in your Activity or the Fragment- public class YourActivity or YourFragment implements AlertRetryDialog.Listener{ //here's my listener interface's method @Override public void onRetry() { //your code for action } } Always make sure that you do a null check of the listener interfaces before calling any of its methods to prevent NullPointerException (Screen rotation will cause the listener interfaces to be null). Please do let me know if you find this answer helpful. Thank You.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "102" }
Q: Tutorial or Guide for Scripting Xcode Build Phases I would like to add some files to the Compile Sources build phase using a script in Xcode, which pulls from some folder references. I haven't been able to find much documentation so far. * *Where is the general documentation (or a good tutorial) for scripting Xcode build phases? *How can I add files to the Compile Sources phase? *How can I discover information about the project and the folder references within it? *Are there any special considerations if I want to script in Ruby or Python vs. bash scripting? A: To add files to the Compile Sources build phase using a script, you will need to manipulate your project's project.pbxproj file programmatically. Generally speaking, you would accomplish this by parsing the project.pbxproj file into an in-memory data structure, manipulating that data structure through a programmatic interface, and then writing the data structure out to a new project.pbxproj file. There are several projects out there that could potentially help you do this, I haven't tried any of them: * *https://github.com/owlforestry/pbxproject *http://github.com/gonzoua/pbxproj/ *https://github.com/facebook/three20/blob/master/src/scripts/Pbxproj.py *http://code.google.com/p/xcodeutils *https://github.com/appcelerator/titanium_mobile/blob/master/support/iphone/pbxproj.py And here is a series of blog posts with great general info on the contents and format of XCode project.pbxproj files. * *http://danwright.info/blog/2010/10/xcode-pbxproject-files/ *http://danwright.info/blog/2010/10/xcode-pbxproject-files-2/ *http://danwright.info/blog/2010/10/xcode-pbxproject-files-3/ Finally, it may be worth noting that for very simple manipulations, particularly if you aren't concerned about the cosmetics of your project.pbxproj file getting messed up, you can follow the suggestion over at this Stack Overflow answer to parse the project.pbxproj file on the command line like so: plutil -convert xml1 -o - myproj.xcodeproj/project.pbxproj Happy parsing!
{ "language": "en", "url": "https://stackoverflow.com/questions/7557273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What should I do when a standard is made private and only accessible for a fee? I have some software which we added an open common file format (.iwb) to. The government organisation that initiated that work has been cut in the cutbacks. Now a not for profit organisation has taken up the mantle, however its going to cost and once you pay you are not allowed to reveal the "materials" you gain. http://www.imsglobal.org/iwbcff/jointheIWBCFFIalliance.cfm I understand people need to be paid but the whole not sharing thing makes it feel like its going against what a standard is meant for. What's a good strategy: * *Pay up and shut up (there might be plenty of closed standards that work in this way) *Fork the standard to an organisation that will not require people to pay to read it *Drop the file format *Stay behind the curve and reverse engineer the files A: Any standard that is not freely accessible is no standard at all but is instead a proprietary format. I'd say either: * *petition them to open the standard up *Drop your support for it (and tell your customers why you have to) *Fork an earlier open version and create a free version of the standard Paying for access to a standard sounds like a horrible idea because: * *It encourages this behavior *It's likely to just be wasted money because others won't want to pay either, and a standard used by no one is not a standard. A: * *Publish the last version you had access to. *Site that you support that version of the standard.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can an element of a array know who is the owner of that array in JS? This probably seems a little bit strange but let me elaborate... I have an instance of an object (z is the instance of Bla in this case), and it has a list of other objects (Bla2's), something like this: Bla = function() { this.array = [new Bla2(), new Bla2(), new Bla2()]; this.x = 4; } Bla2 = function() { this.y = MYOWNER.x; //in this case, z is the owner } z = new Bla(); A: By default no elements don't know which array owns them. Primarily because it's very easy for an element to be contained in multiple arrays. Consider the following var x = new Bla2(); var array1 = [x]; var array2 = [x]; In this case x is in 2 arrays hence having a single owner property will be inherently incorrect. It is possible to manually create this relationship if a specific circumstance warrants it though. Consider the following this.array = [new Bla2(), new Bla2(), new Bla2()]; for (var i = 0; i < this.array.length; i++) { this.array[i].owner = this.array; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I easily package libraries needed to analyze a core dump (i.e. packcore) The version of GDB that is available on HPUX has a command called "packcore", which creates a tarball containing the core dump, the executable and all libraries. I've found this extremely useful when trying to debug core dumps on a different machine. Is there a similar command in the standard version of GDB that I might find on a Linux machine? I'm looking for an easy command that someone that isn't necessarily a developer can run when things go bad on a production machine. A: The core file includes the command from which it was generated. Ideally this will include the full path to the appropriate executable. For example: $ file core.29529 core.29529: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from '/bin/sleep 60' Running ldd on an ELF binary will show what libraries it depends on: $ ldd /bin/sleep linux-vdso.so.1 => (0x00007fff1d3ff000) libc.so.6 => /lib64/libc.so.6 (0x0000003d3ce00000) /lib64/ld-linux-x86-64.so.2 (0x0000003d3ca00000) So now I know the executable and the libraries needed to analyze the core dump. The tricky part here is extracting the executable path from the core file. There doesn't appear to be a good tool for reading this directly. The data is encoded in a prpsinfo structure (from /usr/include/sys/procfs.h), and you can find the location size of the data using readelf: $ readelf -n core.29529 Notes at offset 0x00000468 with length 0x00000558: Owner Data size Description CORE 0x00000150 NT_PRSTATUS (prstatus structure) CORE 0x00000088 NT_PRPSINFO (prpsinfo structure) CORE 0x00000130 NT_AUXV (auxiliary vector) CORE 0x00000200 NT_FPREGSET (floating point registers) ...so one could in theory write a code snippet to extract the command line from this structure and print it out in a way that would make this whole process easier to automate. You could, of course, just parse the output of file: $ file core.29529 | sed "s/.*from '\([^']*\)'/\1/" /bin/sleep 60 So that's all the parts. Here's a starting point for putting it all together: #!/bin/sh core=$1 exe=$(file $core | sed "s/.*from '\([^']*\)'/\1/" | awk '{print $1}') libs=$( ldd $exe | awk ' /=> \// {print $3} ! /=>/ {print $1} ' ) cat <<EOF | tar -cah -T- -f $1-all.tar.xz $libs $exe EOF For my example, if I name this script packcore and run it on the core file from the sleep command, I get this: $ packcore core.29529 tar: Removing leading `/' from member names $ tar -c -f core.29529-all.tar.xz core.29529 lib64/libc.so.6 lib64/ld-linux-x86-64.so.2 bin/sleep As it stands this script is pretty fragile; I've made lots of assumptions about the output from ldd based on only this sample output. A: Here's a script that does the necessary steps (tested only on RHEL5, but might work elsewhere too): #!/bin/sh # # Take a core dump and create a tarball of all of the binaries and libraries # that are needed to debug it. # include_core=1 keep_workdir=0 usage() { argv0="$1" retval="$2" errmsg="$3" if [ ! -z "$errmsg" ] ; then echo "ERROR: $errmsg" 1>&2 fi cat <<EOF Usage: $argv0 [-k] [-x] <corefile> Parse a core dump and create a tarball with all binaries and libraries needed to be able to debug the core dump. Creates <corefile>.tgz -k - Keep temporary working directory -x - Exclude the core dump from the generated tarball EOF exit $retval } while [ $# -gt 0 ] ; do case "$1" in -k) keep_workdir=1 ;; -x) include_core=0 ;; -h|--help) usage "$0" 0 ;; -*) usage "$0" 1 "Unknown command line arguments: $*" ;; *) break ;; esac shift done COREFILE="$1" if [ ! -e "$COREFILE" ] ; then usage "$0" 1 "core dump '$COREFILE' doesn't exist." fi case "$(file "$COREFILE")" in *"core file"*) break ;; *) usage "$0" 1 "per the 'file' command, core dump '$COREFILE' is not a core dump." ;; esac cmdname=$(file "$COREFILE" | sed -e"s/.*from '\(.*\)'/\1/") echo "Command name from core file: $cmdname" fullpath=$(which "$cmdname") if [ ! -x "$fullpath" ] ; then usage "$0" 1 "unable to find command '$cmdname'" fi echo "Full path to executable: $fullpath" mkdir "${COREFILE}.pack" gdb --eval-command="quit" "${fullpath}" ${COREFILE} 2>&1 | \ grep "Reading symbols" | \ sed -e's/Reading symbols from //' -e's/\.\.\..*//' | \ tar --files-from=- -cf - | (cd "${COREFILE}.pack" && tar xf -) if [ $include_core -eq 1 ] ; then cp "${COREFILE}" "${COREFILE}.pack" fi tar czf "${COREFILE}.pack.tgz" "${COREFILE}.pack" if [ $keep_workdir -eq 0 ] ; then rm -r "${COREFILE}.pack" fi echo "Done, created ${COREFILE}.path.tgz" A: I've written shell script for this. It uses ideas from the answers above and adds some usage information and additional commands. In future I'll possibly add command for quick debugging in docker container with gdb.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Building subscription based application with Ruby on Rails I am planning to write a subscription based application which will allow users to do the following: * *Subscribe/Sign-up to a plan (will select from multiple plans available) *Will use subscription based billing solution e.g. Recurly, Chargify. *Each client/user will see its own data *Will have a REST API *For now the plan is to have a shared database with multiple clients/users; but in future may need to scale to multi-tenant architecture. I was wondering if there's already such an application available an open-source example. Any comments, reference to books is really appreciated. Technologies I plan to use: Ruby on Rails, MySQL. One of my primary requirement is to build a cost efficient solution. I am not sure how the Force platform can help me. Any comments on Sales Force platform would be of great help. Thanks A: This book can help you http://www.amazon.com/Service-Oriented-Design-Rails-Addison-Wesley-Professional/dp/0321659368 A: The SaaS Rails Kit (not free, and authored by me, so I'm obviously biased) would be a good starting point for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: django queryset filter question I have a model I want to filter with a search term, which is usually a name. However in my database first_name and last_name are two separate fields. e.g. search_term = 'Will Sm' db_persons record: first_name = 'Will', last_name = 'Smith' the search term would be able to retrieve this record. How can I achieve that? db_persons.objects.filter(__?__) UPDATE: Looking for a way to concatenate fields and querying the concatenated result without raw sql A: If you want to search in first AND lastname you can simply use: db_persons.objects.filter(first_name='Will', last_name='Smith') Use Q objects if you want to search in first_name OR last_name: from django.db.models.query_utils import Q db_persons.objects.filter(Q(first_name='will') | Q(last_name='will')) Update according comment: A simple solution could look like this: search_string = 'will smith' query_list = search_string.split() db_persons.objects.filter(Q(first_name__in=query_list) | Q(last_name__in=query_list)) If you use mysql, you could use search. A: A simple solution will be to add another field complete_name on your model. On save you will update this field by concatenate first_name and last_name fields without any space (you need to strip all spaces from the concatenation result). Then you will do your query on this field with the search_term but with spaces also stripped. Simple example to give you the general idea: class Person(models.Model): first_name = CharField(...) last_name = CharField(...) complete_name = CharField(...) def save(self, *args, **kwargs): complete_name = '%s%s' % (self.first_name, self.last_name) self.complete_name = complete_name.replace(' ', '') super(Person, self).save(*args, **kwargs) results = Person.objects.filter(complete_name__icontains=search_term.replace(' ', ''))
{ "language": "en", "url": "https://stackoverflow.com/questions/7557288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MSDOS command(s) to copy files matching pattern in directory structure to local directory I have a job that periodically runs and archives files into a folder structure that looks like this: ArchiveFolder TimestampFolder JobnameFolder job<timestamp>.xml For a given job, I'd like to collect all xml files in the archive folder into a flat directory (no subdirectories, just all the files) without having to drill down into each one, examine for the proper job, then copy the file. It seems there should be a fairly straigtforward way of doing this. Any suggestions? EDIT: I guess I wasn't clear here. The TimeStampFolder will have a name of something like 2011-07-24, the JobnameFolder will have a name like FooFeed or BarFeed, and the job file will have a name like job2011-07-24.xml. There are hundreds to thousands of TimeStampFolders, and each one may have one or more job folders in it. Given a specific job name, I want to collect all the files in all the directories that match that job type, and dump them into the local folder, with no subdirectories. A: @ECHO OFF FOR /R %%v IN (job*.xml) DO COPY "%%v" c:\out\ A: EDIT1: SET JOB=JobName SET OF=OutputFolder START /wait NET USE Z: "\\ServerName\Sharename\ArchiveFolder" password password_here /USER:domainname\username /P:NO PUSHD Z:\ FOR /F "USEBACKQ tokens=*" %%A IN (`DIR /b /a:d /s ^| FIND /I "%JOB%"`) DO ( FOR /R %%F IN (%%A) DO ( COPY /Y "%%~fF" "%OF%" ) ) POPD It basically locates each subdirectory of ArchiveFolder that includes the JobName in it, then digs into each one that it finds to copy the files out of them. EDIT2: Added NET USE to access your network share to perform tasks on the files. If your local machine already has the UNC assigned to a driveletter, you can remove the NET USE command line and change Z: to the assigned driveletter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How many numbers are in the Fibonacci sequence Assuming I'm asked to generate Fibonacci numbers up to N, how many numbers will I generate? I'm looking for the count of Fibonacci numbers up to N, not the Nth number. So, as an example, if I generate Fibonacci numbers up to 25, I will generate: * *1, 1, 2, 3, 5, 8, 13, 21 *that's 8 numbers How do I calculate this mathematically for an arbitrary "n"? A: You can use the following formula (see here): n(F) = Floor(Log(F * Sqrt(5) + 1/2) / Log(Phi)) A: You can calculate the non-recursive function via the generating function. The n-th element can be calculated via the formula: f(n) = (1 / Sqrt(5)) * (((1+Sqrt(5))/2)^n - ((1-Sqrt(5))/2)^n) Maybe you can derive a method with this function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep a secured DB of network passwords and access it programatically I need a solution to store all my network passords in a secure database. For that, I was thinking of Keepass. Now once the kdb (keepass DB) or something similar has been created, I would like to access it programatically preferably via Java. I was also thinking of developing my own solution. Its a client/server architecture. The server will store all the passwd in gpg format. The clients will have the private key for decrypting the password received from the server. Only the clients with the correct private key can get decrypt the passwords. The private key will be embedded within the program. Thanks, Neel
{ "language": "en", "url": "https://stackoverflow.com/questions/7557297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Insert date only into database I am trying to save only date (ex: 2011/09/26 00:00:00) from getdate(). I am using sql server 2005. My sql query is going to be like this: Insert into Merchant(startdate) values **today's date only** How is it possible? A: INSERT INTO Merchant (startdate) VALUES (DATEADD(DAY,0,DATEDIFF(DAY,0,GETDATE()))) A: select dateadd(dd,0, datediff(dd,0, GETDATE())) However, if you move to SQL2008, I recommend changing your column to DATE instead of DATETIME. A: You can try something like this: EDIT - Revised to account for rounding after midday. SELECT CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, GETDATE()))) Here's another apporoach you can try: SELECT CAST(CONVERT(VARCHAR, GETDATE(), 101) AS DATETIME) A: I'm a little late to the party, but here are my 2 cents: INSERT INTO Merchant (startdate) VALUES (cast(GETDATE() as Date)) That, of course, will only work from SQL Server 2008. I'll leave this answer, however, for learning purposes and future references.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: dispose serial port I am using using class System.IO.Ports. In some cases this component still runs even when the program is closed. As a result I can not open the new serial port with the same port name, cause it is already opened. Please, is there any way how to dispose System.IO.Ports in c#? A: When you say "this component still runs..." are you using some 3rd party tool to communicate with the Serial port? Because if you're using System.IO.Ports.Serial, and you properly dispose of it (uinsg a 'using' block) it whould be closed, certainly after your program ends. A: You're looking for the cunningly-named Dispose method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ERROR 1136: Column count doesn't match value count at row 1 I get the Error: Column count doesn't match value count at row 1. But I've checked and rechecked my query and everything seems ok: UPDATE table SET col = 'enum(''FOO'',''BAR'')' WHERE col1 = '' AND col2 = 'val2' AND col3 = 3; I thought the table could have some triggers that were generating the error –I didn't design the system– but I can't find any. I've found the same error with at least three different tables. Note. The "enum" on line three is really supposed to be a string, not an enum type. A: Apparently there were some triggers that updated another database, I don't know why show triggers from <dbname> returned an empty row set. Apparently, when migrating their system, they had to ask support to create the triggers for them. A: It could be a few things, but here are two ideas: -There is a trigger that needs to be changed/removed. -The value that you are updating the cell to exceeds the column length. Article on this. A: Some time triggers create this issue as well. For example I have create a trigger to log the entries, when I add some field in master table and try to update the master table it display the same error. After some work around, I got the point and create the same field in log table and it fix the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }