text
stringlengths
8
267k
meta
dict
Q: why does this text input not cache? I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info. http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username. http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why. Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this. Here's the code from the first example: <form method = "post" action = ""> Username: <input type="text" name="login_name" value="" /> <br><br> Password: <input type="password" name="password" value="" /> <br><br> <input type="submit" value="Login" /> </form> Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php <p> Email address: <input type="text" id="logininfo" value="" /> <br> Password: <input type="password" id="password" value="" /> <br> <input type="button" id="loginbutton" value="Login" /> </p> Here is the jquery used in the second example: <script type ="text/javascript"> $(function(){ $('#loginbutton').click(function(){ var loginvar = $('#logininfo').val(); var passvar = $('#password').val(); //alert(loginvar + ", " + passvar); if (loginvar != '' && passvar != '') { var subdata = { logindata : loginvar, passdata : passvar }; $.ajax({ url: "index_backend.php", type: 'POST', data: subdata, success: function(result) { //alert(result); if (result == '1') { // success window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php") } else if (result == '2') { //$('#logininfo').empty(); $('#logininfo').attr('value', '') $('#password').attr('value', '') alert("Login failed. Please try again, or register if you have not already created an account."); } else { alert("Something has gone wrong!"); alert (result); } } // end success }); // end ajax } else { alert ("Please enter a username and password."); } }); /// end click function for button }); //// end </script> A: Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling class function from module? I am just writing some dummy code for pygame. The first sample of code has a function in the menus.py file. I wanted to practice using import. This works fine. I then wanted to put the function in a class so I can get up and running with classes. This is the second block of code. Unfortunately the second block of code doesn't run. Could someone explain where I am going wrong please. # menus.py def color_switcher(counter, screen): black = ( 0, 0, 0) white = (255, 255, 255) green = (0, 255, 0) red = (255, 0, 0) colors = [black, white, green, red] screen.fill(colors[counter]) # game.py #stuff if event.type == pygame.MOUSEBUTTONDOWN: menus.color_switcher(counter, screen) #more stuff This works fine. This doesn't # menus.py class Menu: def color_switcher(self, counter, screen): black = ( 0, 0, 0) white = (255, 255, 255) green = (0, 255, 0) red = (255, 0, 0) colors = [black, white, green, red] screen.fill(colors[counter]) # game.py #stuff if event.type == pygame.MOUSEBUTTONDOWN: menus.Menu.color_switcher(counter, screen) #more stuff #TypeError: unbound method color_switcher() must be called with Menu instance as first argument (got int instance instead) Could someone tell me what I am doing wrong with the class please? A: That is not problem with import. Since color_switcher is not static method, you must first create class instance, and only then call a member function: if event.type == pygame.MOUSEBUTTONDOWN: menus.Menu().color_switcher(counter, screen) Alternatively, you can declare your class as class Menu: @staticmethod def color_switcher(counter, screen): and then use it as menus.Menu.color_switcher(counter, screen) A: I then wanted to put the function in a class so I can get up and running with classes It's not that simple. You really, really, really need to do a complete Python tutorial that shows how to do object-oriented programming. You rarely call a method of a class. Rarely. You create an instance of a class -- an object -- and call methods of the object. Not the class. The object. x = Menu() x.color_switcher(counter, screen) A: You're trying to call an instance method as a class method. Two solutions: 1) change the client code: call the method on an instance of the class menus.Menu().color_switcher(counter, screen) # note the parentheses after Menu 2) change the definition: change the instance method to a class method using the class method annotation A: You need to create an instance of Menu before you can call the method. For example: my_menu = Menu() my_menu.color_switcher(counter, screen) You are currently treating color_switcher as if it is a class method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Working with tomcat I'm used to work with WAMP and I find it very easy to understand. Now I need to start up with JSP and I've downloaded Tomcat7. I installed it together with JRE and Eclipse but i just can't get how it works. I placed my project in /webaps/ but when i access the local host, it shows just the WAMP projects (placed in /www/ folder). How exactly is this Tomcat server used and is there a way to combine it with WAMP so it can be easier to use? Thanks! A: Tomcat listens by default on port 8080. Make sure that you're opening http://localhost:8080. The port number is configureable in Tomcat's /conf/server.xml. To get Tomcat and WAMP (specifically: Apache HTTPD) to work togeher, use mod_jk. Or use XAMPP, it comes with integrated Tomcat next to WAMP as well. A: Did you start it up? The startup script is usually in TOMCAT/bin/startup.bat or Tomcat/bin/startup.sh on a unix environment. A: Like @BalusC said: You tomcat is normally running at port 8080. But also important is that you compiled your java classes of your project. Your eclipse project is not autocomplied. Most simple way: export you project as *.war in the /webapps folder. than your tomcat should autodeploy your project. But you could also use the Tomcat6 IDE for eclipse where you can start your project by "Run As"/"On Server"
{ "language": "en", "url": "https://stackoverflow.com/questions/7515910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Distributing an application across Internet I searched but couldn't find a proper answer for this...may be I didn't look deep enough. Anyways, little insight from you guys will only make things easier. So hear me out. this is for my final year research project. I just need concepts and if any links I can read more. So this application is a distributed one for a hotel which has 3 branches (including the main hotel) in location A, B, C. I & (my colleagues) have developed the database, business logic, and 3 separate GUIs for the billing, bar and the kitchen. All are working perfectly and we used .NET remoting for this. this is the whole system and GUIs connected to the business through LAN. This system, should be deployed in each location (A,B,C) and from the main hotel (A), I should be able to view the details of other locations (B,C). and all 3 systems should be connected through the internet. problem is, how do I do that? I just wanna view the information of other places and may be take printouts. that is not relevant for the question i guess. The database is not distributed, each location has its own database. If I were to use a web service, how can I do it more cost-effectively? where do I have to deploy the service? as a side note, I have developed a simple chat system (remoting) and tried to connect it through internet with a friend but it didn't work. If anyone knows why? please be kind enough to provide any other relevant information on this topic. and please ask questions. A: Why not just build a web application with a secure login? That way you build one system, deploy one system, maintain one system. All your data would be in one place, making reporting a lot less onerous, the whole thing would be faster and if you ever need to add a fourth, fifth or twenty seventh additional location, then you'd need to do very little to make it happen. I see no reason why you have to go about it as you are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validate the edittext field inside alertdialog I am using this function to insert into the database. I'd like to validate inputs from two edittext fields. Whenever I push ok button without giving any inputs, the program crashes.I tried to print the values as well, but it didnt display in logcat.Am i doing anything wrong? private void add() { LayoutInflater inflater=LayoutInflater.from(this); final View addView=inflater.inflate(R.layout.add_country, null); new AlertDialog.Builder(this) .setTitle("Add new country/year") .setView(addView) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClickDialogInterface dialog,int whichButton) { /* Read alert input */ EditText editCountry =(EditText)addView.findViewById(R.id.editCountry); String country = editCountry.getText().toString(); EditText editYear =(EditText)addView.findViewById(R.id.editYear); int year = Integer.parseInt( editYear.getText().toString() ); if(editCountry.getText().toString().trim().length()>0 && editYear.getText().toString().trim().length()>0){ /* Open DB and add new entry */ db.open(); db.insertEntry(country,year); /* Create new cursor to update list. Must be possible to handle * in a better way. */ entryCursor = db.fetchAllEntries(); // all country/year pairs adapter = new SimpleCursorAdapter(CountryEditor.this, R.layout.country_row,entryCursor, new String[] {"country", "year"}, new int[] {R.id.country, R.id.year}); setListAdapter(adapter); db.close(); } else{ Toast.makeText(CountryEditor.this, "You need to enter Country AND Year.", Toast.LENGTH_LONG).show(); } } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int whichButton) { // ignore, just dismiss } }) .show(); } A: You are calling editBlah.getText().toString() which can return ""; When parsing this to an integer an Exception will be thrown. ( It could also be, if you call .getText() on a view which has initialised to null (ie, you have incorrectly specified the id for the ID you want) a NullPointerException will be thrown. Without the Stacktrace you wouldn't be able to tell which - try and post your stack trace with the question where possible ). You're question is correct - What you need to do is validate the input you're getting: ie: int year = Integer.parseInt( editYear.getText().toString() ); should be: if(editYear.getText().toString().equalsIgnoreCase("")) { // Cannot parse into an int therefore perform some action which will notify the // user they haven't entered the correct value. } Or even the following if you are already going to be validating your int values: int year = Integer.parseInt( editYear.getText().toString().equalsIgnoreCase("") ? "-1" : editYear.getText().toString()); A: editCountry.getText() equals with nullstring? nullponterexception
{ "language": "en", "url": "https://stackoverflow.com/questions/7515914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: USB to COM, how does the RS-232 interperate data? If I had a RFID reader that sends a bunch of keystrokes through USB like a HID, how would the COM port interperate that if I used a USB to COM converter? What would the COM port see? A: You should see the "keystrokes" from the rfid device. At the link level, the converter should take care of speed mismatch issues. It does this via an internal buffer or by throttling the sender. But the HID protocol is more than simple keystrokes. So either the additional information will be suppressed by the USB-COM converter or it won't be. This issue may also be converter-dependent. In this sort of HW mashup, the best thing is to try it and see. (And then write a blog post about what you discovered.) What is your overall goal? What sw are you trying to connect the RFID reader to? Added I agree with @Turbo J's point: most every USB-COM converter acts as a USB device. As such, if you connect them to another USB device, nothing will happen since you're using them "the wrong way around." You'll need to find a USB/Host to COM converter. The usual name for such things is "computer" -- a used laptop may be your best bet if you want to continue down this road. A: On USB, a device can only talk to the host. The RFID reader is a device. The USB->COM converter is a device. They cannot talk to each other wihout a host. Conclusion: If you want the RFID data going out of the COM port, write a program which does that - by reading the HID data from RFID device and writing to the USB COM port. A: Probably nothing. COM ports are usually very low speed things (you can usually tweak them up to about 115kbps. USB ports are (by comparison) incredibly high speed ports. I think the lowest speed USB is like 1.5mbps. The more important question is how you are going to make the physical conversion. You have an RFID reader that has a usb plug on it. Are you going to chop this off and solder a db9 connector on the end, which you are then going to plug into an USB to COM adapter and try to read serial data off the com port? You are adding in one more step into it that you don't need to (you're taking up an usb port anyway).
{ "language": "en", "url": "https://stackoverflow.com/questions/7515915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send $_POST content without submit bottun I have form inputs to send to another page to check on and validate them, and in case of errors I have to redirect the user back to the page where he/she filled the form. So I need to send the content of $_POST back to refill the inputs to avoid refilling them manually... How can I do that?? A: Here are two options: 1) Have the PHP script redirect back to the page with the form, with the form values in the URL as GET variables. You can then use those to refill the form. 2) You can send a POST request via jQuery without requiring the user to leave the page. See here: http://api.jquery.com/jQuery.post/ . With this, you can check the user's input in the PHP script, and only redirect them if their input is valid. This saves you the trouble of refilling the form. You can use it like this: $.post("myphpscript.php", { someData: someValue, someMoreData: anotherValue }, function(returnData) { // do stuff here on return }); In myphpscript.php you can get the post values as $_POST["someData"] and $_POST["someMoreData"]. The function is what happens when the PHP script returns, and returnData is what the PHP script echoed. A: If I'm correct you want to check your POST-values and if they are invalid input, you want the user to be directed back to the original page and fill the input-fields with the POST-values. <input type="text" value="<?php echo (isset($_POST["text"] ? $_POST["text"] : "") ?> /> This checks if the POST-var is set, if so, it sets the value of the input-field to the value of the POST-var, else it sets the value to empty A: An alternative to excellent answers posted is to store these values into the session and access them from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery selector differences after page refresh When the page is first loaded the snippet below alerts the correct value. If I F5 the page however I get an alert of the first option in the select, which is not the correct value. If I put the cursor in the URL bar and hit Enter then I again get the correct value. This snippet comes out of the idealforms.js file which isn't working properly and I'm trying to correct it. It's possible that this issue influenced from somewhere else in the code but I have my doubts. Any idea why this is happening, does a page refresh somehow behave differently then when the page is first loaded? form.find('select').each(function () { var select = $(this); nu_title = select.find(':selected').html(); alert(nu_title); }); A: On some browsers after F5, values filled in forms stay. CTRL+F5 (or re-entering the page from the url bar, like you suggested) should clear those under most settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lookup across multiple columns & rows in excel Vlookup's limitation is that it searches for a value down a single column. I need to search across multiple columns and multiple rows. I have data in the following format: HOST1 Guest1 Guest2 Guest3 Guest4 HOST2 Guest5 Guest6 Guest7 Guest8 I need to convert it down to two column pairs like this: Guest1 Host1 Guest2 Host1 Guest3 Host1 So I want to lookup the guest's name in the range, b1:e2 in the first example. Then grab the row number, and grab the value of {A$rownumber}. Is it possible to do this kind of multicolumn, multirow search? Or are all the searches limited to one-dimensional vectors? A: The way for double lookups is to use INDEX(MATCH(...), MATCH(...)). in Excel 2003 you can even activate the Lookup Wizard that does it for you. A: I made a user form with a combobox called ComboBox1 and a textbox called TextBox1 (multiline property enabled). When you load the user form (UserForm1) you the Initialize event will fire executing UserForm_Initialize(). That will populate the combobox with all the hosts. When you select a host the ComboBox1_Change() event will fire and output something like HOST2 Guest5 Guest6 Guest7 Guest8 to the text box. But ofcourse you can change the output to be anywhere you want. Option Explicit Dim allHosts As Range Private pHostRow As Integer Dim hostColumn As Integer Private Sub UserForm_Initialize() Dim Host As Range Dim firstHost As Range Dim lastHost As Range Dim lastHostRow As Integer hostColumn = 1 Set firstHost = Cells(1, hostColumn) lastHostRow = firstHost.End(xlDown).Row Set lastHost = Cells(lastHostRow, hostColumn) Set allHosts = Range(firstHost, lastHost) For Each Host In allHosts ComboBox1.AddItem Host.Text Next Host End Sub . Private Sub ComboBox1_Change() Dim selectedHost As String selectedHost = ComboBox1.Text pHostRow = allHosts.Find(selectedHost).Row Dim guest As Range Dim allGuests As Range Dim firstGuest As Range Dim lastGuest As Range Dim lastGuestCol As Integer Dim Host As Range Set Host = Cells(pHostRow, hostColumn) lastGuestCol = Host.End(xlToRight).Column Set firstGuest = Host.Offset(0, 1) Set lastGuest = Cells(pHostRow, lastGuestCol) Set allGuests = Range(firstGuest, lastGuest) TextBox1.Text = selectedHost For Each guest In allGuests TextBox1.Text = TextBox1.Text & selectedHost & guest.Text & vbCrLf 'if you weren't outputting this to a textbox you wouldn't use the vbCrLf, 'instead you would iterate to the next line in your output range. Next guest End Sub You can see how you can modify this so you would iterate through all the hosts (i.e. while populating the combobox) and for each host call the ComboBox1_Change() event (renamed of course and made a regular sub) to output all the guests to some range that you are iterating through on another worksheet. Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7515928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ClearCase single stream UCM project: When are changes visible in a snapshot view? Consider a single stream UCM project in ClearCase. Each developer works in her own snapshot view on the integration stream of the project. According to the ClearCase documentation when a developer completes an activity, the changes made by the activity become visible to the rest of the developers. When developer A completes an activity P, are the changes of P immediately visible to developer B and C? Or do B and C have to refresh their snapshot view in order to actually see the changes? A: For a snapshot view (UCM or not), you always have to "cleartool update" your view in order to see the changes committed by your colleagues. Note: the notion of "completing an activity" might suggest that you are actually using ClearCase with ClearQuest (which will check-in all checked out files associated with an activity, when the related ClearQuest work item is "completed"). This is valid for single-stream UCM projects as well as multi-streams: every time you have several snapshot views on a single stream, you need an update to see your colleagues' commits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery index of an element in an selector array I'm trying to get the index of an element within an array returned by a jquery selector. Here's my code: $("div").click( function(){ alert( $.inArray( $(this), $("#div") ) ); }); An an example, for this HTML: <div>A</div> <div>B</div> <div>C</div> <div>D</div> I want it to display "4" when the user clicks the div containing D. Is there any way to do this? This inArray function doesn't seem to do what I expect when applied to selectors. A: You just want: $("div").click(function(){ alert($(this).index("div")); }); (You would need to add 1 to the result of the .index() call since the index is 0-based). Example: http://jsfiddle.net/andrewwhitaker/tdcVU/ A: Another method you could use is the prevAll() alert($(this).prevAll("div").length + 1); A: try .index() var selectedItem = $(this); var index = $('div').index(selectedItem); A: Here's an update of your code that would work - $("div").click( function(){ alert( $.inArray( this, $("div") ) ); }); The changes are - * *Changed the selector passed into the array argument of inArray from #div to div *Passed a normal JavaScript DOM element rather than a jQuery wrapped element into the inArray function Working demo - http://jsfiddle.net/ipr101/CfY8j/
{ "language": "en", "url": "https://stackoverflow.com/questions/7515950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIButton image in UITableViewCell keeps being overridden from XIB file We have a Masterview where project data are shown. Each row is build from a Custom UITableViewCell with a XIB file. There is a button on each Cell. We use the Button to explode cq. implode the project list (based on a hierarchy). When doing so the image on the button needs to be changed. This works fine when a button is clicked (a variable:show for all the projects is turned on/off depending on the collapse cq. explode situation, only projects are fetched where show = true) and the correct image is shown in every row. Problem: but when one row is tapped or let's say: selected, then the image from the XIB file is reloaded. In RootViewController: - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Deselect the currently selected row according to the HIG [tableView deselectRowAtIndexPath:indexPath animated:NO]; // Set the detail item in the detail view controller. ProjEntity *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath]; [self selectProjEntity:selectedObject]; ProjectTableViewCell *selectedCell = (ProjectTableViewCell *)[[self tableView] cellForRowAtIndexPath:indexPath]; [selectedCell setCollapseImage:selectedObject]; [tableView reloadData]; [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; In Cell: ProjectTableViewCell: - (void) setCollapseImage:(ProjEntity *) projRow { UIImage* btImage; if ([projRow.explode intValue] == 0) { if ([projRow.projLevel intValue] == 1) { btImage = [UIImage imageNamed:@"add-big.png"]; } else { btImage = [UIImage imageNamed:@"plus.gif"]; } } else { if ([projRow.projLevel intValue] == 1) { btImage = [UIImage imageNamed:@"Minus_groenGroot.png"]; } else { btImage = [UIImage imageNamed:@"min.gif"]; } } self.collapseButton.imageView.image = btImage; } So only when a row is selected the button's image does not update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic jasper report header image I am creating dynamic jasper reports. Things are looking fine. How do I add a dynamic header image to the generated reports? I am using FastReportBuilder fr = new FastReportBuilder(); Style headerStyle = new Style(); headerStyle.setBackgroundColor(Color.BLUE); headerStyle.setPadding(5); fr.setTitle("Title") .setSubtitle("Sub title") .setPrintBackgroundOnOddRows(true) .setUseFullPageWidth(true) .setPageSizeAndOrientation(Page.Page_A4_Landscape()) .setTitleHeight(100) .setTitleStyle(headerStyle); But its not working. Reports will be exported in pdf, csv, and html formats. A: It works for me fr.setUseFullPageWidth(true) .setPageSizeAndOrientation(Page.Page_A4_Landscape()) .addFirstPageImageBanner("path/logo_strip.jpg", 800, 50, ImageBanner.ALIGN_LEFT);
{ "language": "en", "url": "https://stackoverflow.com/questions/7515955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IOS print pdf with minimal margins This must be quite simple but I can't seem to figure this out. I've managed to implement the code for printing an PDF from my App. Problem is, the PDF has quite some whitespace around it and with the default margins... it's just not how I would like the page to come out of the printer. So, I'm trying to reduce the margins to minimum. How would I go about this? Do I need to use a custom UIPrintFormatter, UIPrintPageRenderer or UIPrintPaper. In which method from UIPrintInteractionControllerDelegate would I need to change things? I know it can be done because when I print the PDF from Apple's iBook App, margines are significant less. Thanks. A: I did not quite solve the problem but I'm satisfied with the result now. Actually I did not change anything, the reason why I asked this questing was because in the AirPrint simulator, my PDF printed with an excessive amount of white space / margin. But printing the PDF on an actual device did not have this problem. So, if you run into this problem in the AirPrint simulator, try it on a real device/printer, changes are that everything prints fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to upload photo in album and create a feed at the same time for the new facebook user I want to post photos into facebook, and also create a feed for the photo I posted at the same time. It works when I post photo to the wall, but when I posted to the album, it will create a feed with the photo on the first time. After that, it only create a text message says "bla bla bla post a photo in XXX album". Here is the problem: when user is new for facebook, his wall is non-exsist.The wall will be created after user post a feed with photo on website. Question: So, at this time, how can I post photo for such users and create a feed at the same time? A: When you add a picture you can use the response to ad the picture. share the picture. Scenario 2 in this example shows how to do so and get the repsons with PHP. https://developers.facebook.com/blog/post/498/ With that response you could create a feed dialog: http://developers.facebook.com/docs/reference/dialogs/feed/ And put together the URL for the image using the response from the photo upload. If you run into trouble showing the image, you might need to use a proxy to load it. Facebook sometimes gives you trouble when adding an image that is comming from their CDN in a feed post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Allow directory access for certain IP's at Lighttpd I need to rewrite this rules (from apache's .htaccess): <files "*.*"> Allow from 84.47.125.0/19 66.211.160.0/19 216.113.160.0/19 Deny from All </files> To lighttpd ones, to allow the access to my /pswd directory only for those IP's: 84.47.125.0/19, 66.211.160.0/19, 216.113.160.0/19 How can I do that in lighttpd? A: I've never used lighttpd but I've found this on Google: http://www.cyberciti.biz/tips/lighttpd-restrict-or-deny-access-by-ip-address.html It has an example for blocking access for 2 IPs and for blocking a single IP. It should be easily adaptable for you by doing this: # vi /etc/lighttpd/lighttpd.conf and then: $HTTP["remoteip"] !~ "84.47.125.0/19|66.211.160.0/19|216.113.160.0/19" { $HTTP["url"] =~ "^/pswd/" { url.access-deny = ( "" ) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Signing map application android I made my first app on andoid and it's a app with google maps inside. I have read some articles and I don't understand it. I don't have any keystore or keytool. How can I sign my app? What is procedure? Do I first export signed app with option create new keystore and then get new Maps API key and then in my apk file change map key or what? Here is my debug Maps API key: <com.google.android.maps.MapView android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable="true" android:enabled="false" android:layout_alignParentTop="true" android:layout_above="@+id/seekBar1" android:layout_weight="5" android:apiKey="0djE6Z-QX918E3HmDriPn2hxyzFD0kzduhFbiaQ" > </com.google.android.maps.MapView> A: http://developer.android.com/guide/publishing/app-signing.html here is the answer keytool.exe is on java_jre/bin/keytool.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/7515968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem Deploying new application Im new to this, so please forgive me. What im doing is deploying my application onto the server, it works fine on my local machine but im getting errors when I try to hit the server. Here is the error below and my web.config file. I dont know what im doing wrong. Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS. Source Error: Line 18: <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> Line 19: <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation> Line 20: <authentication mode="Forms"> Line 21: <forms loginUrl="~/Account/Login.aspx" timeout="2880"/> Line 22: </authentication> <configuration> <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <customErrors mode="Off"></customErrors> <compilation debug="true" strict="false" explicit="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation> <authentication mode="Forms"> <forms loginUrl="~/Account/Login.aspx" timeout="2880"/> </authentication> <membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/> </providers> </membership> <profile> <providers> <clear/> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/> </providers> </profile> <roleManager enabled="false"> <providers> <clear/> <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/> <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/> </providers> </roleManager> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> A: I seem to recall this happening when you have deployed your application into a sub-folder of an existing site, and it it's web.config includes a setting that either applies to the entire site/application, and can't be modified on a per-folder basis It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level I'd play with your <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> setting. Try moving it to the site's root web.config and see where that gets you, or remove it entirely. Also, see (just from a quick Google) Error: allowDefinition='MachineToApplication' beyond application level http://geekswithblogs.net/ranganh/archive/2005/04/25/37609.aspx ASP.NET IIS Web.config [Internal Server Error] http://forums.asp.net/t/1031775.aspx/1
{ "language": "en", "url": "https://stackoverflow.com/questions/7515970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Typing in a IFrame with Selenium IDE I'd like to type something in a IFrame with Selenium IDE but I don't know how to do this. Thanks a lot! A: You have to select the iframe and then type selenium.selectFrame("css=iframe.widget[<a_css_identifier>]"); selenium.type(<your_object_or_text_box>, <typed_content>); The statements are in java, but you should be able to find selectFrame and type in the IDE. A: You can use the Selenium IDE command 'selectFrame' to focus within an iframe. Use the Target field to enter the iframe id. A: Try <tr> <td>selectFrame</td> <td>edit</td> <td></td> </tr> <tr> <td>type</td> <td>xpath=//html/body</td> <td>my text</td> </tr>
{ "language": "en", "url": "https://stackoverflow.com/questions/7515981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Enable feature by default in WIX While extending a WIX-installer that I have to maintain, I ran into the following problem - when shown the tree of features and components, the product feature is not selected by default. I tried different variations, including adding InstallDefault ='local', TypicalDefault ='install', and Absent = 'disallow', however, the feature is still disabled. Here is the code that describes the feature: <Feature Id="Complete" Level="1" Display='expand' InstallDefault ='local' TypicalDefault ='install' Absent = 'disallow' Title="$(var.ProductName)"> <ComponentGroupRef Id="Required_files"/> <?ifdef InstallDriver?> <ComponentGroupRef Id='driver_files'/> <?endif?> <ComponentRef Id="ProgramMenuShortcuts"/> <ComponentRef Id="ProductInfo"/> <?ifdef RemoveAllRegKeys?> <ComponentRef Id="RegRemoveAll"/> <?endif?> <ComponentGroupRef Id="FBmodule"/> </Feature> Having examined the logs, I see some entries that seem to be related to this (this is happening when I manually set the feature to "install to local hard disk"). MSI (c) (FC:90) [16:43:57:559]: PROPERTY CHANGE: Adding MsiSelectionTreeSelectedFeature property. Its value is 'Complete'. MSI (c) (FC:90) [16:43:57:559]: PROPERTY CHANGE: Adding MsiSelectionTreeSelectedAction property. Its value is '2'. MSI (c) (FC:90) [16:43:57:559]: PROPERTY CHANGE: Adding MsiSelectionTreeSelectedCost property. Its value is '0'. Action 16:43:57: FeaturesDlg. Dialog created MSI (c) (FC:90) [16:51:44:645]: Note: 1: 2727 2: .... many repetitions of Note: 1: 2727 2: MSI (c) (FC:90) [16:51:45:146]: Note: 1: 2727 2: MSI (c) (FC:90) [16:51:45:630]: Note: 1: 2205 2: 3: MsiAssembly MSI (c) (FC:90) [16:51:45:630]: Note: 1: 2228 2: 3: MsiAssembly 4: SELECT `MsiAssembly`.`Attributes`, `MsiAssembly`.`File_Application`, `MsiAssembly`.`File_Manifest`, `Component`.`KeyPath` FROM `MsiAssembly`, `Component` WHERE `MsiAssembly`.`Component_` = `Component`.`Component` AND `MsiAssembly`.`Component_` = ? MSI (c) (FC:90) [16:51:45:630]: Note: 1: 2205 2: 3: _RemoveFilePath MSI (c) (FC:90) [16:51:45:639]: Note: 1: 2727 2: MSI (c) (FC:90) [16:51:45:647]: PROPERTY CHANGE: Modifying MsiSelectionTreeSelectedAction property. Its current value is '2'. Its new value: '3'. MSI (c) (FC:90) [16:51:45:647]: PROPERTY CHANGE: Modifying MsiSelectionTreeSelectedCost property. Its current value is '0'. Its new value: '7318'. I suspect that this could be related to the fact that there is a custom dialog in the installer - but having looked through the source I could not find anything that would indicate a relationship between the state of the feature and something else in the project. What are the recommended troubleshooting steps? Here is the full installation log. A: I found the culprit. The installer itself is fine, the problem is in how it is started. There is a BAT file that I use for testing purposes, it runs the MSI with some command line arguments that simulate different conditions. The command line arguments REINSTALL=ALL REINSTALLMODE=vomus must only be applied when the installer updates the program; when started that way on a clean system - the progress bar moves and everything goes as expected, but nothing is actually installed. In other words, the error was in the method of testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Understanding parsing SVG file format First off, gist here Map.svg in the gist is the original Map I'm working with, got it off wikimedia commons. Now, there is a land mass off the eastern cost of Texas in that original svg. I removed it using Inkscape, and it re-wrote the path in a strange new way. The diff is included in the gist. Now this new way of writing the path blows up my parser logic, and I'm trying to understand what happened. I'm hoping someone here knows more about the SVG file format that I do. I will admit I have not read through the entire SVG standard spec, however the parts of it I did read didn't mention anything about missing commands or relative coordinates. Then again I may have been looking at the incorrect spec, not sure. The way I understood it, SVG path data was very straight forward, something like this: (M,L,C)[point{n}] .... [Z] then repeat ad-nauseum Now the part I'm trying to understand is this new Inkscape has written out what seems like relative coordinates, without commands like L, or L being implied somehow. My gut is telling me what has happened here is obvious to someone. For what it's worth I'm doing my parsing in C. A: If you're parsing SVG, why not look at the SVG specification? Start a new sub-path at the given (x,y) coordinate. M (uppercase) indicates that absolute coordinates will follow; m (lowercase) indicates that relative coordinates will follow. If a moveto is followed by multiple pairs of coordinates, the subsequent pairs are treated as implicit lineto commands. From: http://www.w3.org/TR/2011/REC-SVG11-20110816/paths.html#PathDataMovetoCommands You said, The way I understood it, SVG path data was very straight forward, something like this: (M,L,C)[point{n}] .... [Z] I don't know where you got that information. Stop getting your information from that source. I will admit I have not read through the entire SVG standard spec... Nobody reads the entire spec. Just focus on the part you're implementing at the moment. You could also start with SVG Tiny, and work with that subset for now. Path Grammar is where you should start when writing a parser. If you can't read it, then buy a book on compilers. Path grammar: http://www.w3.org/TR/2011/REC-SVG11-20110816/paths.html#PathDataBNF
{ "language": "en", "url": "https://stackoverflow.com/questions/7515986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to do a live update to an HTML form using javascript I need to live update a text field in html using javascript, that is as the user is typing text in one field, the contents are being displayed in another as they type. i need just a short code snippet to do that. eg as a person is typing their name, the name is being typed one letter at a time at another position on the screen. A: Give the two fields an id each, then use something like this: document.getElementById("field1").onkeyup = function() { document.getElementById("field2").value = this.value; } All it does is bind an event listener to the onkeyup event, which fires every time a key is released. In the event listener, it simply copies the value of the field which received the event to another field, specified by id. Here's a working example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to return all rows if using if (empty($variable))? I am using this query below and it only returns the first query in the entry if i use only the if (empty($field1)) to display. If i fill in the print(""); it works but i want to use the if (empty($field1)) snippet to display. How can i do it? $sql="SELECT field1, field2 FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC"; $result=mysql_query($sql); $query = mysql_query($sql) or die ("Error: ".mysql_error()); if ($result == "") { echo ""; } echo ""; $rows = mysql_num_rows($result); if($rows == 0) { print(""); } elseif($rows > 0) { while($row = mysql_fetch_array($query)) { $field1 = $row['field1']; $field2 = $row['field2']; print(""); } } if (empty($field1)) { echo ""; //Thats right, i don't want anything to show for this portion } else { echo "<div id=comments>Comments</div><br> <div id=entries>$field1 and $field2</div>"; } A: What are you trying to do? somthing like this: $sql="SELECT field1, field2 FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC"; $result=mysql_query($sql) or die ("Error: ".mysql_error()); $rows = mysql_num_rows($result); if ($rows > 0) echo "here are your entries\n"; while($row = mysql_fetch_array($result)) { echo $row['field1']." "; echo $row['field2']."\n"; } another way $sql="SELECT field1, field2 FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC"; $result=mysql_query($sql) or die ("Error: ".mysql_error()); $rows = mysql_num_rows($result); if ($rows > 0) echo "here are your entries\n"; while($row = mysql_fetch_array($result)) { if (empty($row['field1'])) { echo " "; } else { echo $row['field1']." "; echo $row['field2']."\n"; } } A: i believe mysql_fetch_array only returns one row http://www.w3schools.com/PHP/func_mysql_fetch_array.asp also ur sure that neither p_id and k_id are not unique? i would also try $sql="SELECT * FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC"; just to see if that yields any different results, you can always parse out just the two fields from the return data TRY THIS TO START WITH (the $results variable is just confusing things): $sql="SELECT field1, field2 FROM table WHERE p_id='$pid' and k_id='$kid' ORDER BY id DESC"; $query = mysql_query($sql) or die ("Error: ".mysql_error()); $rows = mysql_num_rows($query); if($rows == 0) { print(""); }else{ while($row = mysql_fetch_array($query)) { if ($row['field1'] == "") { print(""); }else{ $field1 = $row['field1']; print($field1) } if ($row['field2'] == "") { print(""); }else{ $field1 = $row['field2']; print($field2) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ViewModel passed via jQuery POST contains null/empty properties I'm working on my first ASP.NET MVC 3 application and what I want to accomplish is that a user can select a recipe from my grid and then have it displayed in a div called details. There the user can click the Edit button and the view switches to an edit view within that same div and then when the user has made changes the Save button can be clicked which would persist the changes and redisplay the details. I'm using jqGrid (not really germane to the discussion) and have a bit of code to populate the details div like so: onSelectRow: function(theRow) { var grid = jQuery('#recipeGrid'); var cellData = grid.jqGrid('getCell', theRow, 'RecipeID'); $('#details').load('@Url.Action("Details", "Recipe")', { id: cellData }); } In that details view there's a button and some jQuery which does a similar thing to swap out this details view with a details edit: <input type="button" value="Edit" class='editrecipe' data-recipeid="@Model.RecipeID" /> <script type="text/javascript" language="javascript"> $(function () { $('.editrecipe').click(function () ){ var recipeId = $(this).data('reciepid'); $.ajax({ type: "GET", data: "id=" + recipeId, url: '@Url.Action("Edit", "Recipe")', dataType: "html", success: function (result) { $('#details').html(result); } }); }); }); </script> Then on that edit looks something like this: @model IceCream.ViewModels.Recipe.RecipeCreateEditViewModel @using (Html.BeginForm()) { ... <input type="button" value="Save" class='saverecipe' /> } <script type="text/javascript" language="javascript"> $(function () { $('.saverecipe').click(function () ){ $.ajax({ type: "POST", data: $('form').serialize(), cache: false, url: '@Url.Action("Edit", "Recipe")', dataType: "html", success: function (result) { $('#details').html(result); } }); }); }); </script> Back in my controller action, I noticed that some of the properties of the viewModel are correct but most are null. I'm guessing that I'm doing something wrong here related to the ajax call where the serialization happens (or doesn't). Any ideas? Update: So, I changed a few things and it looks better. First, I gave my form an ID like so: @using (Html.BeginForm("Edit", "Recipe", FormMethod.Post, new { id = "editRecipeForm" })) Then I altered my Save button to look like so: <input type="submit" value="Save" /> Then the jQuery looks like this: $('#editRecipeForm').submit(function () { var options = {success: function (html) { $("#details").replaceWith($('#details', $(html))); }, url: '@Url.Action("Edit", "Recipe")' } $(this).ajaxSubmit(options); return false; }); At least initially, it looks like my viewModel is now being populated correctly in the POST action. However it does NOT seem to execute the success callback. What I do in my controller action is call return Details(viewModel.RecipeID); which I expect will return the PartialView back and the success callback would replace the contents of the '#details' div with that info. What actually happens is that it just returns the Details and displays that - not in the div. Ideas? A Solution: Until I went in and created a bad Action in the url: '@Url.Action("Edit", "Recipe")' line, I was fooling myself that this was actually running. Reason? Didn't have jquery.form.js included... that'll help things. :-p I modified things a bit. Looks like this now: var options = { target: "#details", url: '@Url.Action("Edit", "Recipe")', }; and then $('#editrecipeform').submit(function () { $(this).ajaxSubmit(options); return false; }); Still would be interested in the thoughts of others on this - particularly if there is a better way to do this. A: Instead of: $('#editrecipeform').submit(function () { $(this).ajaxSubmit(options); return false; }); I'd use: $(function() { $('#editrecipeform').ajaxForm(options); }); Other than this small remark your solution with the jquery.form plugin is really nice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make a bullet list align with text in css? The image demonstrates the problem. I want the bullet list to be aligned with the text, not indented. This must be modified in css i guess, because source is: <p>This is a test :)</p> <ul> <li>Test1</li> <li>Test2</li> <li>Test3</li> <li>Test4</li> </ul> <p><strong>Bla bla</strong></p> <p><strong>Dette er en test</strong></p> <p><strong><span class="Apple-style-span" style="font-weight: normal;"><strong>Dette er en test</strong></span></strong></p> <p><strong>Dette er en test</strong></p> <p><strong><span class="Apple-style-span" style="font-weight: normal;"><strong>Dette er en test</strong></span></strong></p> </div> So how can I remove the padding/margin from left in this bull list? I tried margin: 0; padding: 0; did not work out A: Apply padding-left: 0 and change the list style position to inside: ul { padding-left: 0; } ul li { list-style-position: inside; } Example link http://jsfiddle.net/vF5HF/ A: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Bullet alignment</title> <style type="text/css"> body { font-size: 14pt; margin: 100px; background-color: #f2f2f2; } ul { margin-left: 0; padding-left: 2em; list-style-type: none; } li:before { content: "\2713"; text-align: left; display: inline-block; padding: 0; margin: 0 0 0 -2em; width: 2em; } </style> </head> <body> <p>Bullet alignment &#x1F608;</p> <ul> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</li> <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</li> </ul> <p>That’s all Folks</p> </body> A: ul { margin-left: 0; padding-left: 0; } li { margin-left: 1em; } A: As @NicolaPasqui mentioned, for your problem you should use: ul { padding-left: 0 } ul li { list-style-position: inside; } When setting list-style-position to inside, the bullet will be inside the list item. Unlike setting it to outside, where the bullet will be outside the list item. There is a great article about bullet style I think you could benefit from here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Using jQuery for tooltips I have a div with a form inside it. The form is small, consists of one or two dropdown/textboxes. I'm wondering what would be required to do the following: * *when I click on a link, a tooltip pops up with the form in it. It appears over top of the link that I clicked so that when it appears the mouse is over top of it. *when the mouse exits the bounds of the tooltip, it disappears. Doing some googling, all of the tooltip examples I found appear upon hovering over a given area. All the jQuery popup examples I seen are modal and force the user to explicitly close it. Does anyone know of a way that I can have a tooltip work as described above? A: If you can't find a plugin that works, what you described is pretty straight forward to implement. You just have to bind a mousemove event to the document and check to see if its target or its target's parents are your tooltip. This example is for a trigger button that is right next to the tooltip, but it might work for having it directly over the trigger as the trigger then wouldn't be hovered. $("#trigger").hover(function () { // move the tool tip div into place // show the tool tip }, function () { $(document).bind('mousemove.tooltip', function (e) { if (e.target.id !== 'tooltip' && $(e.target).parents('#tooltip').length === 0) { // close tooltip $("#tooltip").hide(); $(document).unbind('mousemove.tooltip'); } }); }); Here is a rudimentary fiddle that works as described: http://jsfiddle.net/5h3Zy/5/ A: If you want to use jquery UI plugin use a dialog and a function such as the following: $("#yourDialog").dialog({ autoOpen: false }); $("#yourLink").click(function(){ $("#yourDialog").open(); }); $("#yourDialog").mouseover(function() { }).mouseout(function(){ $(this).close(); }); A: Well i Creted something that i guess was what you where after take a look http://jsfiddle.net/hDcac/1/ The code got kinda messy but you shuld get the idea. :) A: <script type="text/javascript"> $(document).ready(function () { $('#mylink').hover(function () { $('#mytooltip').stop(true, true).fadeIn(); }, function () { $('#mytooltip').fadeOut(); }); $('#mytooltip').hover(function () { $('#mytooltip').stop(true, true).fadeIn(); }, function () { $('#mytooltip').fadeOut(); }); }) </script> <div id="mylink">My Link</div> <div id="mytooltip'">My Form</div> This puts a "hover" event on each element. Anytime your mouse is over either element, it calls "stop(true,true)" which prevents the fadeOut from occuring. Once the mouse leaves the elements, the tooltip fades.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transferring Intellij Live Templates Between Machines I'm trying to figure out how to transfer the templates in the /.IdeaC10/config/templates/user.xml file to my coworker's machines. If I copy into the user.xml file, then those changes seem to be getting squashed by Intellij, reverting to the old file contents. Anyone know how to work around this? EDIT: Is there any way to do this by copying and pasting the xml? That would be preferrable...! A: Use File | Imprort/Export Settings. A: An improved and easier way This allows you to share them easily between collegues. You can select multiple live templates and then copy them (right click and select copy, or ctrl+c). This gives you XML-descriptions in your clipboard you can send to others. Other can then take that XML, and paste it into a "Template Group". Right click one of the groups and select Paste. If the option is greyed out, you didn't select a group but something else. A: If you have Settings Repository set you may find your Live Templates stored in <your_user_home_directory>\ .IntelliJIdea<version>\ config\ settingsRepository\ repository\ templates A: the technique of copying and pasting the xml file on another computer in the correct directory, function perfectly for me! But the name of my template file is android.xml for my Android developments. Maybe the file name "user" is protected. Try maybe with a different file name A: You need to create the required custom template groups and update the relevant predefined groups as necessary and click OK. Based on these changes, IntelliJ IDEA generates the <group_name>.xml files, see Location of Custom Live Templates Definitions above. Depending on the operating system you are using, the .xml files are stored at the following locations: Windows: <your_user_home_directory>.IntelliJ IDEA<version_number>\config\templates Linux: ~IntelliJ IDEA<version>\config\templates OS X: ~/Library/Preferences/IntelliJ IDEA<version>/templates Refer to Intellij Help article.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Overplotting from different data frames in ggplot2 My objective is to plot the path of a river with points indicating important sites near the river. I have two data frames, giving the river and site coordinates respectively: river<-data.frame( long=c(-2.816452494909265,-2.845487331898639,-2.883036393822358), lat=c(56.38229290416972,56.36346886284386,56.36577994637793)) samploc<-data.frame( site=c("Site1","Site2","Site3"), long=c(-2.826213585663894,-2.816519300644918,-2.868437228090127), lat=c(56.3649482229089,56.38166100310631,56.36716019476281)) Using an old school R plot, with par(new=T) and conserving xlim and ylim, I would get something like this: old school plot http://users.utu.fi/susjoh/Riverplot.png But I would like to do it using ggplot2. The river and points can be easily called individually: ggplot(river,aes(x=long,y=lat)) + geom_path() ggplot(samploc,aes(x=long,y=lat,lab=site)) + geom_point() + geom_text(vjust=2) I have tried to cheat, by creating the following data frame from the previous two: > rivsamp river.long river.lat samp.site samp.long samp.lat 1 -2.816452 56.38229 NA NA NA 2 -2.845487 56.36347 NA NA NA 3 -2.883036 56.36578 NA NA NA 4 NA NA Site1 -2.826214 56.36495 5 NA NA Site2 -2.816519 56.38166 6 NA NA Site3 -2.868437 56.36716 ggplot(rivsamp) + geom_path(aes(x=river.long,y=river.lat)) + geom_point(aes(x=samp.long,y=samp.lat)) + geom_text(aes(x=samp.long,y=samp.lat,lab=samp.site),vjust=2) ggplot2 plot http://users.utu.fi/susjoh/riverggplot.png It works, but creating this new data frame is not as straightforward as the old par(new=T) method. Is there a simpler way to overplot from the individual data frames using ggplot2? Thanks! A: Here is one way to do it ggplot(samploc, aes(x = long, y = lat)) + geom_point() + geom_text(aes(label = site), vjust = 2) + geom_line(data = river, aes(y = lat))
{ "language": "en", "url": "https://stackoverflow.com/questions/7516017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Android LocalServerSocket In android, there are two classes LocalServerSocket and LocalSocket. I think they are something like AF_LOCAL in unix socket (I am not sure it is correct or not). My question is that : Is it possible to create LocalServerSocket in Java and use a normal unix socket client to connect to it in native or other process ? If it is possible, what the "sockaddr_un.sun_path" I should set in native ? I have written a sample project to test it, and I try to set the .sun_path as same as string name used in LocalServerSocket, but it failed, the native could not connect to the Java LocalServerSocket. My Java code : package test.socket; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.net.LocalServerSocket; import android.net.LocalSocket; import android.os.Bundle; import android.util.Log; import android.view.View; public class TestSocketActivity extends Activity { public static String SOCKET_ADDRESS = "my.local.socket.address"; public String TAG = "Socket_Test"; static{System.loadLibrary("testSocket");} private native void clientSocketThreadNative(); private native void setStopThreadNative(); localServerSocket mLocalServerSocket; localClientSocket mLocalClientSocket; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mLocalServerSocket = new localServerSocket(); mLocalClientSocket = new localClientSocket(); } /* LocalServerSocket */ public class localServerSocket extends Thread { int bufferSize = 32; byte[] buffer; int bytesRead; int totalBytesRead; int posOffset; LocalServerSocket server; LocalSocket receiver; InputStream input; private volatile boolean stopThread; public localServerSocket() { Log.d(TAG, " +++ Begin of localServerSocket() +++ "); buffer = new byte[bufferSize]; bytesRead = 0; totalBytesRead = 0; posOffset = 0; try { server = new LocalServerSocket(SOCKET_ADDRESS); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "The LocalServerSocket created failed !!!"); e.printStackTrace(); } stopThread = false; } public void run() { Log.d(TAG, " +++ Begin of run() +++ "); while (!stopThread) { if (null == server){ Log.d(TAG, "The LocalServerSocket is NULL !!!"); stopThread = true; break; } try { Log.d(TAG, "LocalServerSocket begins to accept()"); receiver = server.accept(); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "LocalServerSocket accept() failed !!!"); e.printStackTrace(); continue; } try { input = receiver.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "getInputStream() failed !!!"); e.printStackTrace(); continue; } Log.d(TAG, "The client connect to LocalServerSocket"); while (receiver != null) { try { bytesRead = input.read(buffer, posOffset, (bufferSize - totalBytesRead)); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "There is an exception when reading socket"); e.printStackTrace(); break; } if (bytesRead >= 0) { Log.d(TAG, "Receive data from socket, bytesRead = " + bytesRead); posOffset += bytesRead; totalBytesRead += bytesRead; } if (totalBytesRead == bufferSize) { Log.d(TAG, "The buffer is full !!!"); String str = new String(buffer); Log.d(TAG, "The context of buffer is : " + str); bytesRead = 0; totalBytesRead = 0; posOffset = 0; } } Log.d(TAG, "The client socket is NULL !!!"); } Log.d(TAG, "The LocalSocketServer thread is going to stop !!!"); if (receiver != null){ try { receiver.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (server != null){ try { server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void setStopThread(boolean value){ stopThread = value; Thread.currentThread().interrupt(); // TODO : Check } } /* Client native socket */ public class localClientSocket extends Thread { private volatile boolean stopThread; public localClientSocket(){ Log.d(TAG, " +++ Begin of localClientSocket() +++ "); stopThread = false; } public void run(){ Log.d(TAG, " +++ Begin of run() +++ "); while(!stopThread){ clientSocketThreadNative(); } } public void setStopThread(boolean value){ stopThread = value; setStopThreadNative(); Thread.currentThread().interrupt(); // TODO : Check } } public void bt_startServerOnClick(View v) { mLocalServerSocket.start(); } public void bt_startClientOnClick(View v) { mLocalClientSocket.start(); } public void bt_stopOnClick(View v) { mLocalClientSocket.setStopThread(true); mLocalServerSocket.setStopThread(true); } } My Native code : #define SOCKET_NAME "my.local.socket.address" JNIEXPORT void JNICALL Java_test_socket_TestSocketActivity_clientSocketThreadNative (JNIEnv *env, jobject object){ LOGD("In clientSocketThreadNative() : Begin"); stopThread = 1; int sk, result; int count = 1; int err; char *buffer = malloc(8); int i; for(i = 0; i<8; i++){ buffer[i] = (i+1); } /* struct sockaddr_un addr; bzero((char *)&addr,sizeof(addr); addr.sun_family = AF_UNIX; addr.sun_path = SOCKET_NAME; */ struct sockaddr_un addr = { AF_UNIX, SOCKET_NAME }; LOGD("In clientSocketThreadNative() : Before creating socket"); sk = socket(PF_LOCAL, SOCK_STREAM, 0); if (sk < 0) { err = errno; LOGD("%s: Cannot open socket: %s (%d)\n", __FUNCTION__, strerror(err), err); errno = err; return; } LOGD("In clientSocketThreadNative() : Before connecting to Java LocalSocketServer"); if (connect(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { err = errno; LOGD("%s: connect() failed: %s (%d)\n", __FUNCTION__, strerror(err), err); close(sk); errno = err; return; } LOGD("In clientSocketThreadNative() : Connecting to Java LocalSocketServer succeed"); while(!stopThread){ result = write(sk, buffer, 8); LOGD("In clientSocketThreadNative() : Total write = %d", result); count++; if(4 == count){ sleep(1); count = 0; } } LOGD("In clientSocketThreadNative() : End"); } Any suggestion would be greatly appreciated !!! A: Looking at local_socket_client.c in the Android source, it looks like they do this: int socket_make_sockaddr_un(const char *name, int namespaceId, struct sockaddr_un *p_addr, socklen_t *alen) { memset (p_addr, 0, sizeof (*p_addr)); size_t namelen; switch (namespaceId) { case ANDROID_SOCKET_NAMESPACE_ABSTRACT: namelen = strlen(name); // Test with length +1 for the *initial* '\0'. if ((namelen + 1) > sizeof(p_addr->sun_path)) { goto error; } /* * Note: The path in this case is *not* supposed to be * '\0'-terminated. ("man 7 unix" for the gory details.) */ p_addr->sun_path[0] = 0; memcpy(p_addr->sun_path + 1, name, namelen); ... p_addr->sun_family = AF_LOCAL; *alen = namelen + offsetof(struct sockaddr_un, sun_path) + 1; It seems like the memset() is important because the entire sun_path is relevant. (looks like you cover that part with your structure initialization, though.) And it's not "0" plus the original name, it's an actual zero byte! (its value is all binary zeroes, not an ascii '0') Try following more closely what they're doing, including the leading '\0' byte and the AF_LOCAL family. If you have updated code (whether it works or not) please post it! I'm interested in your results. Did you ever get this to work? If it doesn't work, find out what errno is and either call perror() to print it to stderr, or call strerror() and log the output. Let us know what error you get. Edit I recently solved this problem in a project of my own. I found that the key was to specify the correct length when calling connect() and bind(). In the code I posted above, it calculates the length by using the offset of the sun_path in the structure, plus the length of the name, plus one for the leading '\0' byte. If you specify any other length, Java code might not be able to connect to the socket. A: The following code might not be perfect but it works !!! Thanks for Mike. Java part (Socket Server) : package test.socket; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.net.LocalServerSocket; import android.net.LocalSocket; import android.net.LocalSocketAddress; import android.os.Bundle; import android.util.Log; import android.view.View; public class TestSocketActivity extends Activity { public static String SOCKET_ADDRESS = "/test/socket/localServer"; public String TAG = "Socket_Test"; static{System.loadLibrary("testSocket");} private native void clientSocketThreadNative(); private native void setStopThreadNative(); localSocketServer mLocalSocketServer; localSocketClient mLocalSocketClient; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mLocalSocketServer = new localSocketServer(); mLocalSocketClient = new localSocketClient(); } /* LocalSocketServer */ public class localSocketServer extends Thread { int bufferSize = 32; byte[] buffer; int bytesRead; int totalBytesRead; int posOffset; LocalServerSocket server; LocalSocket receiver; InputStream input; private volatile boolean stopThread; public localSocketServer() { Log.d(TAG, " +++ Begin of localSocketServer() +++ "); buffer = new byte[bufferSize]; bytesRead = 0; totalBytesRead = 0; posOffset = 0; try { server = new LocalServerSocket(SOCKET_ADDRESS); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "The localSocketServer created failed !!!"); e.printStackTrace(); } LocalSocketAddress localSocketAddress; localSocketAddress = server.getLocalSocketAddress(); String str = localSocketAddress.getName(); Log.d(TAG, "The LocalSocketAddress = " + str); stopThread = false; } public void run() { Log.d(TAG, " +++ Begin of run() +++ "); while (!stopThread) { if (null == server){ Log.d(TAG, "The localSocketServer is NULL !!!"); stopThread = true; break; } try { Log.d(TAG, "localSocketServer begins to accept()"); receiver = server.accept(); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "localSocketServer accept() failed !!!"); e.printStackTrace(); continue; } try { input = receiver.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "getInputStream() failed !!!"); e.printStackTrace(); continue; } Log.d(TAG, "The client connect to LocalServerSocket"); while (receiver != null) { try { bytesRead = input.read(buffer, posOffset, (bufferSize - totalBytesRead)); } catch (IOException e) { // TODO Auto-generated catch block Log.d(TAG, "There is an exception when reading socket"); e.printStackTrace(); break; } if (bytesRead >= 0) { Log.d(TAG, "Receive data from socket, bytesRead = " + bytesRead); posOffset += bytesRead; totalBytesRead += bytesRead; } if (totalBytesRead == bufferSize) { Log.d(TAG, "The buffer is full !!!"); String str = new String(buffer); Log.d(TAG, "The context of buffer is : " + str); bytesRead = 0; totalBytesRead = 0; posOffset = 0; } } Log.d(TAG, "The client socket is NULL !!!"); } Log.d(TAG, "The LocalSocketServer thread is going to stop !!!"); if (receiver != null){ try { receiver.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (server != null){ try { server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void setStopThread(boolean value){ stopThread = value; Thread.currentThread().interrupt(); // TODO : Check } } /* Client native socket */ public class localSocketClient extends Thread { private volatile boolean stopThread; public localSocketClient(){ Log.d(TAG, " +++ Begin of localSocketClient() +++ "); stopThread = false; } public void run(){ Log.d(TAG, " +++ Begin of run() +++ "); while(!stopThread){ clientSocketThreadNative(); } } public void setStopThread(boolean value){ stopThread = value; setStopThreadNative(); Thread.currentThread().interrupt(); // TODO : Check } } public void bt_startServerOnClick(View v) { mLocalSocketServer.start(); } public void bt_startClientOnClick(View v) { mLocalSocketClient.start(); } public void bt_stopOnClick(View v) { mLocalSocketClient.setStopThread(true); mLocalSocketServer.setStopThread(true); } } Native C part (Client) #include <stdlib.h> #include <errno.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <sys/un.h> #include "test_socket_TestSocketActivity.h" #define LOCAL_SOCKET_SERVER_NAME "/test/socket/localServer" volatile int stopThread; #ifndef __JNILOGGER_H_ #define __JNILOGGER_H_ #include <android/log.h> #ifdef __cplusplus extern "C" { #endif #ifndef LOG_TAG #define LOG_TAG "NativeSocket" #endif #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,LOG_TAG,__VA_ARGS__) #define LOGS(...) __android_log_print(ANDROID_LOG_SILENT,LOG_TAG,__VA_ARGS__) #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__) #ifdef __cplusplus } #endif #endif /* __JNILOGGER_H_ */ JNIEXPORT void JNICALL Java_test_socket_TestSocketActivity_clientSocketThreadNative (JNIEnv *env, jobject object){ LOGD("In clientSocketThreadNative() : Begin"); stopThread = 0; int sk, result; int count = 1; int err; char *buffer = malloc(8); int i; for(i = 0; i<8; i++){ buffer[i] = (i+1); } struct sockaddr_un addr; socklen_t len; addr.sun_family = AF_LOCAL; /* use abstract namespace for socket path */ addr.sun_path[0] = '\0'; strcpy(&addr.sun_path[1], LOCAL_SOCKET_SERVER_NAME ); len = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(&addr.sun_path[1]); LOGD("In clientSocketThreadNative() : Before creating socket"); sk = socket(PF_LOCAL, SOCK_STREAM, 0); if (sk < 0) { err = errno; LOGD("%s: Cannot open socket: %s (%d)\n", __FUNCTION__, strerror(err), err); errno = err; return; } LOGD("In clientSocketThreadNative() : Before connecting to Java LocalSocketServer"); if (connect(sk, (struct sockaddr *) &addr, len) < 0) { err = errno; LOGD("%s: connect() failed: %s (%d)\n", __FUNCTION__, strerror(err), err); close(sk); errno = err; return; } LOGD("In clientSocketThreadNative() : Connecting to Java LocalSocketServer succeed"); while(!stopThread){ result = write(sk, buffer, 8); LOGD("In clientSocketThreadNative() : Total write = %d", result); count++; if(4 == count){ sleep(1); count = 0; } } LOGD("In clientSocketThreadNative() : End"); } JNIEXPORT void JNICALL Java_test_socket_TestSocketActivity_setStopThreadNative (JNIEnv *env, jobject object){ stopThread = 1; } A: Confirmed that the above works properly. The following examples will not only work together, but will work with the corresponding Android LocalSocket and LocalServerSocket classes: Client side (Android is server using LocalServerSocket): #include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */ #include <sys/un.h> /* struct sockaddr_un */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #include <errno.h> #include <stddef.h> #define RCVBUFSIZE 2048 /* Size of receive buffer */ void DieWithError(char *errorMessage) /* Error handling function */ { fprintf(stderr, "Error: %s - %s\n", errorMessage, strerror(errno)); exit(errno); } int main(int argc, char *argv[]) { int sock; /* Socket descriptor */ struct sockaddr_un echoServAddr; /* Echo server address */ unsigned char *localSocketName = "MyTestSocket"; static unsigned char echoString[] = {0x80, 0x00, 0x0e, 0x10, 0x00, 0x9c, 0x40, 0xc9, 0x20, 0x20, 0x20, 0x32, 0x00, 0x00}; static unsigned int echoStringLen = sizeof(echoString); /* Length of string to echo */ unsigned char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ int size; int i; /* Create a reliable, stream socket using Local Sockets */ if ((sock = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) DieWithError("socket() failed"); /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sun_family = AF_LOCAL; /* Local socket address family */ /** * Tricky and obscure! For a local socket to be in the "Android name space": * - The name of the socket must have a 0-byte value as the first character * - The linux man page is right in that 0 bytes are NOT treated as a null terminator. * - The man page is not clear in its meaning when it states that "the rest of the bytes in * sunpath" are used. "Rest of bytes" is determined by the length passed in for * sockaddr_len and Android sets this per the recommended file-system sockets of * sizeof(sa_family_t) + strlen(sun_path) + 1. This is important when making calls * to bind, connect, etc! * We have initialized the struct sockaddr_un to zero already, so all that is needed is to * begin the name copy at sun_path[1] and restrict its length to sizeof(echoServAddr.sun_path)-2 **/ strncpy(echoServAddr.sun_path + 1, localSocketName, sizeof(echoServAddr.sun_path) - 2); size = sizeof(echoServAddr) - sizeof(echoServAddr.sun_path) + strlen(echoServAddr.sun_path+1) + 1; /* Establish the connection to the echo server */ if (connect(sock, (struct sockaddr *) &echoServAddr, size) < 0) DieWithError("connect() failed"); /* Send the string to the server */ if (send(sock, echoString, echoStringLen, 0) != echoStringLen) DieWithError("send() sent a different number of bytes than expected"); /* Receive the same string back from the server */ totalBytesRcvd = 0; printf("Sent: "); for (i = 0; i < echoStringLen; i++) printf("%02X ", echoString[i]); printf("\n"); /* Print a final linefeed */ printf("Received: "); /* Setup to print the echoed string */ if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0) DieWithError("recv() failed or connection closed prematurely"); for (i = 0; i < bytesRcvd; i++) printf("%02X ", echoBuffer[i]); printf("\n"); /* Print a final linefeed */ close(sock); exit(0); } Server side (Android is client using LocalSocket): #include <stdio.h> /* for printf() and fprintf() */ #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */ #include <sys/un.h> /* struct sockaddr_un */ #include <stdlib.h> /* for atoi() and exit() */ #include <string.h> /* for memset() */ #include <unistd.h> /* for close() */ #include <errno.h> #include <stddef.h> #define RCVBUFSIZE 2048 /* Size of receive buffer */ void DieWithError(char *errorMessage) /* Error handling function */ { fprintf(stderr, "Error: %s - %s\n", errorMessage, strerror(errno)); exit(errno); } void HandleLocalClient(int clntSocket) { char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ int recvMsgSize; /* Size of received message */ /* Receive message from client */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithError("recv() failed"); /* Send received string and receive again until end of transmission */ while (recvMsgSize > 0) /* zero indicates end of transmission */ { /* Echo message back to client */ if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize) DieWithError("send() failed"); /* See if there is more data to receive */ if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0) DieWithError("recv() failed"); } close(clntSocket); /* Close client socket */ } #define MAXPENDING 5 /* Maximum outstanding connection requests */ void DieWithError(char *errorMessage); /* Error handling function */ void HandleLocalClient(int clntSocket); /* TCP client handling function */ int main(int argc, char *argv[]) { int servSock; /* Socket descriptor for server */ int clntSock; /* Socket descriptor for client */ struct sockaddr_un echoClntAddr; /* Client address */ unsigned int clntLen; /* Length of client address data structure */ struct sockaddr_un echoServAddr; /* Echo server address */ unsigned char *localSocketName = "MyTestSocket"; static unsigned int echoStringLen = 14; /* Length of string to echo */ unsigned char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */ int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv() and total bytes read */ int size; int i; /* Create a reliable, stream socket using Local Sockets */ if ((servSock = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) DieWithError("socket() failed"); /* Construct the server address structure */ memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */ echoServAddr.sun_family = AF_LOCAL; /* Local socket address family */ /** * Tricky and obscure! For a local socket to be in the "Android name space": * - The name of the socket must have a 0-byte value as the first character * - The linux man page is right in that 0 bytes are NOT treated as a null terminator. * - The man page is not clear in its meaning when it states that "the rest of the bytes in * sunpath" are used. "Rest of bytes" is determined by the length passed in for * sockaddr_len and Android sets this per the recommended file-system sockets of * sizeof(sa_family_t) + strlen(sun_path) + 1. This is important when making calls * to bind, connect, etc! * We have initialized the struct sockaddr_un to zero already, so all that is needed is to * begin the name copy at sun_path[1] and restrict its length to sizeof(echoServAddr.sun_path)-2 **/ strncpy(echoServAddr.sun_path + 1, localSocketName, sizeof(echoServAddr.sun_path) - 2); size = sizeof(echoServAddr) - sizeof(echoServAddr.sun_path) + strlen(echoServAddr.sun_path+1) + 1; /* Bind to the local address */ if (bind(servSock, (struct sockaddr *) &echoServAddr, size) < 0) DieWithError("bind() failed"); /* Mark the socket so it will listen for incoming connections */ if (listen(servSock, MAXPENDING) < 0) DieWithError("listen() failed"); for (;;) /* Run forever */ { /* Set the size of the in-out parameter */ clntLen = sizeof(echoClntAddr); /* Wait for a client to connect */ if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) DieWithError("accept() failed"); /* clntSock is connected to a client! */ printf("Handling client\n"); HandleLocalClient(clntSock); } /* NOT REACHED */ return 0; } Tested with Android 4.0.3 ICS 03/15 A: Thanks for the answers here. Piecing people's responses together, the things to be careful about are On the native side: * *the name of the socket must have a 0-byte value as the first character *The linux man page is right in that 0 bytes are NOT treated as a null terminator. *The man page is not clear in its meaning when it states that "the rest of the bytes in sunpath" are used. "Rest of bytes" is determined by the length passed in for sockaddr_len and Android sets this per the recommended file-system sockets of sizeof(sa_family_t) + strlen(sun_path) + 1. This is important when making calls to bind, connect, etc! On the Java side: Android defines the conventions it uses under the covers but are consistent with above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Change CSS value when page has loaded? Is it possible to change a value of a css style after the page has finished loading? For example I need to change a division that is display:block to display:none after the page has finished loading? Is this possible in jQuery and if so how do I implement it? A: Checkout the ready() event, and the css() method. Look at the list of possible selectors to see how to target your element. $(document).ready(function () { $('selectorForYourElement').css('display', 'none'); }); Edit: To answer your question, you can either combine the selector with the :gt() selector, or use the slice() method (preferred). $(document).ready(function () { $('selectorForYourElement').slice(1).css('display', 'none'); }); Or $(document).ready(function () { $('selectorForYourElement:gt(0)').css('display', 'none'); }); A: $('selector').css({ display: 'none' }); A: Give the block an id f.e. hideMe and do this in jQuery: $(document).ready(function(){$("#hideMe").hide();});
{ "language": "en", "url": "https://stackoverflow.com/questions/7516028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Objective-c Changing UIImagePickerController to video mode I have an application which I want onlt to show in the background the video source from the camera. I have the following code in my viewcontroller: #if !TARGET_IPHONE_SIMULATOR imagePickerController = [[UIImagePickerController alloc] initWithRootViewController:self]; imagePickerController.delegate = self; imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; imagePickerController.navigationBarHidden = YES; imagePickerController.toolbarHidden = NO; imagePickerController.showsCameraControls = NO; //... [self.view addSubview:self.imagePickerController.view]; [imagePickerController viewWillAppear:YES]; [imagePickerController viewDidAppear:YES]; #endif //... [self.view addSubview:otherthings]; Then I add other views on top and I have sounds too. However I changed the imagepicker mode to video but it freezes when a sound plays. here's what i changed: #if !TARGET_IPHONE_SIMULATOR imagePickerController = [[UIImagePickerController alloc] init];//initWithRootViewController:self]; imagePickerController.delegate = self; imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera]; NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(SELF contains %@)", @"movie"]]; BOOL movieOutputPossible = (videoMediaTypesOnly != nil); if (movieOutputPossible) { imagePickerController.mediaTypes = videoMediaTypesOnly; imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh; imagePickerController.navigationBarHidden = YES; imagePickerController.toolbarHidden = YES; imagePickerController.showsCameraControls = NO; } #endif Anyone knows why the camera pickers freezes when a sound plays? The sound is an AVAudioPlayer by the way. A: Solution: Use AVFOundation instead of UIImagePickerController. videoBackground = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)]; AVCaptureSession *session = [[AVCaptureSession alloc] init]; session.sessionPreset = AVCaptureSessionPresetMedium; CALayer *viewLayer = videoBackground.layer; NSLog(@"viewLayer = %@", viewLayer); AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session]; captureVideoPreviewLayer.frame = videoBackground.bounds; [videoBackground.layer addSublayer:captureVideoPreviewLayer]; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; NSError *error = nil; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error]; if (!input) { // Handle the error appropriately. NSLog(@"ERROR: trying to open camera: %@", error); } [session addInput:input]; [session startRunning]; [self.view addSubview:videoBackground];
{ "language": "en", "url": "https://stackoverflow.com/questions/7516029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: background process and UI interaction I am working on an application that is receiving XMPP notifications using the Matrix SDK. As well I am using async web service calls to receive an initial set of data from the server. Now, I am aware that with Mango I can close the app or move it to the background and have a background task that is able to be run every 30 mins (or so) for 15sec max which obviosuly means the XMPP push isn't going to work in this scenario. Is there any way to get background apps to execute more frequently than this? Failing that for the syncing process all I can do is every 30 mins use a web service call to get any updates and store into Isolated storage for my app to pick up when it's next run. But I believe I cannot use any UI from a background task so cannot tell the user of updates? So, if I get an important message can I somehow override the slowness here and force my app to run and inform the user visibly that something has happened and he needs to look at it? Is this where push notifications come in? A: You can use the ShellTile API to update the application's tile on the Start screen, or use the ShellToast API to show a toast to the user. Both of these can be configured to launch into a specific part of your application (deep-linking) when tapped. If you need a constant monitoring/update/notification system for your application when it's not running, then using push notifications is probably the more appropriate approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with digest authentication with http.client in Node.js I try to implement digest request when using http.get and get "Digest authentication failed" message every time :( var hashlib = require('hashlib'), http = require('http'), url = require('url'), qs = require('querystring'), hashlib = require('hashlib'); var username = 'user'; var password = 'pass'; var options = { 'host' : 'username.livejournal.com', 'path' : '/data/rss?auth=digest' }; http.get(options, function(res) { res.setEncoding('utf-8'); // got 401, okay res.on('data', function(chunk) { var authResponseParams = qs.parse(res.headers['www-authenticate'].substr(7), ', '); // cut "Digest " var ha1 = hashlib.md5(username + ':' + authResponseParams.realm + ':' + password); var ha2 = hashlib.md5('GET:' + options.path); var response = hashlib.md5(ha1 + ':' + authResponseParams.nonce + ':1::auth:' + ha2); var authRequestParams = { 'username' : username, 'realm' : authResponseParams.realm, 'nonce' : authResponseParams.nonce, 'uri' : options.path, 'qop' : authResponseParams.qop, 'nc' : '1', 'cnonce' : '', 'response' : response }; options.headers = { 'Authorization' : 'Digest ' + qs.stringify(authRequestParams, ',') }; http.get(options, function(res) { res.setEncoding('utf-8'); res.on('data', function(chunk) { console.log(chunk); }); }); }); }).on('error', function(e) { console.log('Got error: ' + e.message); }); What's the problem with this code? A: A couple of things: * *The callback in res.on('data', fn) isn't necessarily invoked because the response doesn't necessarily contain a body, only headers. So use res.on('end', fn) instead. *Parsing the Digest header resulted in a very peculiar object, since the params can be quoted and can contain spaces (which get escaped). *Same deal for writing the Authentication header. Here's a version that worked for me: var hashlib = require('hashlib'), http = require('http'), _ = require('underscore') var username = 'user'; var password = 'pwd'; var options = { 'host' : 'host', 'path' : '/path' }; http.get(options, function(res) { res.setEncoding('utf-8'); res.on('end', function() { var challengeParams = parseDigest(res.headers['www-authenticate']) var ha1 = hashlib.md5(username + ':' + challengeParams.realm + ':' + password) var ha2 = hashlib.md5('GET:' + options.path) var response = hashlib.md5(ha1 + ':' + challengeParams.nonce + ':1::auth:' + ha2) var authRequestParams = { username : username, realm : challengeParams.realm, nonce : challengeParams.nonce, uri : options.path, qop : challengeParams.qop, response : response, nc : '1', cnonce : '', } options.headers = { 'Authorization' : renderDigest(authRequestParams) } http.get(options, function(res) { res.setEncoding('utf-8') var content = '' res.on('data', function(chunk) { content += chunk }).on('end', function() { console.log(content) }) }); }); }) function parseDigest(header) { return _(header.substring(7).split(/,\s+/)).reduce(function(obj, s) { var parts = s.split('=') obj[parts[0]] = parts[1].replace(/"/g, '') return obj }, {}) } function renderDigest(params) { var s = _(_.keys(params)).reduce(function(s1, ii) { return s1 + ', ' + ii + '="' + params[ii] + '"' }, '') return 'Digest ' + s.substring(2); } A: Unable to npm install hashlib, I used the Crypto module in Node to create md5 hashes. var ha1 = crypto.createHash('md5').update(new Buffer(username + ':' + challengeParams.realm + ':' + password)).digest('base64');
{ "language": "en", "url": "https://stackoverflow.com/questions/7516036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best Practice for flex consuming Java web services We are planning to use flex and Java Web Services, what is the best practice to consume web service from flex is it better to directly call the web service from Action scripts or to use remoting where java client will call the web services and later flex using remoting will the java client? A: Since Flex provides connection to web services why would want to you use a java client. Anyway, the best way to connect java and flex, IMHO, would be to use blazeds, either you're using webservices or another connection method. In case you are using spring framework, you should take a look at spring flex integration
{ "language": "en", "url": "https://stackoverflow.com/questions/7516040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MongoDB GridFS store multiple sizes of image or use on the fly resizing In my web app i'm using MongoDB GridFS to store user uploaded images. The rest of the site is managed by MySQL. In a photo table (in mysql) I have three fields for storing the MongoId of the file object. * *small *medium *large So I store three versions of the image. Small, medium and large. My question is, sometimes i'll need to use a thumbnail smaller than the 'small' version of the image (i.e. in a widget box, message avatars etc.) or i'll need to use a slighly smaller version of the medium image. So my question, would it better to just store one image in the GridFS system and then have one field in the photo table storing the MongoID and then create a script that resizes the image on the fly (i.e. http://localhost/image/fetch/{mongoid}?resize=50 Otherwise, in my db i'll need thumbnail_50, thumbnail_100, medium_300, medium_400 etc. etc. What would be the implications of going down the on-the-fly resize route? is it a bad or a good idea? What would you do? Thanks. A: Resizing on the fly will result in far more CPU load on your server than resizing to a variety of sizes once, and storing the results. On the other hand, resizing ahead of time may result in a larger set of data to be stored in GridFS. In other words, it's a tradeoff. You could consider a hybrid approach, where you resize on the fly but save the results back to GridFS so that you don't need to resize any one image to a given size more than once. You should also know that HTML and CSS allow various options for controlling the displayed size of an image. For example: <img src="/path/to/image.jpg" width="50"/> Will result in an image scaled proportionally to 50 pixels wide (in most modern browsers, at any rate). You can also use the width and max-width CSS properties to control image size. For myself, and knowing nothing about the volume or file size of the images you'll be storing, I'd probably resize when images are added -- in other words, take the page speed and CPU load hit once -- and then serve the various sizes out of GridFS, using max-width to control the on-screen size if a slightly different size is required in one particular case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Which is better for provisioning sub-domains on Azure - wildcard CNAME or an API-based DNS like Route 53? I am building an application on Azure that requires the use of subdomains for each customer. Subdomains will be provisioned during the registration process. Since Azure requires the use of CNAME for DNS resolution, I must decide between a wildcard CNAME or should I add each entry manually using an API such as Amazon Route 53 I am concerned about wildcard CNames because there is some question of whether or not they are fully supported by all DNS systems. I see that it is part of the RFC spec, but I am worried about how up to date all the DNS systems are. Alternatively, I'm worried about provisioning new CNAME DNS entries for customers in real time. Would they have to wait for the TTL to expire, or would new subdomain CNAME entries be picked up immediately? Thanks, Doug A: I don't know about how many DNS systems support wildcards, but I do know that DNS caches failures. So if a user requests the new domain before you have provisioned it (or perhaps requests anything from the base domain) then he will need to wait up to TTL before he can see the new entry. A: DNS wildcards is like meta-information to your DNS server. It never leaves the nameserver, and simply directs your server to treat DNS queries a certain way. Your DNS clients, or their recursive resolvers don't know, don't need to know, and can't tell* that you're using a CNAME with a wildcard. That Serverfault link you have just means you will have a harder time finding a host that you can add a wildcard to. If Amazon Route 53 supports wildcard for CNAMES then that is fine for production, assuming the rest of the server complies with the other DNS RFCs. The only other time you should care about wildcard support is if you use secondary NS records at a different provider. Regarding the TTL, there are two TTLs to pay attention to: the TTL of the wildcard CNAME or static CNAME you create. Then there is the A record TTL that is stored on Microsoft's name servers and you can't control this one. (you also can't control MSFT's NXDOMAIN expiry in the SOA record, but that is a tangent) You need to consider that when switching between Prod and DEV that there will be clients caching the A record of the former up until the A record expires. If you're using a mobile app, then I've seen cellular ISP's cache this entry longer than expected, and some phones to cache the A record longer too. Sometimes the way to fix this is to reboot the phone. Bottom line is don't worry about CNAME TTL, it's the A record that matters and MSFT owns this. Do a dig or NSlookup to see the value. If you find a NameServer that supports wildcards, go ahead an use it, but I'd be worried about security and compatibility with other RFCs. I really only trust the DNS provider of my ISP (ATT), UltraDNS, and Dynect. Amazon and UltraDNS have a good relationship. All except ATT has a SOAP API. If you want to use ATT, you can use them (or another ISP) as a secondary DNS server and make that the primary NameServer. Then make all your changes to the hidden Master DNS. I geek out on DNS so feel free to ask follow up questions. *Footnote: They can tell if you are using a CNAME by querying RandomGUID.domain.com If they get the same Answer then they can assume you're using a wildcard CNAME.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authenticate communication to backend from iOS I have a backend that handles requests to a database. My apps do not talk directly to the database for security reasons. How would I make sure that only my apps talk to the backend on my server? I do not want other people querying my backend and try to access data. I only want my apps, that I build, to talk to it. Do I add something like Oauth or use certs? What is the best way for iOS apps (or any apps in general) do talk to a backend? A: You're asking how an application installed on an iOS device can authenticate itself against your server. How do you identify your users? If you can identify your users, the program could on the first start connect to your server, provide username/pass and get "secret" token. With this token, it can access the backend. You can store that token or not. If you provide any kind of key in your app, it will be identical to every installation and easy to fetch from the app. A: In Applicasa every app has its "space" So only your apps talk to the DB (each one to its own space) www.applicasa.com A: You can use an authorization mechanism such as OAuth. Or you can build your own. It can be as simple as having a secret token/key. And you can keep it just as simple or you can start making it more complex (i.e. generating hashes with the token and the parameters in order to not send the token itself but a hash calculated with the token and the request parameters, etc). However there is no way to keep the api tokens secret. Because an attacker can decompile your app, introspect the code and find your api key. You could check some http headers but faking the request headers is super simple. So you cannot guarantee that the requests are made from the iOS device. It would be great if Apple provided a way to store something during the installation process that is signed with your developer certificate or something like that so you can keep something actually secret you can trust in the iOS device. But in the end someone would just sniff the network traffic to crack your authorization system. So you can do things very complex but you cannot guarantee that the requests are always made from your device.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook achievement does not show image in the ticker I have added some achievements to my FB app. Everything works fine, but the images of the achievements are not shown in the ticker. I checked the achievements with the URL Linter and the image property seems to be valid. Does it take some time for Facebook to upload my images in their own system or have I made a mistake? The images in the ticker have a URL but at this URL is no picture, when it should display the picture of the achievement. Here is link to my app. A: I have found the answer to my question: Facebook does not use the images from a https recource. I used this: <meta property="og:image" content="http://imgurl.png"/> instead of this: <meta property="og:image" content="https://imgurl.png"/> and it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Escaping double-quote in `delims` option of `for /F` I'm having a bit of trouble with a batch script which needs to parse a value out of an config file into a variable. Suitably anonymised, the relevant line of the file looks like <?define ProductShortName="Foo" ?> I want to set a variable to Foo. The string ProductShortName is unique enough to get the line with findstr, but then I have to extract the value. The correct approach seems to be for /F, but all of the following give errors: for /F "delims=^" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`) for /F "delims="" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`) for /F "delims=\" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`) for /F 'delims=^" usebackq' %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`) for /F 'delims=" usebackq' %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`) for /F "delims=" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`) mostly along the lines of usebackq" %G in (`findstr /L "ProductShortName" "C:\foo\bar\Installer\Branding.wxi"`) was unexpected at this time. What's the correct way of escaping it to split the string on "? A: EDIT: This is wrong, see my comment later: As Joey said, there seems no possibility to use the quote as delim, it can be only used as EOL character. This seems to be an effect of the FOR-LOOP parser of cmd.exe, as it scans the options-part and stops scanning it after an quote, only the EOL= option breaks this, as it read always the next character without any expection. You can solve it with a workaround like icabod. The solution is to replace the quotes with an unused character, but if you want to accept any character inside the quotes there isn't an unused character. So my solution first creates an unused character, by replacing all previous occurences. I want to use the # to replace the quotes, ut to preserve all # inside the quotes a replace it before with $R, but then it can collides with an existing $R in the text, therefore I first replace all $ with $D, then it is absolutly collision free. After extracting the "quoted" text, I have to replace the $R and $D back to their original values, that's all. @echo off setlocal EnableDelayedExpansion for /F "tokens=1,2" %%1 in ("%% #") DO ( for /f "tokens=* usebackq" %%a in ("datafile.txt") do ( set "z=%%a" set "z=!z:$=$D!" set "z=!z:#=$R!" set "z=!z:"=#!" for /f "tokens=1-3 delims=#" %%a in ("!z!") do ( set "value=%%b" if defined value ( set "value=!value:$R=#!" set "value=!value:$D=$!" echo result='!value!' ) ) ) ) Sample text: <?define ProductShortName="Two #$* $D $R" ?> results to Two #$* $D $R as expected EDIT: There is a way! I always tested things like this (and it fails) setlocal EnableDelayedExpansion set "var=one"two"three" FOR /F ^"tokens^=1-3^ delims^=^"^" %%a in ("!var!") do echo %%a--%%b--%%c But removing the first quote, it works. setlocal EnableDelayedExpansion set "var=one"two"three" FOR /f tokens^=1-3^ delims^=^" %%a in ("!var!") do echo %%a--%%b--%%c A: I don't believe this is possible - a quote (") can't be used as a delimiter. However one solution is to store the whole line in an environment variable, and use the built-in "replace" functionality of set to replace the quote with something else - for example _. You can then use another for loop on just this line to split on the new delimiter: setlocal EnableDelayedExpansion for /f "tokens=* usebackq" %%a in (`...`) do ( set z=%%a set z=!z:"=_! for /f "tokens=1-3 delims=_" %%a in ("!z!") do echo %%b ) A little explanation... the first for loop gets the entire line into the %a variable. This is then copied into variable z. z is then set again using sets' built-in search/replace functionality (note that here we're referencing the variable using !z:"=_!, which does the replacement). Finally we parse this single line to get the item between the quotes. I hope that makes some kind of sense. A: You can use the double quotation mark as a delimiter with syntax like: FOR /F delims^=^"^ tokens^=2 %G IN ('echo I "want" a "pony"') DO @ECHO %G When run on the command line, using tokens^=2 should give you want, and 4 tokens gets you a pony. Applying the technique to your original question, this should work in your batch file: FOR /F delims^=^"^ tokens^=2 %%G IN ('FINDSTR /L "ProductShortName" "data.txt"') Details I'm no expert on quirks of the command line parser, but it may help to think of the usual "delims=blah tokens=blah" as a single, combined argument passed to FOR. The caret escaping trick in delims^=blah^ tokens^=blah bypasses the need for enclosing quotes while still treating the sequence as a single argument. I've used a bit of creative analogy here, and the effect isn't universal across the shell. E.g. you can't do dir C:^\Program^ Files (which makes sense since ^ is a valid filename character). Test Cases With sufficient escaping, you can quickly check your original sample on the command line: FOR /F delims^=^"^ tokens^=2 %G IN ('echo ^^^<?define ProductShortName="Foo" ?^^^>') DO @ECHO %G Others playing with this may want to create a file testcases.txt: blah blah "red" blah "green" blah How about a "white" "unicorn"? and run something like: FOR /F delims^=^"^ tokens^=2 %G IN (testcases.txt) DO @ECHO %G to check results for a variety of inputs. In this case it should yield: red green white One last example: FOR /F delims^=^"^ tokens^=2 %G IN ('FINDSTR /L "unicorn" "testcases.txt"') ^ DO @ECHO The unicorn is %G. Finally, note my testing for this was done on Windows Server 2003. A: I haven't found a way for that to be possible. Maybe jeb chimes in with more in-depth knowledge than I have. Alternatively, chop up the line using = and space as delimiters and just remove the quotes around the result: for /f "tokens=3 usebackq delims== " %G in (`...`) do @echo %~G A: I think that it is mostly easier to search for the characters that surround the quotes and strip the quote off in a later step. If we want to extract the values from a certain line in an XML file <line x0="745" y0="1162" x1="1203" y1="1166"/> We proceed like this SETLOCAL ENABLEDELAYEDEXPANSION FOR /F "tokens=3,5,7,9 delims==/ " %%i IN ('FINDSTR line %1') DO ( SET x0=%%~i SET y0=%%~j SET x1=%%~k SET y1=%%~l ) In general, quotes are no real delimiters for themselves, so this will do the trick in most cases. A: I recently had as issue similar to this. The examples in the answers are overly complex and hard to read. I ended up wrapping the command and its functionality into another CMD script and then calling it from the FOR /F. Here is an example of the command: wmic fsdir where name="C:\\some\\path\\to\\a\\folder" get creationdate The path was extracted and passed in as a variable and the output captured and set in the DO section for the FOR /F of the calling script. This lead to a more readable approach and reduced complexity. Hopes this helps someone in the future. A: Just avoid the double quote using ^ to escape all characters in the string (including spaces). This way you can add the double quote as parameter. for /F Tokens^=1^,2^-5^*^ Delims^=^" %%i in ( ... This should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Find img src and append to href I am using the jQuery Plugin Galleriffic with a content management system. I need to generate the thumbnails with jQuery. I basically need to use jQuery to look inside a div, find all the images, wrap each image in an <a> and a <li> around that. Find the img src and input it into the href of the <a>. So each image in the end will look like this: <li><a href="link to img src"><img src="image src" /></a></li> A: Perhaps something like this : $('img').each(function(){ $(this).wrap('<li><a href="' + $(this).attr('src') + '"></a></li>'); }); A: See a working demo http://jsfiddle.net/usmanhalalit/UYQqw/1/ $(function(){ $('#imgs img').each(function(){ $(this).wrap('<li><a href="'+$(this).attr('src')+'">','</a><li>') }); }); Here is the demo markup I used <img src="image src" /> <div id='imgs'> <img src="image src1" /> <img src="image src2" /> <img src="image src3" /> </div> As you said you need to look inside a div, so it will do it only for img inside #imgs div above. A: $('img').each(function(){ var parent = $(this).parent(); var a = $('<a>', { href: this.src }); $(this).appendTo(a); var li = $('<li>'); a.appendTo(li); li.appendTo(parent); }); Fiddle: http://jsfiddle.net/maniator/bAuwT/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I save data in an eav field? I have successfully installed an EAV attribute by doing $installer->addAttribute('order', 'field', etc). I also successfully run an observer when the order is saved on the sales_order_save_before / sales_order_save_after event. Now I try to put data into my field on the observer $observer->getOrder()->setMyField('someuniquestring'); I've tried doing this before save and after, in which case I add $observer->getOrder()->getResource()->save($order); After searching my entire database the unique string doesn't exist in any tables. Also if I use the getMyField() and echo it to the screen in the observer and die() it shows the value I set. Any help on how to save this into the db? A: I found the answer to my own question after quite a while debugging. At some point in time magento changed the way that data fields should be added the the order model in the database. Previously EAV fields were used but now magento just modifies the flat table itself. So in my install script I just do $installer->getConnection->addColumn($installer->getTable('sales_flat_order', 'site_license_id', 'int(1) ...'); Then in my observer before save I add $observer->getEvent()->getOrder()->setMyField($myval); That's all there is too it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to bring alert dialog when user clicks on notification? I am trying to give user an alert dialog when alarm notification of calendar is clicked by the user,How to bring alert dialog when user clicks on notification? My question is where to give alert dialog? Either in Alarmservice? or the Class extending AlarmReceiver that extends BroadCastReceiver? A: The best thing would be to call a new activity from your BroadcastReceiver. There you can do whatever you want. EDIT: This is what I mean: Intent intent = new Intent(context, SomeActivity.class); context.startActivity(intent); Now that you're calling a new activity - use it as usual... Add your AlertDialog and show it to the user A: Just create an activity and when you register it in your manifest add this tag. Have your broadcast receiver onReceiver() method launch it. <activity android:theme="@android:style/Theme.Dialog"> Also add excludeFromRecents=true or else so this way it wont show up in recent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing a SQL query over a given set of values I am trying to write a plsql query that allows me to query a set of known values that are not stored in a table. Say those known values are the following strings: * *abc *def *ghi *jkl I would like to achieve something like the following: select * from [fill-in-the-blank] myvalues where not myvalues in ( select id from dbtable ) ..where I am trying to ascertain which of those know values are not in a database table. Constraints * *This is pl/sql (oracle) *This solution must run from within Oracle PL/SQL Developer *I only have read access to the schema so I cannot create temporary tables. Any ideas? A: You could use a Common Table Expression (CTE) to accomplish this: with cte as ( select 'abc' as id from dual union all select 'def' from dual union all select 'ghi' from dual union all select 'jkl' from dual ) select * from cte where not id in ( select id from dbtable ) In fact, you may not even really need the CTE at all (though I find it aids readability): select * from ( select 'abc' as id from dual union all select 'def' from dual union all select 'ghi' from dual union all select 'jkl' from dual ) where not id in ( select id from dbtable ) A: Old thread I know, but nobody mentioned select * from table(sys.dbms_debug_vc2coll('abc','def','ghi','jkl')); You don't have to use sys.dbms_debug_vc2coll, of course. Available collection types can be listed using: select c.owner, c.type_name, c.elem_type_name, c.length from all_coll_types c where c.coll_type = 'TABLE' and c.elem_type_name = 'VARCHAR2' order by 1,2;
{ "language": "en", "url": "https://stackoverflow.com/questions/7516082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to synchronize two text box form values? Hi all i am new to jQuery. Suppose I have two HTML text boxes. How can I make it happen that if I write in text box A then same value goes to textbox B and if I write in B then it goes to A and same as delete the text. How can this be done in jQuery? A: This is quite easy: $("#textBoxA").keyup(function(){ $("#textBoxB").val($("#textBoxA").val()); }); $("#textBoxB").keyup(function(){ $("#textBoxA").val($("#textBoxB").val()); }); A: This is a more dynamic way using jQuery: $(document).ready(function() { $(".copyMe").keyup(function() { $(".copyMe").val($(this).val()); }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="copyMe" type="text" placeholder="Enter a text"/> <input class="copyMe" type="text" /> <input class="copyMe" type="text" /> <input class="copyMe" type="text" /> A: A slightly more efficient way than the most upvoted answer is: var $inputs = $(".copyMe"); $inputs.keyup(function () { $inputs.val($(this).val()); }); http://css-tricks.com/snippets/jquery/keep-text-inputs-in-sync/ A: I ran into this challenge today. I made a small plugin to make the code more readable and to handle text inputs, but also select fe. When you include the plugin, you can simply use $("selector").keepInSync($("otherselector")); $.fn.keepInSync = function($targets) { // join together all the elements you want to keep in sync var $els = $targets.add(this); $els.on("keyup change", function() { var $this = $(this); // exclude the current element since it already has the value $els.not($this).val($this.val()); }); return this; }; //use it like this $("#month1").keepInSync($("#month2, #month3")); $("#text1").keepInSync($("#text2")); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Two way sync</h1> <select id="month1"> <option value="">Please select a moth</option> <option value="jan">January</option> <option value="feb">February</option> <option value="mar">March</option> </select> <select id="month2"> <option value="">Please select a moth</option> <option value="jan">1</option> <option value="feb">2</option> <option value="mar">3</option> </select> <select id="month3"> <option value="">Please select a moth</option> <option value="jan">Jan</option> <option value="feb">Feb</option> <option value="mar">Mar</option> </select> <br> <input type="text" id="text1"> <input type="text" id="text2"> A: You'll have to put a function call on each textbox's onchange events, that will take the value of one box and put it in the other. A: Using Snicksie's method, you can see the live demo below. I have included a button to reset the textbox values as well. http://jsfiddle.net/refhat/qX6qS/5/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: Possibilities of a uml component diagram I have a question concerning the uml component diagram: as I can see in Wikipedia, it is possible to create my own "component types" like <<thin client>>, <<thick client>> etc. I thought that I can only say <<subsystem>> and <<component>>?! Are these entries stereotypes or what? I'd like to model a third-party-database like oracle or mysql. Do I have to create something like <<database>> or should I use the artifact for this? To make it more clear I added a graphic example: the "Zugriffsmanagement" (access management) uses the artifact "Drittanbieter-Datenbank" (Third-Party-Database) to store the data. Should it be <<artifact>> or <<database>> or what? Thank you! A: Yes, you can. The stereotypes are for that. You DO CAN use a stereotype that says something different that "<<subsystem>>" and "<<component>>". Of course, your "thin client" or "database", its an specialization of a "component".     +-------------------+     |  <<thin client>>  |<--------+     |  Local Database 1 |         |     +-------------------+         |                                   |                                   |                                   |     +-------------------+         |+--------------------+     |  <<thin client>>  |<--------+|  <<system>>        |     |  Local Database 2 |         ||  Finantial Server  |     +-------------------+         |+--------------------+                                   |                                   |     +-------------------+         |     |  <<database>>     |<--------+     |  North SQL Server |         |     +-------------------+         |                                   |                                   |     +-------------------+         |     |  <<database>>     |<--------+     |  Sth SQL Server   |     +-------------------+ Cheers. A: In UML you have stereotypes but also keywords. It means that you can write whatever you want with keywords and only what is available into the profile with stereotypes. My answer is therefore yes to "thin client" using keyword approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Select element's initial value I would like to initialize a select with an initial value. I have a Json object returned from my backend like this one: [{Nom:"xxx", TypeIld:1, ....},{Nom:"xxx", TypeId:1, ....}] I have an array of typeIds declared like this : [{ Nom: "Plats", TypeId: 0 }, { Nom: "Crudités", TypeId: 1 }, { Nom: "Tartes Salées", TypeId: 2}] I would like to display all my records in a table with a select for the typeId initialized to the correct value. Here is my code: <form class="PlatsCuisinesEditor"> <table data-bind="visible: platscuisines().length > 0"> <thead><tr><th></th><th>Nom</th><th>Description</th><th>Prix</th><th>Frequence</th><th>Type</th><th></th></tr></thead> <tbody data-bind='template: { name: "PCRowTemplate", foreach: platscuisines }'></tbody> </table> <br /> <div style="margin-top:10px;"> <button data-bind="enable: platscuisines().length > 0" type="submit">Enregistrer les plats</button> </div> </form> <script type="text/html" id="PCRowTemplate"> <tr> <td><input class="required" data-bind="value: Nom, uniqueName: true"/></td> <td> <select data-bind="options: viewModel.platstypes, optionsText:'Nom'"></select> </td> </tr> </script> <script type="text/javascript"> var initialData = @Html.Raw(Json.Encode(ViewBag.JsonPlats)); var dataFromServer = ko.utils.parseJson(ko.toJSON(initialData)); //var testTypesPlats = @Html.Raw(Json.Encode(ViewBag.platsTypes)); var viewModel = { platscuisines: ko.observableArray(dataFromServer), platstypes : [{ Nom: "Plats", TypeId: 0 },{ Nom: "Crudités", TypeId: 1 },{ Nom: "Tartes Salées", TypeId: 2}], }; ko.applyBindings(viewModel); </script> A: You would want to write your select like: <select data-bind="options: viewModel.platstypes, optionsText:'Nom', optionsValue: 'TypeId', value: TypeId"> </select> This tells Knockout that you want to use the TypeId property from platstypes as the value for your options and tells it to read/write the value of the field from the TypeId property of each item in platscuisines
{ "language": "en", "url": "https://stackoverflow.com/questions/7516089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Parsing string for retrieving date in bash I have s string in following format dd/MMM/YYYY:HH:mm:ss(e.g 13/Jan/2011:08:23:34) I need to convert this string to date. How can I do this? Thanks in advance A: Try GNU Date mydate='13/Jan/2011:08:23:34' date +%s -d "${mydate:3:3} ${mydate%%/*} ${mydate:7:4} ${mydate#*:}" FreeBSD Date mydate='13/Jan/2011:08:23:34' date -j -f '%d/%b/%Y:%H:%M:%S' "${mydate}" +%s Basically, with GNU date you must reformat your date into something GNU date can understand and parse. I chose a crude method (in the real world it would need to be more reliable). FreeBSD is better in this regard and allows you to specify the date format the parser should look for. A: You have to massage the date string to be valid for the date command. Given d="13/Jan/2011:08:23:34" * *epoch=$( IFS="/:"; set -- $d; date -d "$1 $2 $3 $4:$5:$6" +%s ) *d2=${d//\// } # replace slashes with spaces epoch=$( date -d "${d2/:/ }" +%s )
{ "language": "en", "url": "https://stackoverflow.com/questions/7516093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a user control after a postback within an UpdatePanel, followed by another postback - how to get the input of controls within the user control? I have a user control which is being loaded to the page dynamically after performing a postback within an UpdatePanel. Then I'm performing another postback for saving, where I would like to access the user input for the controls within that user control (for example, a grid with a checkbox in every row). A simplified example if this scenario would be something as follows: <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div><asp:Button ID="ButtonAdd" runat="server" Text="Add User Control" OnClick="ButtonAdd_OnClick" /></div> <div id="divContent" runat="server"></div> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanel ID="UpdatePanel2" runat="server"> <ContentTemplate> <div><asp:Button ID="ButtonSave" runat="server" Text="Save" OnClick="ButtonSave_OnClick" /></div> </ContentTemplate> </asp:UpdatePanel> And: protected void ButtonAdd_OnClick(object sender, EventArgs e) { MyUserControl uc = Page.LoadControl("MyUserControl.ascx") as MyUserControl; divContent.Controls.Add(uc); } protected void ButtonSave_OnClick(object sender, EventArgs e) { // Hopefully, get controls from within the user control's grid and save their input } The problem is that after the save button is clicked, the user control is gone. That's understandable and I have no problem creating and adding it again - but I do want to access the user input and save it. How can I do that? A: To access the internal controls, you have to expose them with properties or use FindControl. Also, as you mentioned, you have add dynamic controls back to the page on each postback. Dynamic Web Controls, Postbacks, and View State A: If you want to add controls programatically then choose Page_Load (more preferred) or Page_Init event. You can solve your problem by adding control "statically" (design time) with visible=false and later you may turn on its visibility. In case you want stick with current approach as in your post, you have to use a trick. MyUserControl uc; protected void Page_Load() { if(ViewState["isAdd"]!=null) { AddControl(); } } void AddControl() { uc = Page.LoadControl("MyUserControl.ascx") as MyUserControl; divContent.Controls.Add(uc); } protected void ButtonAdd_OnClick(object sender, EventArgs e) { if(ViewState["isAdd"]==null) AddControl(); ViewState["isAdd"]="yes"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Item 9 (equals contract) from Effective Java: is the example correct? Bloch's wonderful book "Effective Java" points out that if equals is not symmetric then the behavior of Collections contains is indeterminate. In the example he gives (reproduced with small modifications below), Bloch says that he sees a "false", but could just as well have seen a true or an Exception. You could see a "true" if the standard does not specify whether contains(Object o) checks e.equals(o) or o.equals(e) for each item in the collection, and the former is implemented. However, the Collections Javadoc clearly states that it has to be the latter (and it's what I observed). So the only possibilities I see are "false" or possibly an exception (but the String Javadoc seems to preclude the latter). I understand the broader point, it's likely that an asymmetric equals is will lead to problems in code outside of Collections, but I don't see it for the example he quotes. Am I missing something? import java.util.List; import java.util.ArrayList; class CIString { private final String s; public CIString(String s) { this.s = s; } @Override public boolean equals( Object o ) { System.out.println("Calling CIString.equals from " + this.s ); if ( o instanceof CIString) return s.equalsIgnoreCase( ( (CIString) o).s); if ( o instanceof String) return s.equalsIgnoreCase( (String) o ); return false; } // Always override hashCode when you override equals // This is an awful hash function (everything collides -> performance is terrible!) // but it is semantically sound. See Item 10 from Effective Java for more details. @Override public int hashCode() { return 42; } } public class CIS { public static void main(String[] args) { CIString a = new CIString("Polish"); String s = "polish"; List<CIString> list = new ArrayList<CIString>(); list.add(a); System.out.println("list contains s:" + list.contains(s)); } } A: It is early in the morning, so perhaps I am missing the true point of your question, this code will fail: public class CIS { public static void main(String[] args) { CIString a = new CIString("Polish"); String s = "polish"; List<String> list = new ArrayList<String>(); list.add(s); System.out.println("list contains a:" + list.contains(a)); } } At the very least it is odd that your code finds it and my code does not (from the point of view of sanity, not that that is clearly how your code is written :-) Edit: public class CIS { public static void main(String[] args) { CIString a = new CIString("Polish"); String s = "polish"; List<CIString> list = new ArrayList<CIString>(); list.add(a); System.out.println("list contains s:" + list.contains(s)); List<String> list2 = new ArrayList<String>(); list2.add(s); System.out.println("list contains a:" + list2.contains(a)); } } Now the code prints out: list contains s:false Calling CIString.equals from Polish list contains a:true Which still doesn't make sense... and is very fragile. If two objects are equal like a.equals(b) then they must also be equal like b.equal(a), that is not the case with your code. From the javadoc: It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. So, yes, the example in the book may be contrary to the Javadoc of the collections API, but the principle is correct. One should not create an equals method that behaves oddly or eventually problems will arise. Edit 2: The key point of the text is: In Sun’s current implementation, it happens to return false, but that’s just an implementation artifact. In another implementation, it could just as easily return true or throw a run-time exception. Once you’ve violated the equals contract, you simply don’t know how other objects will behave when confronted with your object. However, given that the Javadoc says what it says it would seem that the behaviour is fixed not an implementation artifact. If it wasn't in the javadoc, or if the javadoc is not meant to be part of the specification, then it could change at a later date and the code would no longer work. A: In the copy of the book I look at now (2nd Edition), item number is 8 and the whole section about symmetry requirement is presented pretty poorly. Particular issue you mention seem to be caused by usage code being too close to implementation, obscuring the point author is trying to make. I mean, I look at list.contains(s) and I see ArrayList and String through it and all the reasoning about returning true or throwing exception makes zero sense to me, really. * *I had to move the "usage code" further away from implementation to get the idea of how it may be: void test(List<CIString> list, Object s) { if (list != null && list.size() > 0) { if (list.get(0).equals(s)) { // unsymmetric equality in CIString assert !list.contains(s); // "usage code": list.contain(s) } } } Above looks weird but as long as list is our ArrayList and s is our String, test passes. Now, what will happen if we use something else instead of String? say, what happens if we pass new CIString("polish") as the second argument? Look, despite passing through first equals check, assertion fails at the next line - because contains will return true for this object. Similar reasoning applies for the part where Bloch mentions exception. This time, I kept the second parameter as String, but for first one, imagined an List implementation other than ArrayList (that's legal isn't it). * *You see, List implementations are generally allowed to throw ClassCastException from contains, we just need to get one that does exactly that and use it for our test. One that comes to mind could be based on TreeSet wrapped around our original list with appropriate comparator. List<CIString> wrapperWithCce(List<CIString> original, Comparator<CIString> comparator) { final TreeSet<CIString> treeSet = new TreeSet<CIString>(comparator); treeSet.addAll(original); return new ArrayList<CIString>() { { addAll(treeSet); } @Override public boolean contains(Object o) { return treeSet.contains(o); // if o is String, will throw CCE } }; } What happens if we pass list like above and String "polish" to test? list.get(0).equals(s) will still pass the check but list.contains(s) will throw ClassCastException from TreeSet.contains(). This seem to be like the case Bloch had in mind when he mentioned that list.contains(s) may throw an exception - again, despite passing through first equals check.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SQL Queries: Queries depending on previous queries and merging results Following problem: Query 2 and Query 3 depend on the results of Query 1 and Query 4 depends on the results of query 2. How would you express these queries without executing the same query multiple times? Example: Query 1 SELECT id, color, part FROM T1 Query 2 SELECT id, owner FROM T2 WHERE T2.color in (SELECT id, color, part FROM T1) Query 3 SELECT id from T3 where T3.part in (SELECT id, color, part FROM T1) Query 4 SELECT id from T4 where T4.owner in (SELECT id, owner FROM T2 WHERE T2.color in (SELECT id, color, part FROM T1)) edit At the end i need the union of the result Query1 union Query2 union Query3 union Query4 Now as you can see, I have copied and pasted the previous queries, there must be a better way of doing this. A: Just join them by the specific columns. select * from T1 inner join T2 on T1.color=T2.color inner join T3 on T3.part=T1.part inner join T4 on T4.owner=T2.owner A: Do you really need four different result sets? How many rows are you expecting in each set and what kind of entities are T1, T2, T3, T4 - because it may be possible to combine those queries into a single set. In addition, this: SELECT id, owner FROM T2 WHERE T2.color in (SELECT id, color, part FROM T1) isn't valid SQL, you probably mean: SELECT id, owner FROM T2 WHERE T2.color in (SELECT color FROM T1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7516104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Override WCF Client Methods I have a WCF service that I use in one of my applications. Everything is working just fine, but I am trying to create some test classes that have the same API, but avoid the trip to the server to get their information. For example: // Goes to the server to get a list of names. It might be a while. MyClient client = new MyClient(); string[] theNames = client.GetSpitefulUsers(); ... // This is what I would use in a test case... public FakeClient : MyClient { ... public override string[] GetSpitefulUsers() { // This returns almost immediately, but I can't just override it because the // 'MyClient' definition is generated code. return new string[] {"Aldo", "Barry", "Cassie"}; } } So what is the easiest way to provide this type of functionality without having to resort to clever hacks, mocking libraries, etc? A: WCF service reference has an interface, so all your logic should refer to that interface, not service client. In such case, you will be able to choose, what implementation(real or fake) to pass to your application logic. Let's say your WCF service interface is this: public interface IWcfInterface { string[] GetTheNames(); } And your application logic class looks like: public class ApplicationLogic { public IWcfInterface WcfInterface {get;set;} public SomeLogic() { WcfInterface.GetTheNames(); } } So in case you need real implementation, you just pass it to WcfInterface property of your application logic (usually this does dependency injection container). Fake implementation will also look simple: public FakeImplementation : IWcfInterface { public string[] GetTheNames() { return new string[] { "foo", "bar" }; } } A: if i am right the compiler will suggest to use the keyword new instead. http://msdn.microsoft.com/en-us/library/435f1dw2.aspx This msdnpage will explain how to use it. public class BaseC { public int x; public void Invoke() { } } public class DerivedC : BaseC { new public void Invoke() { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accent insensitive search in Grails How to make full text search using Grails Searchable Plugin accent insensitive ? A: I have solved this problem with help of Peter Ledbrook's post, however some effort was needed: Since latest searchable plugin uses Lucene 2.4.1 which does not contain ASCIIFoldingFilter (available since 2.9.0) and ISOLatin1AccentFilter doesn't support many languages I have created custom filter for stripping accents: import java.text.Normalizer import org.apache.lucene.analysis.Token import org.apache.lucene.analysis.TokenFilter import org.apache.lucene.analysis.TokenStream class StripAccentsFilter extends TokenFilter { StripAccentsFilter(TokenStream input) { super(input) } public final Token next(Token reusableToken) { assert reusableToken Token nextToken = input.next(reusableToken) if (nextToken) { nextToken.setTermBuffer(Normalizer.normalize(nextToken.termBuffer() as String, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")) return nextToken } return null } } and corresponding filter provider: import org.apache.lucene.analysis.TokenStream import org.compass.core.config.CompassSettings import org.compass.core.lucene.engine.analyzer.LuceneAnalyzerTokenFilterProvider class StripAccentsFilterProvider implements LuceneAnalyzerTokenFilterProvider { public void configure(CompassSettings paramCompassSettings) { } public TokenStream createTokenFilter(TokenStream paramTokenStream) { return new StripAccentsFilter(paramTokenStream) } } Now all you need to do is to register this filter provider in configuration of searchable plugin (grails-app/conf/Searchable.groovy): compassSettings = [ 'compass.engine.analyzer.default.filters': 'stripAccents', 'compass.engine.analyzer.search.filters': 'stripAccents', 'compass.engine.analyzerfilter.stripAccents.type': 'StripAccentsFilterProvider' ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7516111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SQL - count and percent hit a wall on getting a count AND a percentage of total in a single query I want the TOTAL units per location AND the PERCENT of TOTAL ACROSS ALL LOCATIONS... what I've got - is returning a 0 (zero) for percentage - I believe I have to cast the figure into a decimal or real type - but whatever i try (casting each element, or casting the whole result - i get errors...) SELECT count(I.ID) as count ,L.ID ,( count(I.ID) / ( SELECT count(I2.ID) FROM LOCATION L2 JOIN ITEM I2 ON I2.LocID = L2.ID WHERE L2.ID IN (36,38,39,40) ) ) AS percent FROM LOCATION L JOIN ITEM I ON I.LocID = L.ID WHERE L.ID IN (36,38,39,40) GROUP BY L.ID Any thoughts on how to return a decimal??? or just make it more elegant .. period? What I'd "expect" ID COUNT PERCENT 2436 362 30.47 2438 184 15.48 2439 173 14.56 2440 172 14.47 2441 151 12.71 2442 54 4.54 2702 92 7.74 ======== "t" suggested this - count(I.ID) * 100.0 / count(*) over () AS percent What is the "over()" supposed to do?? here's the return: ID COUNT PERCENT 2436 362 51 2438 184 26 2439 173 24 2440 172 24 2441 151 21 2442 54 7 2702 92 13 ========== SOLUTION SELECT count(I.ID) as count ,L.ID ,( 1.0 * count(I.ID) / ( SELECT count(I2.ID) FROM LOCATION L2 JOIN ITEM I2 ON I2.LocID = L2.ID WHERE L2.ID = L1.ID ) ) * 100 AS percent FROM LOCATION L JOIN ITEM I ON I.LocID = L.ID WHERE L.ID IN (36,38,39,40) GROUP BY L.ID A: Simply multiply by a float/decimal value SELECT count(I.ID) as count ,L.ID ,( 100.0 * count(I.ID) / ( SELECT count(I2.ID) FROM LOCATION L2 JOIN ITEM I2 ON I2.LocID = L2.ID WHERE L2.ID = L1.ID ) ) AS percent FROM LOCATION L JOIN ITEM I ON I.LocID = L.ID WHERE L.ID IN (36,38,39,40) GROUP BY L.ID Also, you'll need to consider a zero divisor giving "divide by zero" errors A: First, check if your query works and returns the right values with: SELECT count(I.ID) as count ,L.ID ,(SELECT count(I2.ID) FROM LOCATION L2 JOIN ITEM I2 ON I2.LocID = L2.ID WHERE L2.ID IN (36,38,39,40) ) FROM LOCATION L JOIN ITEM I ON I.LocID = L.ID WHERE L.ID IN (36,38,39,40) GROUP BY L.ID Then use the proper syntax for DB2 casting: CAST(%Expression% AS data-type) A: You could use the ROUND() function... ROUND(..., 2) AS percent Or just multiply by a decimal value (i.e. 1.0). You also might want to include an IF or CASE (depending on your SQL server) to get around possible zero values
{ "language": "en", "url": "https://stackoverflow.com/questions/7516116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can a Visual C++ program be compiled and run on Mac OS X or Linux? … and if so, how? Specifically, I'd like to compile and run wavdiff on Mac OS X Snow Leopard 10.6.8. As far as I can tell (which isn't very far, since I'm a total novice at C++), this was created with MS Visual C++ or similar. I'd be most grateful for answers that address the general case of compiling Visual C++ programs on Mac OS X or Linux, and that also address the specific challenge above. A: The C++ language is portable. In theory, C++ source code can be compiled to run on any platform. However, there are a few caveats to be aware of: * *behavior might be different on different platforms. The C++ standard leaves many things implementation-defined, which means that it's up to the individual platform and compiler how it should behave. For example, the size of common data types can (and will) vary across different platforms. A long is typically 64 bits wide on 64-bit Linux, but only 32-bit on 64-bit Windows. A wchar_t is 16 bits wide on Windows, but typically 32 bits on Linux. So if your code makes assumptions about implementation-defined behavior, it might not be portable (a classic example is code which assumes that a pointer can be stored into an int or unsigned int. That works great on a 32-bit machine, but on 64-bit, you end up trying to store 64 bits of data into a 32 bit wide object. *even if your code is portable, your dependencies may not be. The most obvious example is of course the OS APIs. Code which uses the Win32 API won't compile on platforms where it's not available (anywhere other than Windows). Code which relies on POSIX APIs won't compile if that's not available (Windows supports some POSIX APIs, but far from all). *C++ can mean a lot of different things. There's the ISO standardized language, which is portable, and then there's the dialect understood by individual compilers. Visual C++, GCC, and any other major C++ compiler, allow a set of language extensions which aren't part of the standard, and may not be allowed on a different compiler. If your code relies on those, it may not compile using other compilers. (For example, Visual C++ allows a non-const reference to bind to a temporary, which isn't strictly speaking allowed, and other compilers will reject it. GCC by default allows dynamically sized arrays allocated on the stack, which, again, is a non-standard extension, and which other compilers will reject.) So it depends on the code, really. Clean, high-quality code tends to be portable with little trouble. Except of course for the parts that rely directly on OS services, which will have to be rewritten for a different OS (or where a cross-platform wrapper/library may be available which can be used to do the same thing in a portable manner) A: This program can not be easily ported (recompiled without source changes). At least not without changes to the source. It holds dependencies to Windows libraries and is tied to Windows API in certain parts. The problem is not that it's coded in VC++, but that it has these dependencies. A program that is coded such that it has no platform-dependencies can be easily ported in a lot of cases by just recompiling on the target platform or with a switch to target a different platform. A: Based just on this source file, it looks as if the code itself might be reasonably portable C++. The question is whether it (or any of the classes it uses) makes use of Windows APIs that won't exist on those other platforms. The bet you can do is ask the authors what they think, or just give it a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Modify DataTables TableTools default PDF export filename at runtime I am using JQuery DataTables TableTools plugin and am defining a default filename for the PDF. However, I am using datatables with ajax, and have a date range selector, so the page isnt refreshed and therefore I am unable to provide a new default filename when then criteria changes. Does anyone know how I can change the default filename at runtime, after datatables has been initialized with table tools, i.e modify the config directly? "oTableTools": { "sSwfPath": "js/DataTables/copy_cvs_xls_pdf.swf", "aButtons": [ "copy", "csv", "xls", { "sExtends": "pdf", "sTitle": "Report Name", "sPdfMessage": "Summary Info", "sFileName": "<?php print('How do i use jquery to change this after the table has been initialized'); ?>.pdf", "sPdfOrientation": "landscape" }, "print" ] } A: I guess you want some dynamically generated name. Create a function that returns the (string) file name. function getCustomFileName(){ var docDate = $("#from").val(); var filter = $("#example_filter input").val(); var oSettings = oTable.fnSettings(); var fileName = docDate+"_"+filter; return fileName; } And use the function inside $(document).ready but outside $('#dTable').dataTable({ }). "oTableTools": { "sSwfPath": "js/DataTables/copy_cvs_xls_pdf.swf", "aButtons": [ "copy", "csv", "xls", { "sExtends": "pdf", "sTitle": "Report Name", "sPdfMessage": "Summary Info", "sPdfOrientation": "landscape" "fnClick": function( nButton, oConfig, flash ) { customName = getCustomFileName()+".pdf"; flash.setFileName( customName ); this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } }, "print" ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to debug java class file in eclipse while running the ant script? I am running the ant script from eclipse helios. Which executes the jave files in same workspace. how to debug the java code? I have put line break points and running the script in debug mode but the control is not going in java class file. It is going in ant script where i put the break points
{ "language": "en", "url": "https://stackoverflow.com/questions/7516121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making a object class name a parameter I have a TC script that handles report options for a variety of screens. The window class name changes on each screen and, as I want this script to work in a translated environment, the window caption will be changing as well. The first part works correctly but how to I account for the changing window name as well? If I remove the caption, TC bombs with an ambiguous window recognition error. Current code snippet (with the caption of one screen) : w := p.WaitWindow('*', 'Options', 1, 10000); if w.Name='frmBasicOpt' then begin .... Can I set the class name as a parameter that is fed in so I can leave out the caption? If so, how can I do this? Head... hurt. Thanks! A: Not sure I understand the task, but I will try to help to the extent of my understanding. So, the window class name is a dynamic thing, that's why you masked it with a wildcard. But you tell that you want to use the class name anyway if you are able to parameterize it. So, it seems like there is a way to get the class name during test execution from somewhere. If so, you can put the class name to a variable, and pass this variable to the WaitWindow method as a parameter, and mask the caption to avoid using language-specific captions: clsName := ....; // get it from somewhere w := p.WaitWindow(clsName, '*', 1, 10000); if w.Name='frmBasicOpt' then begin If my understanding is not correct and there is no way to know the class name beforehand, you may consider using a different approach to identify the Options window without specifying the caption. The possible solution include: * *When the dialog opens, it becomes active. So, you can get the dialog through Sys.Desktop.ActiveWindow. *If this is an MFC application, pay attention to the ControlID property of the window - it's something that can be set in the application's code, to be used for object recognition. So, you can use the FindChild method to find the window by the property value. *If the window has some child objects that are specific only to this window, you can create a function that will get all child windows of the Process object (FindAllChildren), iterate through the list and check which of them has those specific child objects. Does anything for this work for you? If not, then a little bit more information about your task could probably help me make other suggestions. Alex
{ "language": "en", "url": "https://stackoverflow.com/questions/7516130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send "{" or "}" signs through send keys method in vb 2010 I want to send { and } signs to the Active window in Visual Basic 2010.But the problem is when we send a key like "Backspace" we send it as "{BS}".So it also contains the { & } signs. Therefore when we send { and } signs nothing happen.Anyone help me... A: From http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses () have special meanings to SendKeys. To specify one of these characters, enclose it within braces ({}). For example, to specify the plus sign, use "{+}". To specify brace characters, use "{{}" and "{}}". Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces. In other applications, brackets do have a special meaning that might be significant when dynamic data exchange (DDE) occurs. Basically, you need to double up the braces to escape them, Like {{} to send a { opening brace, and {}} to send a closing brace. It may not be obvious at first glance, but that's just enclosing a brace character within braces. This is consistent with other escape sequences, such as using \\ in C/C#/etc to indicate a literal \ instead of a string formatting character.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Print screen with GWT I want to print a html page generated by GWT. I am using Window.print(). But when print is invoked only one page is printed. Is there a way to print all pages? A: We were able to print complete page by creating new window and adding inner html of current page to it and then executing print on it. A class which provides the same functionality is shared at google code. http://code.google.com/p/gwt-print-it/ A: But when print is invoked only one page is printed. Are you sure that this is a GWT's problem? The problem maybe is in browser or in printer's configuration. Try to check this options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ØMQ multithreaded REQ/REP I'm trying to write an application that will allow the user to start long-running calculation processes which will receive commands from a web server using ØMQ. I use standart request-reply architecture: server has a REQ socket connected to a worker processes REP socket. When a new command is received from a user, it is sent to the worker process: self.instance_dict[instance_id].socket.send(json_command) result = self.instance_dict[instance_id].socket.recv() The problem appears when the second command is sent while the first one is still being executed. Does ØMQ provide functionality that will take care of message queues or do I have ot implement it myself? Or should I change the architecture? A: For REQ/REP, the second command must not be sent until the first one has been acknowledged; ZMQ enforces the correct ordering of messages in the protocol. You might want to use PUSH/PULL instead - the messages will then be queued up automatically without requiring replies in between (as an aside, I think this also automatically allows you to use multiple workers for scaling and load balancing). If you use an IOLoop, you can set up ZMQStreams that will queue up messages within a process. See https://github.com/zeromq/pyzmq/blob/master/zmq/eventloop/ioloop.py
{ "language": "en", "url": "https://stackoverflow.com/questions/7516139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Segmentation fault in std::vector::erase() in Visual C++ I am having a segmentation fault in the erase function of std::vector that is driving me crazy. Am having the following code: std::map<uint32_t, std::vector<boost::uuids::uuid> >::iterator it = theAs.find(lSomeUint32); if (it != theAs.end()) { std::vector<boost::uuids::uuid>& lIds = it->second; // vector contains one entry std::vector<boost::uuids::uuid>::iterator it2 = lIds.begin(); while (it2 != lIds.end()) { if (*it2 == lSomeUuid) { lIds.erase(it2); break; } ++it2; } } In lIds.erase(it2), I get a segmentation fault. More precisely, I get a segmentation fault in _Orphan_range (can be found in c:\Program Files\Microsoft Visual Studio 10.0\VC\include\vector) that is called from erase. But I have no clue why. The vector and the iterator look ok. But in _Orphan_range, something goes completely wrong. The while loop in there is executed three time although my vector contains one item only. In the third run, the variable _Pnext gets broken. Does someone have an idea? That would be awesome! David Unfortunately (or maybe fortunately), the example above executed standalone works. But inside my big software project, it doesn't work. Does someone know what the failing function _Orphan_range is executed for? A: Erasing from std::vector invalidates iterators. see STL vector::erase Therefore it2 is invalid after the first call to erase. Alas the check "(it2 != lIds.end()) " will not be true. change your code to: if (*it2 == lSomeUuid) { it2 = lIds.erase(it2); break; } A: You compare with wrong end iterator. std::vector<boost::uuids::uuid>::iterator it2 = lIds.begin(); while (it2 != pIds.end()) { Note lIds and pIds. Try to use more letters in your variables names and don't use hungarian notation. You'd caught Ids_ptr almost instantly. A: Isn't your "theAs.find(lSomeUint32);" returning the index position rather than the Map::iterator? I'm not sure about this. Can you check it out? The find() function returns the position of the lSomeUint32 in theAs and would return the position of that lSomeUint32 in the string(if it is present). I suppose that is the reason why your erase function is throwing an error. It is not able to erase a data that is not present or that is not in the scope of your program. Even otherwise if your find() returns the map object I would, in addition to that put a simple if structure to check whether that particular find() returns any object or is NULL just to make sure that the iterator is assigned a value before being operated. Just a suggestion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facing Issue while using XMLHttpRequest with QML JavaScript Facing Issue while using XMLHttpRequest with QML and JavaScript. I am calling JavaScript Function from a QML button click, In that JavaScript I am sending XMLHttpRequest to an server. But when I send the request I get immediate call back in the function (which I have resisted using onreadystatechange property) as req.readyState == XMLHttpRequest.DONE but req.status is '0'. Usually we get readyState as follows: XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; and then XMLHttpRequest.DONE = 4; and in done state we check for request status which should be 200. What can cause this type of behavior. Is this an problem with QT JavaScript Interpreter? I am stuck with this Thanks. A: I can't say whether there is a problem with the QT interpreter, but it may be a problem with your request. req.readyState == XMLHttpRequest.DONE does not imply that the request was a success; you will get it even on an error, see DONE in this source. DONE (numeric value 4) The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects). [...] The DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false. From the status attribute: The status attribute must return the result of running these steps: If the state is UNSENT or OPENED return 0 and terminate these steps. If the error flag is true return 0 and terminate these steps. Return the HTTP status code. A: Do you happen to use HTTPS connection with a self-signed certificate in the backend? If yes, try with plain HTTP instead (or with a valid SSL cert) - had a similar kind of problem few days ago with a self-signed cert.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can i trace an error or exception due to a trigger in sql server 2005? I need help to find the error in a trigger, the syntax is correct and i can add it to my table. however when i insert data in this table through a software i get an error. when i disable the trigger the software can insert data. the problem is that software doesn't throw any exception. how can i get the exact error, so i will be able to fix that trigger. is there an SQLserver error trace tool ? or Log Thank you very much the trigger is after INSERT INTO statement if that could help ? A: You can use SQL Server Profiler / Trace to trace user error messages. Probably by far the most common error in triggers is assuming that the inserted and deleted tables will only contain 1 row so they then fail when a statement affects multiple rows. Does your trigger code do this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7516155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does set iterator pointer cause segmentation fault? Bottom line, why would iterator cause segmentation fault? Note, I'm typing here the relevant parts of my code and not copy pasting. If there is an error in compilation, please note but do not consider it the source of my issue. In my code, I have a map of boxes for beads: map<vector<int>,set<shared_ptr<bead> > > > nextBoxes; Each bead has, among others, a vec pos member which, in turn has: class vec{ double x; double y; double z; . . . vector<int> getBox(); . . . } vector<int> vec::getBox(){ vector<int> out(3,0); extern double boxSize; out[0] = x/boxSize; out[1] = y/boxSize; out[2] = z/boxSize; return out; } I use a very simple method to get through the beads into the boxes extern vectrot<shared_ptr<bead> > beads; for (int i = 0; i < beads.size(); i++){ vector<int> t = beads[i]->pos.getBox(); nextBoxes[t].insert(beads[i]); } Elsewhere in the code, the pos values of the beads might change and I update the boxes locally. I use the following loop to go through the boxes and beads: map<vector<int>,set<shared_ptr<bead> > >::iterator mit = nextBoxes.begin(); extarn vector<vector<int> >::targets; //holds a vector of a 1, -1 and 0 vectors of distance from the box extern int boxNum; while (mit != nextBoxes.end()){ vector<int> t1 = mit->second(); set<shared_ptr<bead> >::iterator bit1 = mit->second.begin(); set<shared_ptr<bead> >::iterator bit2; while (bit1 != mit->second.end()){ shared_ptr<bead> b = *bit++; vector<int> t2(3,0); for (int i = 0; i < 13 i++){//13 is the size of the targets index. for (int j = 0; j < 3; j++){ t2[j] = t1[j] + targets[i][j]; if (t2[j] >= boxNum) t2[j] -= boxNum; if (t2[j] < 0 ) t2[j] += boxNum; } bit2 = beadsBoxes[t2].begin(); while (bit2 != nextBoxes[t2].end()){ shared_ptr<bead> b2 = *bit2++//the segmentation fault is here . . . } } } } For some reason, I get a segmentation fault. What I got so far is: * *the segmentation fault is cause because of the incrementation of the interator. *the box size is 2. *this is not the first box I am testing (didn't count them but it runs for a while). *I have absolutely no idea how to access the second element in the box (the first I can use the iterator since I don't increment it. *This is the outPut error from gdb: 0 0x00002aaaaab43c65 in std::_Rb_tree_increment(std::_Rb_tree_node_base*) () from /usr/lib64/libstdc++.so.6 1 0x000000000041a28e in operator++ (this=0x63d7c0) at /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_tree.h:265 I'll appreciate any help, thanks. Edit: Solved, kinda. Trying to reduce the error to a minimum running example, I have deleted all those line and rewritten them and now things look fine. I'm still interested of such a case though: If you want, I can reask the question: When will iterator incremental cause a segmentation fault in c++? A: To answer your edit the only way possible: If you want, I can reask the question: When will iterator incremental cause a segmentation fault in c++? Incrementing an iterator will cause a segmentation fault only if it is used incorrectly. That's it. The standard doesn't list the cases in which code must segfault, it only lists what should happen when code is used correctly. When you use it incorrectly, it is simply undefined behavior, and any of a million things might happen, including, but not limited to, segmentation faults. If incrementing your iterator gave you a segfault, it is either because: * *the iterator already pointed to the end of the set, or *the iterator pointed outside the set, to a variable that had gone out of scope, or perhaps the iterator had never been initialized at all. But segmentation faults happen when you have undefined behavior. And that, by definition, makes it impossible to tell you which cases will trigger a segmentation fault. A: At least one error is present in these lines: bit2 = beadsBoxes[t2].begin(); while (bit2 != nextBoxes[t2].end()){ shared_ptr<bead> b2 = *bit2++//the segmentation fault is here Assuming beadsBoxes and nextBoxes are objects of standard container types, you are using the iterator incorrectly. bit2 appears to be an iterator pointing at the members of beadsBoxes. But, you are comparing it to the end of nextBoxes. If beadsBoxes[2] and nextBoxes[2] represent different objects, you can't do that. A: The first thing you should fix is getBox. It does not return a value, so undefined behavior happens when it is called. Add return out; at the end.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to embed 3rd party Javascript that uses , how can i stop php from parsing the "" I'm working in an insane mess of a CMS system where php, javascript, and html are all within templates. I'm trying to drop in code from a third party site for integration functionality, but they have javascript of the form: <script type="lib"> Hello, <?js= firstName ?>! </script> The PHP interpreter see's and does its thing, and thus the entire template errors out. Anyone know how to perhaps wrap this code block to prevent PHP interpreter from caring about it? Thanks in advance! A: If disabling PHP Short-tags isn't an option, you could simply output said string using PHP, so you'd get something like this: Hello, <?php print "<?js= firstName ?>"; ?>! A: Disable PHP Short-Tags and you should not have an issue. A: In a PHP document with short open tags enabled, the PHP interpreter will see the <? part of the <?js tag and will try to parse it as PHP, resulting in this error: Parse error: syntax error, unexpected T_STRING in ... on line ... To fix the problem, disable the short form (<? ?>) of PHP's open tag. This will now disable the use of <? and <?= in your PHP scripts. If your site only uses <?php tags then this is safe to do; if it uses <? as well then it is not safe to do as your scripts will no longer function as expected. There are two ways your Web Host or System Administration will have configured Apache to use PHP: * *Apache loads the PHP interpreter as an Apache module *Apache runs the PHP interpreter as a CGI binary Which solution you will use below will depend on how Apache is running PHP in your environment*. In Apache's .htaccess file, place the following: # PHP as an Apache Module php_value short_open_tag 0 In the global or a local php.ini file, place the following: # PHP as a CGI Wrapper short_open_tag = Off In either case, you'll want to restart Apache after making any configuration changes to ensure your new settings get picked up. Note: If your server is configured to run PHP as an Apache module, then you will have the choice of using either a php.ini or Apache .htaccess files. However, if your server runs PHP as a CGI wrapper then you will only have the choice of using php.ini files locally to change settings, as Apache is no longer in complete control of PHP. When PHP is running as a CGI wrapper, putting PHP settings in to an .htaccess file will cause the server throw an error. A: Do you happen to be running apache? Do these files live separate from the PHP? If so, you could use an .htaccess file (or httpd.conf if you have the rights to modify it) to do something like this: <FilesMatch "\.template_file_ext"> php_flag engine off </FilesMatch>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Delay the fade In action until the Animation action has occurred Right basically I have a number of headers. When one of those headers is clicked, the rest of the headers slide down (for this I am using the animate() method). This works fine. But straight after the headers slide down, I want the contents of that header to display in the space directly before it. The code below works, the items are being grabbed and displayed. The problem I am having, is delaying the $(this).find('ul').fadeIn(); part. At the moment, the items are fading in while the animation is happening which is causing the animation to jump. Any help would be much appreciated. Thanks in Advance. $(function () { $('ul#work-headers li ul').hide() $('ul#work-headers li').toggle(function () { var itemHeight = $('ul#work-headers li').find('ul').height(); $(this).next('ul#work-headers li').animate({ marginTop: itemHeight }, 1000); $(this).find('ul').fadeIn(); }, function () { $(this).next('ul#work-headers li').animate({ marginTop: "0px" }, 1500); $('ul#work-headers li ul').fadeOut(1000); }); }); A: Make the FadeIn start on animation complete, by using the animate() callback function $(function () { $('ul#work-headers li ul').hide() $('ul#work-headers li').toggle(function () { var caller = $(this); var itemHeight = $('ul#work-headers li').find('ul').height(); $(this).next('ul#work-headers li').animate({ marginTop: itemHeight }, 1000, function() { // Animation complete. caller.find('ul').fadeIn(); }); }, function () { $(this).next('ul#work-headers li').animate({ marginTop: "0px" }, 1500); $('ul#work-headers li ul').fadeOut(1000); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7516163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript-Facebook-integration: window.fbAsyncInit no longer firing We use the fbAsnycInit hook to init the FB object, which was working till last week. Now the hook does not get called any longer. There are no JS errors in the FireBug-Console in FF and the IEs Development tools. The hook is assigned correctly (according to debug output.) before UnityObject before embedUnity after embedUnity window.fbAsyncInit will be assigned: [object Window] window.fbAsyncInit: undefined window.fbAsyncInit has been assigned: [object Window] window.fbAsyncInit: function () { log("fbAsyncInit"); FB.init({appId: "143585412381528", status: true, cookie: true, xfbml: true}); log("FB.init finished"); FB.getLoginStatus(function (response) {if (response.session) {log("User already logged in");} window.fbAsyncInit has been assigned 2 load all.js started load all.js finished firstFrameCallback before send message[object HTMLEmbedElement] uid undefined after send message Do you have any ideas how to go on finding the cause? Are there some JS errors swallowed? The all.js library with problems? The appliation can be found here. UPDATE March, 8th 2012: At the moment the application seeems to work. Problems may be related to older revisions of Facebook supplied JS-files?!
{ "language": "en", "url": "https://stackoverflow.com/questions/7516164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery Slider/Accordion Combination I'm trying to make a section on a website for client testimonials whereby once clicked the text area expands over a corresponding image with the testimonial. Alone this would be straight forward enough using a simple slider but we are trying to incorporate into this an accordion menu. To add extra complications the testimonials are only contained within one tab of the accordion menu. Please see the attached image to gain a better understanding: http://i55.tinypic.com/o08cqv.png (This image is to demonstrate the concept only) Thanks a lot! A: is this the kind of thing you are looking to do? http://jsfiddle.net/hollandben/HLSkW/ Also, you can use this jQuery plugin... http://www.slidorion.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7516166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to fully understand JavaScript hoisting Edit Looks like it was an issue on my part and my usage of jsfiddle :? Ive been reading a couple of articles on hoisting lately, one is by Nicholas Zakas, and the other is by Ben Cherry. Im trying to follow the examples and just test on my own to make sure I fully grasp it but Im having an issue mainly with this example, if (!('a' in window)) { var a = 1; } console.log(a); Instead of logging undefined its logging 1. If I am understanding everything correctly, a should be undefined, because it should exist in the window scope due to the var statement being hoisted to the top, so it should not be assigned the value. But the following is acting as expected, (function bar(){ console.log(foo); var foo = 10; console.log(baz); })(); foo is undefined, and baz is not defined. I have a fiddle here with both examples. Really just trying to wrap my head around this. Has something changed since these articles were written maybe? If anyone can shed some light on this it would be appreciated. Im using Chrome 14 when testing. A: Change the wrap in the fiddle to no wrap(head) http://jsfiddle.net/rlemon/VjCqF/3/ A: In the second example, hoisting transforms the code into this: (function bar(){ var foo; console.log(foo); foo = 10; console.log(baz); })(); So foo is undefined during the first call to log. The declaration is always hoisted to the top of the enclosing function, but assignment is never hoisted with it. A: You have JSFiddle set to onLoad, so var a is scoped to the onLoad function. Change it to no wrap and you get: undefined undefined Uncaught ReferenceError: baz is not defined A: object.a === undefined; // true, but a in object; // true var object = {a: undefined}; ('a' in object); // is true because a is a property of object A: Hoisting is understood differently but to my understanding what it does is Whenever you create an variable/functions it sets up a memory space for you.It does not put the variable/functions on the top of execution context. Type 'this/window' in console you'll find your var/functions sitting there lexically. for example: a; //returns undefined b(); //returns Hello World var a = "Hello"; function b() { console.log('Hello World'); } If it is placed on top during execution then it should output 'Hello' not 'undefined' functions will get excuted.Variables won't get excuted. Please avoid hoisting excute the vars after it is being declared: var a = "Hello"; function b() { console.log('Hello World'); } a; //returns Hello b(); //returns Hello World
{ "language": "en", "url": "https://stackoverflow.com/questions/7516175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Regular expression for Alphabet, numeric and special character Can someone please give regular expression for a word, which should have: * *length in the range of 6 to 10 *It must be a combination of alphanumeric, numeric and special character (non-alphanumeric character) A: So in other words, all characters are allowed, but at least one letter, one digit, and one "something else" character is required? ^(?=.*\p{L})(?=.*\p{N})(?=.*[^\p{L}\p{N}]).{6,10}$ I wouldn't impose a maximum length restriction on a password, though... Explanation: ^ # Match start of string (?=.*\p{L}) # Assert that string contains at least one letter (?=.*\p{N}) # Assert that string contains at least one digit (?=.*[^\p{L}\p{N}]) # Assert that string contains at least one other character .{6,10} # Match a string of length 6-10 $ # Match end of string A: You should do this as a sequential series of tests: * *Is it of the right length? ^.{6,10}$ *Does it contain an alphabetic character? [A-Za-z] *Does it contain a digit? [0-9] *Does it contain a "special character" [^0-9A-Za-z] If it passes all four tests, it's ok.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery get generated elements attributes FF vs IE problem I have a click event on my select-tag (filterBA), and then the options are generated dynamicly. $("#filterBA").click(function(event){ var $tgt = $(event.target); if($tgt.is('option')){ if($tgt.attr('id') != 0){ sortRowsByBA($tgt.attr('id')); }else{ appendOrReplaceRows("replace", getSortColumn(), getAscdesc()); } } }); This works great... in firefox, but IE won't reconnize my $tgt as an option. I check by adding: $("#filterBA").click(function(event){ var $tgt = $(event.target); alert($tgt.is('option')); ... And no matter what it returns false. But in FF it return true vi i hold my mouse down a selects one of the options. I don't get it, since i use the same approach when i have to select a div used in a custom select-list i created (in the same system), but when the click-event is on the tag it won't work. Anybody know what might be wrong? btw. here is my function to generate the options: function pupulateBA(){ $selectTag = $('#nav select').html('<option id="0">Select business area</div>'); $.ajax({ url: "ajaxBAs.cgi", dataType: 'json', success: function(jsonData){ for(var businessIndex in jsonData){ $selectTag.append("<option id='"+jsonData[businessIndex].id+"'>"+jsonData[businessIndex].name+"</option>"); } }, error: function(){ alert('Ajax error retriving business areas to frontpage.'); } }); } I found a solution: ofc im an idiot, since I forgot all about ":selected".. DOH! So here is my new event on my tag: $("#filterBA").change(function(){ $('#filterBA option:selected').each(function(){ alert($(this).attr('id')); }); }); This works with both FF and IE on dynamically created options in a select-dropdown. A: From QuirksMode. event.target - W3C/Netscape says: the target. No, says Microsoft, the srcElement. Not positive how to work around it. Read the QuirksMode article though as it provides a function that may or may not do what you want it to do and also specifies a few other attributes that will hopefully work for you. Although I would hope that maybe jQuery had an abstracted version so that you don't have to worry about IE hacks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android TabHost.setCurrentTab() not working I have a TabActivity that I am having problems after the device changes orientation. Followed some places on how to keep the current tab open after the change, but even tho I do get the correct tab number, it always sets it back to 0. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); int currentTab = 1; if (savedInstanceState != null) currentTab = savedInstanceState.getInt("tabNumber"); tabHost = getTabHost(); // (TabHost) findViewById(android.R.id.tabhost); createTabs(tabHost); tabHost.setCurrentTab(currentTab); } protected void onSaveInstanceState(Bundle outState) { outState.putInt("tabNumber", getTabHost().getCurrentTab()); super.onSaveInstanceState(outState); } Am I doing something wrong here? A: add this to yout manifest file .. activity android:name="youractivity" android:configChanges="orientation|keyboardHidden" ... Leslie
{ "language": "en", "url": "https://stackoverflow.com/questions/7516187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting today's date in blank cells I would like a macro that puts today's date into all blank cells within a column. If there is a date already in then a cell, then it should skip this row. A: You can do this without VBA, see http://www.contextures.com/xlDataEntry02.html With code as requested (select your range to populate prior to running) Sub QuickFill() Dim rng1 As Range On Error Resume Next Set rng1 = Selection.SpecialCells(xlBlanks) On Error GoTo 0 If Not rng1 Is Nothing Then rng1.Value = Format(Now(), "dd-mmm-yy") End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7516188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two same name variables In https://github.com/Khan/khan-exercises/blob/master/khan-exercise.js there are two var Khan variables. How come? Do they affect each other? A: One Khan is the name of the global variable "Khan", the other is a variable inside the self executing function that it is equal to. var Khan = (function(){ .... var Khan = ... .... })(); The indentation in the source file is horrible and you probably did not notice that.... A: variables wrapped in anonymous functions only work inside that function. So this should work okay. <script type="text/javascript"> $(function(){ var khan = (function(){ var khan = //this should not be a problem and they both work, this will be only available in the function }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create Custom URLs I have a model that returns a list of artist's names from a database along with their ID. I want to loop through these artists in my view and create links to their pages with the following format: http://www.example.com/the-artist-name/artist-portfolio/ID.html What is the best way to do this? A: Controller $data['artists'] = $this->artists_model->get_all(); // should return array $this->load->view('yourview', $data); View <?php foreach($artists as $artist): ?> <a href="http://example.com/<?php echo $artist['name']; ?>/artist-portfolio/<?php echo $artist['id']; ?>.html"> <?php echo $artist['name']; ?> </a> <?php endforeach; ?> A: Pass the data from the model into the view and loop through it like you normally would. In your controller: $view_data['artists'] = $this->artist_model->get_artists(); $this->load->view('view.php', $view_data); In your view: foreach ($artists as $artist) { echo "<a href=\"http://www.example.com/{$artist['name']}/artist-portfolio/{$artist['id']}.html\">{$artist['name']}</a>"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the pros and cons of using MSI and MSP? What are the pros and cons of using MSI and MSP in using them for deployment. I was thinking of automating the deployment of my software using MSI and MSP. I wanted to understand if there is any concerns. And also how feasible is it to use MSP for patch deployment A: For MSI package advantages you can go through this thread: What's the prime advantage to having an MSI installation package? Regarding MSP patches, they were designed to be applied as patches. If you follow the patching rules, they work perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Comments - current page URL Is there any way the Facebook Comments box can use the current page's URL? I want to add the feature to my site but don't want the same comments showing on each page. For example, I want the comments for "article1" to only show with "article1." The comments for "article2" would only show with "article2" etc. A: Facebook comment plugin is url based. You would need to set href or data-href property with unique urls for each article that you want to have unique comments on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't locate build.xml file when running ant through a shell script I'm using bash shell running on Cygwin on Windows 7. I have this in my bash script, which attempts to figure out the location of a build file based on the location of the currently executing script … SCRIPT_DIR="$( cd -P "$( dirname "$0" )" && pwd )" BUILDFILE=$SCRIPT_DIR/build.xml ant -buildfile $BUILDFILE -Dbuildtarget=$1 -Dmodule="$2" -Dproject=$3 -Dnolabel=true -DFirefox=$4 -DInternetExplorer=$5 -DGoogleChrome=$6 Selenium4 However, even though the file is there, I get an "Unable to locate buildfile error" $ sh c:/selenium//run_client_tests.sh prod "\Critical Path\Live\QX" MyProj true false false cygwin warning: MS-DOS style path detected: c:/selenium//run_client_tests.sh Preferred POSIX equivalent is: /cygdrive/c/selenium/run_client_tests.sh CYGWIN environment variable option "nodosfilewarning" turns off this warning. Consult the user's guide for more details about POSIX paths: http://cygwin.com/cygwin-ug-net/using.html#using-pathnames Started script Buildfile: \cygdrive\c\selenium\build.xml does not exist! Build failed ls reveals the file is there … dev@selenium_w7 /cygdrive/c/selenium $ ls /cygdrive/c/selenium/build.xml /cygdrive/c/selenium/build.xml dev@selenium_w7 /cygdrive/c/selenium $ ls c:/selenium/build.xml c:/selenium/build.xml A: The problem here is that ant does not know about Cygwin-style paths. Note that ant is complaining that it cannot find \cygdrive\c\selenium\build.xml. That is because /cygwin is only understood by the Cygwin shell. What you need to do is pass a DOS-style path to ant. So replace BUILDFILE=$SCRIPT_DIR/build.xml with BUILDFILE=`cygpath -w $SCRIPT_DIR/build.xml` Or to make this a bit more platform-agnostic, use Java-style paths BUILDFILE=`cygpath -m $SCRIPT_DIR/build.xml`
{ "language": "en", "url": "https://stackoverflow.com/questions/7516206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery iterate some div I have html: <div class="box"> <input name="radio-1" value="1" type="radio" class="radio"> <div class="hidden_box"> some content </div> </div> <div class="box"> <input name="radio-2" value="1" type="radio" class="radio"> <div class="hidden_box"> some content </div> </div> .... and so on When I click on radio button I need to make "hidden_box" visible in this "box" div. How can I do it? Please, help. A: Since you tagged your Q with jQuery, I'll use that: $('.radio').click(function(){ $(this).parent().find('.hidden_box').show(); }); See working example. UPDATE: If you want to apply this to all present and future '.box' items, use: $('.radio').live('click', function(){ $(this).parent().find('.hidden_box').show(); }); A: $(".radio") //select the radio buttons .click( function() { //Assign a click handler $(this).next().show(); //Get the element that comes after this one and make it visible }); A: $('.radio').click(function(i,v){ $(this).next('.hidden_box').toggle(); }); A: $('.radio').click(function(){ $('.hidden_box', $(this).parent()).show(); }) Will work, even if hidden_box isn't the next DOM element. The second parameter in a jquery selector is the scope. UPDATE: Using find(), as demonstrated elsewhere in the answers looks a bit cleaner to me A: Using jQuery: $('.box input').click(function(){ $(this).next('.hidden_box').toggle(); }); Live example: http://jsfiddle.net/ZmRdg/
{ "language": "en", "url": "https://stackoverflow.com/questions/7516210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ / Mysql Connector : undefined reference to `get_driver_instance' I've found some topics on this forum concerning the same error, but I didn't find the solution in it. I'm trying to make work C++ & Mysql Connector on Ubuntu 11.04. My error is (after following official Mysql tutorial) /tmp/ccDmH4pd.o: In function `main': mysql.cpp:(.text+0xb): undefined reference to `get_driver_instance' collect2: ld returned 1 exit status Here is my code : int main(){ sql::Driver* driver; // Create a pointer to a MySQL driver object sql::Connection* dbConn; // Create a pointer to a database connection object sql::Statement* stmt; // Create a pointer to a Statement object to hold our SQL commands sql::ResultSet* res; // Create a pointer to a ResultSet object to hold the results of any queries we run driver = get_driver_instance(); dbConn = driver->connect(server, username, password); delete dbConn; return 0; } Here are my includes : #include "mysql_driver.h" #include "mysql_connection.h" // Include the Connector/C++ headers #include "cppconn/driver.h" #include "cppconn/exception.h" #include "cppconn/resultset.h" #include "cppconn/statement.h" Thanks in advance everybody Touki A: The get_driver_instance() function is not in the global namespace but in ::sql::mysql. So you have to use the proper name: ::sql::Driver *driver = ::sql::mysql::get_driver_instance(); A: LIBPATH = -L/usr/lib/ -lmysqlcppconn -lmysqlclient_r
{ "language": "en", "url": "https://stackoverflow.com/questions/7516213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Prevent google overlay/infowindow from allowing clicks through to markers underneath I'm trying to make some custom Google maps info windows, but I'm getting the issue where markers underneath my custom info window is clickable through the info window. Here's an example (basically straight from googles example here) <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <title>Google Maps JavaScript API v3 Example: Info Window Custom</title> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> /* An InfoBox is like an info window, but it displays * under the marker, opens quicker, and has flexible styling. * @param {GLatLng} latlng Point to place bar at * @param {Map} map The map on which to display this InfoBox. * @param {Object} opts Passes configuration options - content, * offsetVertical, offsetHorizontal, className, height, width */ function InfoBox(opts) { google.maps.OverlayView.call(this); this.latlng_ = opts.latlng; this.map_ = opts.map; this.offsetVertical_ = -195; this.offsetHorizontal_ = 0; this.height_ = 165; this.width_ = 266; var me = this; this.boundsChangedListener_ = google.maps.event.addListener(this.map_, "bounds_changed", function() { return me.panMap.apply(me); }); // Once the properties of this OverlayView are initialized, set its map so // that we can display it. This will trigger calls to panes_changed and // draw. this.setMap(this.map_); } /* InfoBox extends GOverlay class from the Google Maps API */ InfoBox.prototype = new google.maps.OverlayView(); /* Creates the DIV representing this InfoBox */ InfoBox.prototype.remove = function() { if (this.div_) { this.div_.parentNode.removeChild(this.div_); this.div_ = null; } }; /* Redraw the Bar based on the current projection and zoom level */ InfoBox.prototype.draw = function() { // Creates the element if it doesn't exist already. this.createElement(); if (!this.div_) return; // Calculate the DIV coordinates of two opposite corners of our bounds to // get the size and position of our Bar var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_); if (!pixPosition) return; // Now position our DIV based on the DIV coordinates of our bounds this.div_.style.width = this.width_ + "px"; this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px"; this.div_.style.height = this.height_ + "px"; this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px"; this.div_.style.display = 'block'; }; /* Creates the DIV representing this InfoBox in the floatPane. If the panes * object, retrieved by calling getPanes, is null, remove the element from the * DOM. If the div exists, but its parent is not the floatPane, move the div * to the new pane. * Called from within draw. Alternatively, this can be called specifically on * a panes_changed event. */ InfoBox.prototype.createElement = function() { var panes = this.getPanes(); var div = this.div_; if (!div) { // This does not handle changing panes. You can set the map to be null and // then reset the map to move the div. div = this.div_ = document.createElement("div"); div.style.border = "0px none"; div.style.position = "absolute"; div.style.background = "url('http://gmaps-samples.googlecode.com/svn/trunk/images/blueinfowindow.gif')"; div.style.width = this.width_ + "px"; div.style.height = this.height_ + "px"; var contentDiv = document.createElement("div"); contentDiv.style.padding = "30px" contentDiv.innerHTML = "<b>Hello World!</b>"; var topDiv = document.createElement("div"); topDiv.style.textAlign = "right"; var closeImg = document.createElement("img"); closeImg.style.width = "32px"; closeImg.style.height = "32px"; closeImg.style.cursor = "pointer"; closeImg.src = "http://gmaps-samples.googlecode.com/svn/trunk/images/closebigger.gif"; topDiv.appendChild(closeImg); function removeInfoBox(ib) { return function() { ib.setMap(null); }; } google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this)); div.appendChild(topDiv); div.appendChild(contentDiv); div.style.display = 'none'; panes.floatPane.appendChild(div); this.panMap(); } else if (div.parentNode != panes.floatPane) { // The panes have changed. Move the div. div.parentNode.removeChild(div); panes.floatPane.appendChild(div); } else { // The panes have not changed, so no need to create or move the div. } } /* Pan the map to fit the InfoBox. */ InfoBox.prototype.panMap = function() { }; function initialize() { var myOptions = { zoom: 8, center: new google.maps.LatLng(-33.397, 150.644), mapTypeId: google.maps.MapTypeId.ROADMAP, sensor: 'true' } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ position: new google.maps.LatLng(-34, 150), map: map }); google.maps.event.addListener(marker, "click", function(e) { var infoBox = new InfoBox({latlng: marker.getPosition(), map: map}); }); var m2 = new google.maps.Marker({ position: new google.maps.LatLng(-33.5, 150.5), map: map }); google.maps.event.addListener(m2, "click", function(e) { var infoBox = new InfoBox({latlng: m2.getPosition(), map: map}); }); } </script> </head> <body style="margin:0px; padding:0px;" onload="initialize()"> <div id="map_canvas" style="width:100%; height:100%"></div> </body> </html> You can see I'm making two markers, one just to the north east of the other. Click the bottom one then observe how the other marker is clickable through the marker (right near the 'W'). How can I fix this?! I've tried altering the z-index but that didn't seem to help. This is using api v3 btw. A: For posterity, you want to disable a bunch of events on the marker pop-up dom, this was the prescribed method, even though it feels like overkill. You could alternatively cycle through all the markers present apart from the one clicked and disable clicking on them (actually that's probably a better solution in hindsight). Depends on how many markers you have perhaps, I had a lot. Something like this (transcribed here without testing from my coffeescript so...) // All in a google.maps.OverlayView subclass. ... this.listeners = new Array(); // save listeners for unbinding later ... this.cancelEvents = function(){ events = ['mousedown', 'mousemove', 'mouseover', 'mouseout', 'mouseup', 'mousewheel', 'DOMMouseScroll', 'touchstart', 'touchend', 'touchmove', 'dblclick', 'contextmenu']; // Note, don't disable 'click' if you want to be able to click links in the dom. Some things we're disabling here will can effect how your user might interact with the popup (double click to select text etc) for(var i = 0; i < events.length; i++){ var event = events[i]; this.listeners.push( google.maps.event.addDomListener( this.popup_dom_element, event, function(ev){ e.cancelBubble = true; if(e.stopPropagation){ e.stopPropagation(); } } ); ); } } this.onAdd = function (){ // build your html popup var html_code = "..."; // easy way to get a dom element but probably over kill if its your only JQ this.popup_dom_element = $(html_code); this.cancelEvents(); } this.onRemove = function(){ // any other removal code you have ... for(var i = 0; i < this.listeners.length; i++){ // remove our event listeners google.maps.event.removeListener(this.listeners[i]); } } A: Try and use the MapPane overlayMouseTarget instead of floatPane. A: If you don't want people to be able to click on a marker, could you call marker.setClickable(false) A: i had the same problem and its actually very easy:/ if u are using jquery just set $(div).bind("click",function(e) { return false; }); in the InfoBox.prototype.createElement function. This should help. Cheers A: use: google.maps.event.addDomListener instead of google.maps.event.addListener
{ "language": "en", "url": "https://stackoverflow.com/questions/7516225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: adding new role to already authenticated user (without logging him out) I'm using Spring Security, and in some cases after logging in user can make some actions which should gave him access to some resources, so ideally it should be done via giving this user a new role. But, the authorities inside org.springframework.security.core.userdetails.User class are unmodifiable Set. So no any changes are allowed in the given list of roles. How usually (I'm sure it's quite common, normal behaviour) developers do in this case? A: A valid approach would be to look at your roles and think if they make sense. Maybe you need to have more roles, so users are allowed to do everything right after login. I think you might need to "break in smaller pieces your roles". You are not allowed to modified roles after logon. And you are not meant to do so. That would be a security threat to the platform. I authenticate as a plain user. Execute some code and become admin. That's what I think that you should reissue the login. Udo.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Asp.net Mvc Convert return Action result(view) to string I am working on a project in asp.net mvc3(c#). I need a solution for convert a view(not a partial view) to string from different controllers. Code Explantion: 1) Calling "details" action of proposalmoduleController from proposalsController. 2) proposalmoduleController action "details" returns a view and convert this view(return result) as a string in proposalsController. Code public class proposalmoduleController : ControllerBase { [HttpGet] public ActionResult details(int id, int widgetuniqueid) { //id - widgetid of div container List<ModuleViewModel> listmoduleviewmodel = new List<ModuleViewModel>(); List<ModuleFieldViewModel> listmodulefieldviewmodel = new List<ModuleFieldViewModel>(); var objProposalModuleService = new ProposalModuleService(); var objModuleViewModel = new ModuleViewModel(); string WidgetTitle = ""; Int64 ModuleTemplateID = 0; //objModuleViewModel.ProposalID = proposalid; objModuleViewModel.ProposalModuleWidgetID = id; listmoduleviewmodel=objProposalModuleService.Select(1, objModuleViewModel,out listmodulefieldviewmodel, out WidgetTitle, out ModuleTemplateID); return View(listmoduleviewmodel); } } public class proposalsController : ControllerBase { public string SaveHtml(int ProposalID) { var objProposalSortOrderViewModelList = new List<ProposalSortOrderViewModel>(); proposalmoduleController objModuleController = new proposalmoduleController(); // Initilize the object of proposalmoduleController for accessing details method objProposalSortOrderViewModelList = GetProposalSortorders(ProposalID); string result; foreach (var item in objProposalSortOrderViewModelList) { ViewResult viewResult = (ViewResult)objModuleController.details(Convert.ToInt32(item.KeyID), Convert.ToInt32(item.SortOrder)); // Fetch the result returned from proposalmodulecontroller,details action result=viewResult.ToString(); // Need to get result fetch from the proposalmodulecontroller,details action as a string } } } enter code here Please suggest any solution. A: A ViewResult is not a View. ViewResult is used by the MVC engine to determine the view that must be rendered. I think it's better if you change your perspective: * *if you want to include a partial view in a view just work on the presentation code using @Html.Partial *if you want to get the details data in your proposalsController don't call the action of the proposalmoduleController but call a service method that gives you the data
{ "language": "en", "url": "https://stackoverflow.com/questions/7516234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to execute Javascript on an anchor Generally, there are 3 ways (that I am aware of) to execute javascript from an <a/> tag: 1) Use onclick(): <a href="#" onclick="alert('hello'); return false">hello</a> 2) Directly link: <a href="javascript:alert('hello')">hello</a> 3) Or attach externally: // In an onload event or similar document.getElementById('hello').onclick = window.alert('Hello'); return false; <a id="hello" href="#">hello</a> I am actually loading the link via AJAX, so #3 is basically out. So, is it better to do #1 or #2 or something completely different? Also, why? What are the pitfalls that I should be aware of? Also of note, the anchor really doesn't link anywhere, hence the href="#", I am using a so the styles conform as this is still an object to be clicked and a button is inappropriate in the context. Thanks A: If you are loading the content via ajax and need to hook up event handlers, then you have these choices: * *Put a javascript handler in your HTML with your option 1) or 2). In my mind option 1) is a cleaner way of specifying it, but I don't think there's a mountain of difference between 1) or 2) - they both do essentially the same thing. I'm not a fan of this option in general because I think there's value in keeping the markup and the code separate. *After loading the content with ajax, call some local code that will find and hook up all the links. This would be the same kind of code you would have in your page and execute on DOMReady if the HTML had been static HTML in your page. I would use addEventListener (falling back to attachEvent) to hook up this way as it more cleanly allows multiple listeners for a single object. *Call some code after you load the content with ajax that finds all the links and hooks up the clicks to some generic click handler that can then examine meta data in the link and figure out what should be done on that click based on the meta data. For example, this meta data could be attributes on the clicked link. *When you load the content, also load code that can find each link individually and hook up an appropriate event handler for each link much the way one would do it if the content was just being loaded in a regular page. This would meet the desire of separating HTML from JS as the JS would find each appropriate link and hook up an event handler for it with addEventListener or attachEvent. *Much like jQuery .live() works, hook up a generic event handler for unhandled clicks on links at the document level and dispatch each click based on some meta data in the link. *Run some code that uses an actual framework like jQuery's .live() capability rather than building your own capability. Which I would use would depend a little on the circumstances. First of all, of your three options for attaching an event handler, I'd use a new option #4. I'd use addEventListener (falling back to attachEvent for old versions of IE) rather than assigning to onclick because this more cleanly allows for multiple listeners on an item. If it were me, I'd be using a framework (jQuery or YUI) that makes the cross browser compatibility invisible. This allows complete separation of HTML and JS (no JS inline with the HTML) which I think is desirable in any project involving more than one person and just seems cleaner to me.. Then, it's just a question for me for which of the options above I'd use to run the code that hooks up these event listeners. If there were a lot of different snippets of HTML that I was dynamically loading and it would be cleaner if they were all "standalone" and separately maintainable, then I would want to load both HTML and relevant code at the same time so have the newly loaded code handle hooking up to it's appropriate links. If a generic standalone system wasn't really required because there were only a few snippets to be loaded and the code to handle them could be pre-included in the page, then I'd probably just make a function call after the HTML snippet was loaded via ajax to have the javascript hook up to the links in the snippet that had just been loaded. This would maintain the complete separation between HTML and JS, but be pretty easy to implement. You could put some sort of key object in each snippet that would identify which piece of JS to call or could be used as a parameter to pass to the JS or the JS could just examine the snippet to see which objects were available and hook up to whichever ones were present. A: Number 3 is not "out" if you want to load via AJAX. var link = document.createElement("a"); //Add attributes (href, text, etc...) link.onclick = function () { //This has to be a function, not a string //Handle the click return false; //to prevent following the link }; parent.appendChild(link); //Add it to the DOM A: Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks. The way that CSP does this is disabling all the vectors where a user could inject Javascript into a page - in your question that is both options 1 and 2 (especially 1). For this reason best practice is always option 3, as any other option will break if CSP is enabled. A: I'm a firm believer of separating javascript from markup. There should be a distinct difference, IMHO, between what is for display purposes and what is for execution purposes. With that said, avoid using onclick attribute and embedding javascript:* in a href attribute. Alternatives? * *You can include javascript library files using AJAX. *You can setup javascript to look for changes in the DOM (i.e. if it's a "standard task", make the anchor use a CSS class name that can be used to bind a specific mechanism when it's later added dynamically. (jQuery does a great job at this with .delegate())) *Run your scripts POST-AJAX call. (Bring in the new content, then use javascript to [re]bind the functionality) e.g.: function ajaxCallback(content){ // add content to dom // search within newly added content for elements that need binding }
{ "language": "en", "url": "https://stackoverflow.com/questions/7516235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Return to the first index of UINavigationController? I'm doing an application which uses a UINavigationController and I'm switching to other UIViewControllers as follows: if(self.myViewController == nil){ MyViewController *aViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; self.myViewController = aViewController; [aViewController release]; } AppDelegate *delegate = [[UIApplication sharedApplication] delegate]; [delegate.myNavController pushViewController:myViewController animated:YES]; I imagine this is creating a pile of UIViewControllers into the UINavigationController, maybe an array of indexs? I would like to know how to turn back without having to be back one by one. For example, I'm sailing through a few screens and with a button I would like to return at the first index of navigation. I would also like know how to modify indexes, view, erase and anything pertaining to this issue. Sorry if I have not explained well. A: You've asked two questions. The first is, how do I get back to my first view controller. As @Thomas Clayson and @ender have answered, you want the popToRootViewControllerAnimated: method of your navigationcontroller object for that. The second is how to move to a particular index in the view controller stack. The answer to that is, you can set the array of viewControllers explicitly. So you can pull out the current listing of view controllers, modify it, and set it back into the navigationController stack. It'll reset the stack and animate you moving to the top item in the stack. Thusly: NSMutableArray *controllers = self.navigationController.viewControllers; [controllers removeObjectAtIndex:[controllers count] - 1]; //or whatever [self.navigationController setViewControllers:controllers animated:YES]; A: NSArray *viewControllers = [[self navigationController] viewControllers]; for (int i = 0; i < [viewContrlls count]; i++){ id obj = [viewControllers objectAtIndex:i]; if ([obj isKindOfClass:[yourViewControllername class]]){ [[self navigationController] popToViewController:obj animated:YES]; return; } } Using this you can come back to any specified viewController. A: [self.navigationController popToRootViewControllerAnimated:YES]; Will take you back to the very first view controller (root view controller). Hope this helps A: Use this NSArray *viewContrlls=[[NSArray alloc] initWithArray:[[self navigationController] viewControllers]]; id obj=[viewContrlls objectAtIndex:1]; [[self navigationController] popToViewController:obj animated:YES]; [viewContrlls release]; A: You should use popToRootViewControllerAnimated: From UINavigationController class reference: Pops all the view controllers on the stack except the root view controller and updates the display. A: You can return to the first view with [self.navigationController popToRootViewControllerAnimated:YES]; That being said, you can also remove a particular view controller, or navigate to a specific index in your view controller if you look at the example. NSMutableArray *allViewControllers = [NSMutableArray arrayWithArray:navigationController.viewControllers]; // You can now manipulate this array with the methods used for NSMutableArray to find out / perform actions on the navigation stack [allViewControllers removeObjectIdenticalTo: removedViewController]; // You can remove a specific view controller with this. navigationController.viewControllers = allViewControllers;
{ "language": "en", "url": "https://stackoverflow.com/questions/7516240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Very basic AChartEngine XY I've been trying for hours to get something as simple as displaying a line chart based on 2 dots that I supply manually and all I get is a crash. I've tried to understand how everything works based on the demo code but it's too complex. I'm not even concerned about writing nice code with onResume() etc, I just want something to display the first time I open the activity. Once I know how to do that I'll be able to adapt and learn what I need. Here's the code I came up with: public class StatsActivity extends Activity { private XYMultipleSeriesDataset StatsDataset = new XYMultipleSeriesDataset(); private XYMultipleSeriesRenderer StatsRenderer = new XYMultipleSeriesRenderer(); private XYSeries StatsCurrentSeries; private GraphicalView StatsChartView; protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.stats); LinearLayout layout = (LinearLayout) findViewById(R.id.Statschart); StatsRenderer.setAxesColor(Color.YELLOW); String seriesTitle = "Rank"; XYSeries series = new XYSeries(seriesTitle); series.add(5, 7); //1st series I want to add StatsDataset.addSeries(series); series.add(9, 1); //the 2nd one StatsDataset.addSeries(series); StatsCurrentSeries = series; System.out.println(series); XYSeriesRenderer renderer = new XYSeriesRenderer(); renderer.setColor(Color.RED); StatsRenderer.addSeriesRenderer(renderer); StatsChartView = ChartFactory.getLineChartView(this, StatsDataset,StatsRenderer); layout.addView(StatsChartView); } } I've been reading the docs to determine what each function does but in the end I still can't get anything to display. Thanks! A: The big thing that I struggled with is that you need a renderer for each XYSeries. You have two series here, but just one renderer - I just create/add renderers when I input data. Also, Android is mostly pass-by-reference, so you've passed the same data set in twice (i.e. your second update to the data will be mirrored "in" the MultipleSeriesDataset).
{ "language": "en", "url": "https://stackoverflow.com/questions/7516245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to play mp3 music files (more than one music) in java? I write some core java code to a play one mp3 file in java .I was successful. But i want to play more than one mp3 music file sequentially one by one in java. can it be possible ?? If possible plz help me. Here is the demo code , import java.io.BufferedInputStream; import java.io.FileInputStream; import javazoom.jl.player.Player; public class MP3 extends Thread{ static int k=0; private String filename; private Player player; // constructor that takes the name of an MP3 file public MP3(String filename) { this.filename = filename; } public void close() { if (player != null) player.close(); } // play the MP3 file to the sound card public synchronized void play() { try { FileInputStream fis = new FileInputStream(filename); BufferedInputStream bis = new BufferedInputStream(fis); player = new Player(bis); } catch (Exception e) { System.out.println("Problem playing file " + filename); System.out.println(e); } // run in new thread to play in background new Thread() { public void run() { try { player.play();} catch (Exception e) { System.out.println(e); } } }.start(); } // test client public static void main(String[] args) { String filename = args[0]; //StringBuffer br= new StringBuffer(filename); StringBuffer mp3_name = new StringBuffer(); String arr[]=new String[3]; String mp3temp=filename; for(int i=0;i<mp3temp.length();i++) { int count = mp3temp.indexOf(","); System.out.println(count); if(count != -1) { String temp = mp3temp.substring(0,count); System.out.println(temp); mp3_name.append(temp); arr[k++] = temp; mp3temp = mp3temp.substring(count+1,mp3temp.length()); } if(count == -1) { if(mp3temp.endsWith("mp3")) { mp3_name.append(mp3temp); arr[k++] = mp3temp; System.out.println(mp3temp); break; } } } StringBuffer bb=mp3_name; String test =""; String subtest =""; for(int s= 0;s < arr.length;s++) { System.out.println(arr[s]); MP3 mp3 = new MP3(arr[s]); mp3.play(); System.out.println(arr[s]); // do whatever computation you like, while music plays int N = 4000; double sum = 0.0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { sum += Math.sin(i + j); } } System.out.println(sum); // when the computation is done, stop playing it mp3.close(); // play from the beginning mp3 = new MP3(arr[s]); mp3.play(); //} } } } Pass mp3 files from comand prompt by separating commas. ex :java MP3 test.mp3,a.mp3,b.mp3 Thanks Bipin A: It is definitely possible. If reading from a directory say your C:\Music, then simple have your program read in all of the locations (I am assuming you are reading in only one at the moment). Then execute on each of those files by calling your play method(Im assuming you have something similar)) You can loop that method or have it play down the list etc etc. I can elaborate if you post a snippet of your code. EDIT: I didnt know you were using command line arguements, so I will try and help the best I can. You should be able to read in each arguement and have it execute on each one until there are not left using a for loop. public static void main(String[] args) { //declare the length of your args int length = args.length; Once thats done you can run the play method on each of the songs. //Perform your loop for (int i = 0; i < length; i++) { //Call your play method here } // End Loop //When done you can print something System.out.println("All Songs have been played"); } A: Similar to what birryree said in his comment. You could change the MP3 class to store a list of filenames. Play can then loop over these playing each in turn.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery templates iterate on value, not number of keys Using the jquery template plugin is pretty straighforward, but i'm facing an issue quite simple to explain. I'd like to iterate in my template based on the value of one key I get; for example num_lines : 15 {{each (var i = 0; i < ${num_lines}; i++)}} poet {{/each}} While logic is ok, it does'nt do the trick. Any idea where i'm wrong ? Thanks. A: {{each}} expects some sort of collection. You will need to build up a collection from your count to use it. You could simply create a helper function for your template and pass it in the options parameter. Here's a sample jsFiddle jQuery template that uses an each-friendly custom function. You simply give it the word you want repeated and how many times and {{each}} does the work for you. Template <script id="itemTemplate" type="text/x-jquery-tmpl"> <ul> {{each(i, prop) $item.makeArrayForEach("poet", $data.someInteger)}} <li>${prop}</li> {{/each}} </ul> </script> JavaScript var makeArrayForEach = function (word, size) { var i, result = []; for (i = 0; i < size; i++) { result.push(word); } return result; }; $("#itemTemplate").tmpl(yourObject, { makeArrayForEach: makeArrayForEach }).appendTo($(".results")); A: i don't think each is meant to use in this fashion. the only thing I can think of is doing: javascript: var poet = [{ {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"}, {Poet:"poet"} }]; HTML: {{each Poet}} ${$value} {{/each}}
{ "language": "en", "url": "https://stackoverflow.com/questions/7516254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is using optional parameters for backwards compatibility a good idea? I was wondering about providing backwards compatibility by using optional parameters. In my program I have an interface with a function that is used throughout my program as well as in a lot of unittests. For some new functionality, a boolean has to be passed into this function which will alter its behaviour if set to false. If you pass in true, you will get the same behaviour as before. Now I have to pass in true everywhere where in my current code where I have called this function before. That is why I was thinking: "Ok I just put true as the default value of the boolean. Then I only have to pass in false in the few new places where I need the new behaviour." I feel however, that my motivation to make the interface this way is to have to do less coding now. Usually when that is the only motivation I can think of it is a short-cut and will probably bite me later on. I cannot think of anything that will cause problems later on though, which is why I post this question here. Next to my situation as I described above, is it a good idea in general to make a new parameter optional for backwards compatibility (e.g. in interfaces that are used by third parties)? Thanks in advance. A: I good reason against would be that optional parameters default values are only used at compile time (except when using the dynamic keyword). So if your third party is trying to use the new version without recompiling their code (such as having your library marked as a dependency in nuget) it would not be compatible because the signature has an extra parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating an SQL Server connection string without importing a datasource in C# I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to. So how can I manually create the connection string? I am using SQL Server 2005. A: Step 1: Go to connectionstrings.com and find the proper format for your database. Step 2: Plug in the appropriate values to the connection string. Step 3: Pass that string to the constructor of SqlConnection. I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to: SqlConnection sqlConn = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString); A: I don't see where the connection string is "compiled". In the code SqlConnection con = new SqlConnection( ConsoleApplication1.Properties.Settings.Default.masterConnectionString) ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string. A: for SQL Server format of the connection string is "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;" save this connection string in a string variable and use with connection object. either way you can add in web.config file. <ConnectionString> <add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/> </ConnectionString> you can change the provider as needed by you. then in code behind file access this particular connection string using configuration manager.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pass argument to mouseCallback I have a simple, but problematic question. Is there a way, using google script to send an argument to a mouseCallback? Some examples are explained here, but each time the cell in written in the function. I want this cell to change over time, and I need to pass a string to the callback. This works function foo() { var doc = SpreadsheetApp.getActiveSpreadsheet(); var app = UiApp.createApplication(); var button = app.createButton('submit'); app.add(button); var handler = app.createServerClickHandler('b'); button.addClickHandler(handler); doc.show(app); } function b() { var doc = SpreadsheetApp.getActiveSpreadsheet(); var cell = doc.getRange('a1'); cell.setValue(Number(cell.getValue()) + 1); var app = UiApp.getActiveApplication(); app.close(); // The following line is REQUIRED for the widget to actually close. return app; } I would like something like this function foo() { var doc = SpreadsheetApp.getActiveSpreadsheet(); var app = UiApp.createApplication(); var button = app.createButton('submit'); app.add(button); var value = 'A1'; var handler = app.createServerClickHandler('b', value); button.addClickHandler(handler); doc.show(app); } function b(value) { var doc = SpreadsheetApp.getActiveSpreadsheet(); var cell = doc.getRange(value); cell.setValue(Number(cell.getValue()) + 1); var app = UiApp.getActiveApplication(); app.close(); // The following line is REQUIRED for the widget to actually close. return app; } Can anyone help me in this? Thanks ! A: There is answers to this question in here : Thansk to google forum users :) http://www.google.com/support/forum/p/apps-script/thread?fid=2ef3693fc9aee1050004ad903de88dd4&hl=en
{ "language": "en", "url": "https://stackoverflow.com/questions/7516267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using libunwind on HP-UX and getting stacktrace I have a C application that is executing in an HP-UX environment and I need to get the stacktrace. I am attempting to use U_STACK_TRACE, but output to stderr is going somewhere else and I need it printed to a string. How can I do this? I.E. How can I take the output from U_STACK_TRACE and put it in a string instead of it being written to stderr. A: U_STACK_TRACE() prints a formatted stack trace to standard error. _UNW_STACK_TRACE() produces a formatted stack trace on the output stream indicated by parameter out_file. The stream must be a writable stream for output to be produced. So, open a file using fopen() and call _UNW_STACK_TRACE() instead of U_STACK_TRACE().
{ "language": "en", "url": "https://stackoverflow.com/questions/7516273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need some basic github help I am trying to learn github to deploy a webpage. Here are the steps I am taking: git checkout master git pull origin master git checkout –b my-awesome-branch Do some work, do a git status to check on everything, everything is ok. git add . git commit –m "awesome message here" git push origin my-awesome-branch git checkout integration git merge my-awesome-branch git push origin integration cap development deploy this will push a file to the dev server we have so people can look at it - this worked fine for me you won't be able to see the link but it generates something like this: http://dev.mywebsite.com/events/email/welcome Let's go live (pretending there are no further changes) git checkout master git merge my-awesome-branch git push origin master cap production deploy In theory, the file should push to the live website (which would be http://mywebsite.com/events/email/welcome) but that webpage is not created when i cap production deploy. Another developer more familiar with this system says : It looks like you forked "my party events" repo and have pushed the master there. You'll want to push master to the upstream remote (the main "my party events", or my_events repo.) I don't follow this step. Can anyone follow this logic? If so, do you have a suggestion for me on what i may be doing wrong? Any help is appreciated. A: If you have a forked branch on Github, that means you have a copy of the entire git repo under your name. Check your Github account to verify this. To do this, go to https://github.com/your-github-user-name-here. On the left side, look for "my-party-events" (assuming that's the repo name). Underneath it, look for "forked from xyz/my-party-events". If you don't see 'forked from ...', then you're the original owner of that repo. This shouldn't be the case. If you do see 'forked from ...', then you have a copy under your name (that's what a fork is). Any changes you make to a fork don't affect the original repo. If you're with me up to here, there's 2 ways you can go. Via Git (Recommended) Whenever you did a git pull or git push earlier, you were specifying origin, which is a human-readable name for a repo that you set up earlier. The repo address actually looks like this git@github.com:your-user-name/project-name.git As you can see, referring to it by a nickname like 'origin' is way easier to remember. Assuming you have write access to the main project repo, you can just add another repo to your config. Make sure you have write access before attempting this, otherwise you're just wasting your time. Ask your coworker if you're not sure. Lets say you wanted to nickname the repo as 'production', you would do this git remote add production git@github.com:PROJECT_OWNER/project-name.git The git repo address looks almost identical to your fork repo. It differs only by username. On the front page of all Github projects, the repo address is in a text field. It's next to the "SSH | HTTPS | Git Read-only" buttons. Get the address from there, replace it in the command above, and finally, do this in your command line git push production master From now on, you can just git push production master, which is pretty simple. If you don't have write access, then you'll have to submit changes via pull requests. Through the Website You can submit a pull request to the repo you forked from. A pull request asks the original repo admin to include changes you've made on your fork. To submit a pull request, click on your project fork from your projects page. Look for the 'Pull Request' icon near the top right. That should take you to a page where you can choose the target and source branches.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can TeamCity check out code to more than one machine Can I have TeamCity Build server check out code to another server or machine, in addition to itself? What I am asking is can I run build configurations that automatically checks out, udpates source code from TFS into multiple servers. Each Build configuration handling a different server? A: I didnt try it myself, but waht you could try is to set the "Checkout directory" in the "Version Control settings" to an network dir. for example \10.30.9.1\d$\project\ or "map" a network drive on the TeamCity Build server
{ "language": "en", "url": "https://stackoverflow.com/questions/7516294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Routing ASP.NET MVC root application to MVC virtual directory I have an MVC application setup as a root application. With in that root dir I have a virtual directory that is also an MVC app. I need to navigate from the root app to the virtual directory. The first hurdle was finding the controller that existed in another namespace, and I was able to do that as follows.. Dim namespaceControllers() As String = {"ExternalAssemblyName"} routes.MapRoute( _ "virtualroute", _ "ExternalAssemblyName/{controller}/{action}/{id}", _ New With {.controller = "testvir", .action = "Index", .id = ""}, _ namespaceControllers _ ) routes.MapRoute( _ "Default", _ "{controller}/{action}/{id}", _ New With {.controller = "Home", .action = "Index", .id = ""} _ ) It correctly finds the controller, however it still tried to locate the view in the root application, not the virtual dir. If I move the View from the virtual dir to the root dir, it works. A: Routes can be tricky. I can't recommend a fix without seeing your application (someone with more experience might be able to), but I can suggest installing the RouteDebugger tool to help with routing issues. It has helped me work out routing issues multiple times. It's also available as a NuGet package.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace continuous space with single space and multiple "&nbsp" elements I have one html document which contains whitespaces in some nodes. For example, <B>This is Whitespace Node </B> When this html is displayed in the browser, more than one continuous space in html is always displayed as one space. To avoid this issue, I want to replace the continuous spaces with a single space and multiple &nbsp; elements. What is the best solution to achive this? I am using C# 2005. A: Try this, string str = "<B>This is Whitespace Node </B>"; Regex rgx = new Regex("([\\S][ ])"); string result = rgx.Replace(str, "$1.") .Replace(" .","?") .Replace(" ","&nbsp") .Replace("?"," "); A: Use CSS's white-space property as per http://www.w3.org/TR/CSS2/text.html#white-space-prop white-space: pre-wrap Or, if you really want to do it with bruteforce, replace two consecutive spaces with a non-breaking-space and a normal space... I strongly recommend against this. string text = originalText.Replace(" ", "&nbsp; "); A: You can try String.Replace(" ", " ") if you prefer regex Regex rgx = new Regex("([ \t]|&nsbp)+"); string result = rgx.Replace(input, " "); A: I assume you are setting the value of the control from code behind? If so then ... <strong><asp:Literal id="myLiteral">This is Whitespace Node </asp:Literal></strong> And in code behind ... var myText = "This is Whitespace Node "; myLiteral.Text = myText.Replace(" ", "&nbsp;"); If no code behind or not in a literal ... <strong><%= "This is Whitespace Node ".Replace(" ", "&nbsp;") %></strong>
{ "language": "en", "url": "https://stackoverflow.com/questions/7516311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MySQL leading whitespace with C# When I update a field in my MySQL database, it always adds a whitespace to the value. I tried to remove the whitespace with the trim-command and the replace-command. Neither of them worked. So I expect that it isn't a whitespace but some vague ASCII character. These are the commands I used: this.foo = result.GetValue(0).ToString().Trim(); this.bar = result.GetValue(0).ToString().Replace(" ",""); The field it updates is a VARCHAR(xx). This is my MySQL update command: MySqlCommand cmd = new MySqlCommand("UPDATE " + table + " SET " + new_field + " =' " + new_value+ "' WHERE " + field+ "= " + value + "",this.con); this.con is my connection to the MySQL database. FYI: I use .NET 3.5CF with a mysql.data.cf DLL in Visual Studio 2008. Could someone help me out with this problem? It's driving me nuts. A: Well yes, you've got a leading space in the SQL: "UPDATE " + table + " SET " + new_field + " =' " + new_value+ "' Note the bit straight after "=" - you've got a quote, then a space, then new_value. However, you shouldn't be putting the values in the SQL directly in the first place - you should be using parameterized SQL statements... currently you've got a SQL injection attack waiting to happen, as well as potential problems for honest values with quotes in. You should use parameterized SQL for both new_value and value here... I'm assuming that field and table come from more "trusted" sources? A: This appears to have a space where the * is " ='*" + new_value
{ "language": "en", "url": "https://stackoverflow.com/questions/7516313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Routed Events problem - hitting the root UI element before the child element My routed events are hitting the root UI element before the child element. Is this expected? How can I have the routed events hit the child element first? Objective: If text is typed anywhere other than "custom textbox", put text in "default textbox" Result: Window_PreviewTextInput is being hit before custom_PreviewTextInput, even if my cursor focus is on "Custom Textbox" What should I do differently? XAML <Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" SizeToContent="WidthAndHeight" PreviewTextInput="Window_PreviewTextInput" > <Grid Margin="100,100,100,100"> <StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="default" Width="100"/> <TextBox x:Name="defaultTB" Width="300" Height="50"/> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Text="custom" Width="100"/> <TextBox x:Name="custom" PreviewTextInput="custom_PreviewTextInput" Width="300" Height="50"/> </StackPanel> </StackPanel> </Grid> </Window> Code Behind: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } //goal: if text is typed anywhere except custom textbox, put text in default textbox private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e) { Keyboard.Focus(defaultTB); } //goal: if text is typed in custom TB, put text there, and end the event routing private void custom_PreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = true; } } } A: Routed Event could be a bubbling or tunneling. You've a tunneling event behaviour. From MSDN, UIElement.PreviewTextInput Event: Routing strategy - Tunneling The corresponding bubbling event is TextInput. Routed Events Overview - Routing Strategies: Bubbling: Event handlers on the event source are invoked. The routed event then routes to successive parent elements until reaching the element tree root. Most routed events use the bubbling routing strategy. Bubbling routed events are generally used to report input or state changes from distinct controls or other UI elements Direct: Only the source element itself is given the opportunity to invoke handlers in response. This is analogous to the "routing" that Windows Forms uses for events. However, unlike a standard CLR event, direct routed events support class handling (class handling is explained in an upcoming section) and can be used by EventSetter and EventTrigger. Tunneling: Initially, event handlers at the element tree root are invoked. The routed event then travels a route through successive child elements along the route, towards the node element that is the routed event source (the element that raised the routed event). Tunneling routed events are often used or handled as part of the compositing for a control, such that events from composite parts can be deliberately suppressed or replaced by events that are specific to the complete control. Input events provided in WPF often come implemented as a tunneling/bubbling pair. Tunneling events are also sometimes referred to as Preview events, because of a naming convention that is used for the pairs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Format code in Doxia Apt Format I am currently starting to write a documentation for one of our projects. For reasons of simplicity we chose to use the Almost Plain Text (APT) Format, see more info here: http://maven.apache.org/doxia/references/apt-format.html APT is great documentation format, since it uses a minimal syntax and hence it is very easy to create and make changes to the documentation without knowing a lot about APT. However, I couldn't find a way to format code in a nice way. Is there a code tag or similar, which can be used to include some source code? I'm aware I could use FML, but this would be less desirable. Thanks A: Apache Maven Fluido Skin highlights syntax out of the box. Here you can find an example. Information about syntax highlighting in Fluido: "Source code sections are enhanced by Google Code Prettify, users can optionally enable line numbers rendering (disabled by default)" from Fluido website. A: The +--------------------- code +--------------------- syntax is correct. And Fluido does highlight using Prettify out of the box as others have mentioned. However, a Doxia change in Site Plugin 3.3 broke Fluido. MSKINS-86 fixes this, but hasn't been released yet. Workarounds * *Use the site.xml workaround <body> <head> <script type="text/javascript"> $(document).ready(function () { $("div.source pre").addClass("prettyprint"); prettyPrint(); }); </script> </head> </body> *Use Site Plugin 3.2 *Build the unreleased Fluido 1.4 that contains MSKINS-86 fix and use it instead of 1.3.1 A: I ended up using the snippet macro from the Doxia Macros Guide: http://maven.apache.org/doxia/macros/index.html#Snippet_Macro It puts the code from the snippet file in a verbatim box. However it does not provide a syntax highlightning. A: For those who are still wondering how to make a code snipped in APT: This is regular text +--------------------- This is a code snippet +--------------------- More regular text A: Version 1.0 of doxia include macro is not at maven central however the following versions are: http://mvnrepository.com/artifact/org.tinyjee.dim/doxia-include-macro
{ "language": "en", "url": "https://stackoverflow.com/questions/7516315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: the new facebook like, that open the comment box...+ overlow:hidden a quick introduction : facebook has changed the LIKE (count) button into something like : LIKE (count) [ -------------------- clic = open a Big zone bottom / right --------------------] problem : Its nice BUT .... you forgot that a lot of website are using the like button in "toolbars". Page example Header Left column Tooblbar, include fb:like -------------------- Right column Document content Footer and lot of structured pages/ blocs are using "overflow:hidden" !! So it makes the displayed widget randomly truncated everywhere (right, bottom...) depending of its environnement. Its impossible to remove all the overflow:hidden from the containers blocks, to satisfy a widget update. What can we do. Some sites where clean, now they look drafts, with all button opening truncated stuff... any solution ? A: If you want to use the Facebook plugin, the only solution seems to be to change the HTML/CSS so overflow:hidden can be removed. Alternatively, you could try to use a service that forwards the user actions to social networks for you and offers different methods of website integration. A: If you're not using overflow: hidden for semantic reasons, you could always change it to overflow: visible or just remove it. I'm assuming that the fix isn't that simple... A quickfix that wouldn't require you to modify your CSS would be to place your FB Like button outside of any containing elements that have overflow: hidden or overflow: auto and use absolute positioning to get it where you want it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7516316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }