text
stringlengths
8
267k
meta
dict
Q: How do I invoke a Javascript that does not have a name using C# I would like to invoke a Javascript function on a web page that does not have a function name. Using C#, I would normally use Webbrowser.Document.InvokeScript("ScriptName"). In this instance however, there is only a type attribute. This is what it looks like: <script type="text/javascript"> (function(){ SOME CODE HERE; })(); </script> A: That is a self-invoking function. It will run as soon as that statement is executed. It is not possible to run it again without modifying the script. A: As long as this closure does not export methods to the global namespace, you can't A: Expose a Method. <script type="text/javascript"> (function(){ MyFunction = function() { SOME CODE HERE; } })(); </script> Webbrowser.Document.InvokeScript("MyFunction");
{ "language": "en", "url": "https://stackoverflow.com/questions/7628136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: During Eclipse debugging While debugging my code in eclipse IDE, the code enters into some class files. Please refer to the screen shot here, ![enter image description here][1] http://imageshack.us/f/26/newposterh.jpg/ I get confused here. Please tell me what is the best way to recover in this case A: You get NoSuchMethodException. It can happen only if your sources are not synchronized. Meaning during the compilation you used one class, but in runtime you have replaced it with a different version of this class. Check your classpath. A: It looks like your application threw an exception. Set some break points before the exception is thrown and attempt to determine why the exceptions was thrown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: TFTP server written in C - Binary diff at the client end shows a difference but not always I have written a tftp server in C . The tftp client I am using is the native linux client . The file transfer seems to happen correctly . The sent and received file sizes appear to be the same . But if I do "cmp" on both the files there is a difference . I have attached the function which sends "512 bytes" of data or less to the client. I am not sure if there is any padding being introduced but I don't know where that might happen . void send_next_data (int client_id) { int opcode = 0; int block_id = 0; unsigned long bytes_left = 0; unsigned long offset = 0; unsigned long file_length = 0; char *ptr = buffer_send; int total_bytes = 0; int result; int i; opcode = 3; client_list[client_id].prev_blockid += 1; block_id = client_list[client_id].prev_blockid; opcode = htons(opcode); block_id = htons(block_id); bzero(buffer_send,520); memcpy(ptr, &opcode, sizeof(uint16_t)); ptr += sizeof(uint16_t); memcpy(ptr, &block_id, sizeof(uint16_t)); ptr += sizeof(uint16_t); total_bytes += 4; offset = client_list[client_id].offset; file_length = client_list[client_id].file_length; if(offset < file_length) { bytes_left = file_length - offset; if(bytes_left > 512) { memcpy(ptr, &client_list[client_id].file[offset], 512); ptr += 512; total_bytes += 512; client_list[client_id].offset += 512; } else { memcpy(ptr, &client_list[client_id].file[offset], bytes_left); ptr += bytes_left; total_bytes += bytes_left; client_list[client_id].offset += bytes_left; } } result = sendto(socket_list[client_id], buffer_send, total_bytes, 0 , (struct sockaddr *)&client_list[client_id].clientAddr, client_list[client_id].clientAddrLen); printf(" total_bytes sent = %d, result = %d , client id = %d, send on fd = %d\n", total_bytes, result, client_id, socket_list[client_id]); // printf(" Error = %d\n", errno); } I copy the data from the binary file onto a buffer and then use offsets on this buffer to transfer 512 or less bytes of data . To test if the file has been copied to the buffer properly ,I wrote this buffer back to a "test" file and a cmp between the source and this "test" file says there is no difference. fseek(fp, 0L, SEEK_END); client_list[n].file_length = ftell(fp); fseek(fp, 0L, SEEK_SET); client_list[n].file = malloc((client_list[n].file_length+100) * sizeof(char)); bzero(client_list[n].file, client_list[n].file_length+100); i=0; c = getc(fp) ; while (!(feof(fp))) { client_list[n].file[i] = c; c = getc(fp); i++; } printf(" Number of bytes read from file = %ld , size of file = %ld \n", i, client_list[n].file_length); send_next_data(n); fclose(fp); fp = fopen("test", "wb"); fwrite(client_list[n].file, 1,client_list[n].file_length ,fp); fclose(fp); I generate binary files using time dd if=/dev/urandom of=random-file bs=1 count=xxxx and send it . For a file size of 77940 bytes , cmp says that the first diff appears at byte 44393 . Any help would be appreciated .
{ "language": "en", "url": "https://stackoverflow.com/questions/7628174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to set value of property defined at C# to javascript Is it possible to set value of property defined at C# to javascript... c# Code. public int val { get; set; } Now i want to set val property at java script function A: You could do a <% Response.Write( val )%> , or <%= val %> in the .aspx page if you wanted something quick and dirty. Edit If you want to go the reverse. No, it's not really possible. You might look into WebMethods, but that's not directly what you want to do. A: Not implicitly. You can register a startup script with this class. http://msdn.microsoft.com/en-us/library/stax6fw9.aspx A: Are you trying to se a property on a class from javascript or a javascript variable from a C# property? The former isn't possible directly as the C# code isn't available on the client. The latter can be done on the server before the response is sent to the client, but how would depend on whether you are doing web forms or ASP.NET MVC. Ex: to set javascript value from a C# property using MVC/Razor <script type="text/javascript"> var jsVariable = '@Model.CSharpProperty'; </script> A: It is not possible to do that. asp.net is a serverside technology and javascript is clientside. A: I may be wrong but I think the question is about using "Properties" in Javascript like you can do in C# if you want to syntactically hide a method or function with a variable assignment? If that is the case then yes. You can use "Properties" in Javascript. http://en.wikipedia.org/wiki/Property_(programming)#JavaScript
{ "language": "en", "url": "https://stackoverflow.com/questions/7628175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to zip archive individual sub folders I have a main folder called "Test" under that I have around 100 sub folders starting from test 1, test 2 ..... test 100. I am trying to create a work flow in Macautomator. But it puts all the 100 folders into one big archive file rather than creating 100 archive files with its original name in the mail Test folder. am I expecting too much from the automator. I would greatly appreciate your help . thanks in advance. A: I can help you out. Create the following Automator Workflow: * *Ask for Finder Items * *select folders *Set Value of Variable * *variable name I put was "folder" *Get Folder Contents * *select "Repeat for each subfolder" *Dispense Items Incrementally *Create Clean Archive * *select "Deleting original files" *Loop * *select "Loop Automatically" and "stop after 100 times" (or how many you want) This should work. I tested it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java Scanner, taking user input from console into array list as separate words I am trying to read the user input from the console directly into an array list, separated by each word or entity that has whitespace on either side (the default behavior). The problem is I am stuck inside of a while loop. Scanner.next() keeps waiting for more input, though I know I want to stop feeding input after the user presses return: Scanner input = new Scanner(System.in); System.out.print("Enter a sentence: "); do { if (words.add(input.next()); } while (input.hasNext()); System.out.println(words); I input a line, except I will have to press CTRL-D to terminate it (IE. signal the end of input). I just want to automatically end it when the return '\n' character is pressed at the end of the sentence. A: It may be simpler to use split for what you want. // read a line, split into words and add them to a collection. words.addAll(Arrays.asList(input.nextLine().split("\\s+"))); A: You could always use the Console class, like this: Console console = System.console(); System.out.print("Enter a sentence: "); List<String> words = Arrays.asList(console.readLine().split("\\s+")); System.out.println(words); The readline() method should take care of the \n issue. If you require a Scanner for the type reading capabilities, you can mix both classes: Scanner scanner = new Scanner(console.reader()); Hope this helps! A: You could call input.hasNextLine and input.nextLine to get a line, and then create a new Scanner for the line you got and use the code that you have now. Not the cheapest solution, but an easy way to implement it until you come up with a better one :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set a minimum delay for BlockUI? I'm trying to set a minimum display of the BlockUI but having trouble. No matter what value I put in setTimeout, the element is unblocked immediately. Here I'm setting up the options for the jQuery ajaxForm plugin: var options = { type: 'POST', contentType: 'application/json; charset-utf-8', dataType: 'json', complete: function () { setTimeout($('#MyElement').unblock(), 5000); } }; And here I'm showing the BlockUI on 'MyElement' when my submit button is clicked. $('.submit').click(function () { window.showBlockUI($('#MyElement')); }); Any ideas? Thanks. A: You are calling the function in your setTimeout(), not passing a reference to a function so it executes immediately and passes the return result of that function to setTimeout(). Thus it executes immediately. Change it to this: complete: function () { setTimeout(function() {$('#MyElement').unblock()}, 5000); } or in a little less compact form where you can see it better: complete: function () { setTimeout(function() { $('#MyElement').unblock() }, 5000); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Regex match in google app engine webapp WSGIApplication Hi A rather simple question: application = webapp.WSGIApplication([ ('/result', Result), ('/result/', Result), The only difference is the trailing '/'. Can I merge the two url mapping into one? A: For SEO reasons, it is usually better to choose one URL to handle, and redirect the other to the chosen one. Otherwise search engines will see duplicate content. For example something like this: class RedirectHandler(webapp.RequestHandler): def get(self): self.redirect("/result/", True) application = webapp.WSGIApplication([ ('/result', RedirectHandler), ('/result/', Result), ... A: '/result/?' The question mark makes the preceding character optional. A: by default the google app engine will recognize /result/ same as /result so you can just go with application = webapp.WSGIApplication([ ('/result', Result), you can as well make regular expressions for links such as application = webapp.WSGIApplication([ ('/block/([0-9]+)/permissions', Result),
{ "language": "en", "url": "https://stackoverflow.com/questions/7628187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is a good idea to use a GUID in name of files generated by users? I'm building a application (a CMS) where user can upload files like images. My question is how to rename these files to save. I think generate a GUID (System.GUID.NewGuid()) to save a file is the best way to go. I'm right or exist better approach in this case? Note: An example of the GUID that is generated: 7c9e6679-944b-7425-40from-e07fc1f90ae7. In that case a image file will be: 7c9e6679-944b-7425-40from-e07fc1f90ae7.jpg Update: Users will not interact directly with the name of the file. A: Yes. But probably a much more convenient scheme would use a hash-sum (say the MD5-sum) of the contents. That way, * *the generation of the filename is repeatable (in case something goes wrong, data needs to be migrated to a different server, content is shared across different intallations etc). *you'd automatically share duplicate uploads. Of course, then you'd need to track who owns the file (and not delete it untill the last usage is deleted) Note An example of a typical md5sum is 5eb63bbbe01eeed093cb22bb8f5acdc3 (for ASCII/UTF8 "hello world") Edit in response to the comments (about hash collisions): True enough, you might get hash collisions with very large sets of documents. In that case, it is most common to use the hash sum + the length of a file to identify the 'content blob'. So you'd do something like: http://cms.mysite.local/docs/123986/5e/b63bbbe/01eeed093cb22bb8f5acdc3.png for a png of length ~ 123Kb A: If you want better SEO, you should add something before the GUID. Better is to generate your own unique id in combination with something that explains the image/file (because of SEO). For example if you have an item, the image name can be something like: itemId-ItemName.jpg A: Yes, that approach is fine. It's very similar to the way that Git stores its files. If you're doing things the same way Linus Torvalds does then you're probably doing it right. A: Typically I'll first save the uploaded file to a temp file via Path.GetTempFileName, then move it to permanent storage with an appropriate name after its passed whatever checks are appropriate. See: http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename%28v=vs.80%29.aspx For permanent storage, guid-based file names are fine and depending on your DB server such names can be nicely indexed as well for quick querying. A: Will the user ever need to interact with the file directly via it's name? If not then using a GUID is perfectly fine. If you store the association between the name the user supplied name and the generated name then the user need never see the GUID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is it possible to use google tcmalloc to get per thread memory usage Like the title says I'm interested if I can see per thread memory usage on programs compiled with -ltcmalloc. AFAIK with regular malloc memory is linked to process not to thread, but I'm not sure about tcmalloc. A: TcMalloc has some per-thread memory caches. But they are just a proxy to a shared heap (to reduce the congestion). All the memory in tcmalloc comes from a single shared pool. Alive (allocated) memory may be passed freely from one thread to the other, so it's not easy to say which thread uses it. You could monitor which thread allocated the used memory, but you would need either completely separated memory pools (not very elastic) or some per-allocation memory overhead. Neither of those is present in tcmalloc... A: There is no such thing as per-thread memory usage. Memory is a process resource.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding new input:checkbox and not has value I have problem in add new input:checkbox, when i adding new input and checked on it next setup clicked on button i not have value for input:checkbox that was checked. how is fix it? DEMO: http://jsfiddle.net/G4QRp/ $(function () { $('a.add_input').live('click', function (event) { event.preventDefault(); var $class = '.' + $(this).closest('div.find_input').find('div').attr('class').split(" ")[0]; var size_un = $($class).length; var $this = $(this), $div = $this.closest($class), $clone = $div.clone().hide().insertAfter($div).fadeIn('slow'); $clone.find('.adda').not(':has(.remove_input)').append('<div class="mediumCell"><a href="" class="remove_input"></a></div>'); $clone.find('input').val('').prop('checked', false); $this.remove(); var size_un = $($class).length---1; $($class + ':last input:checkbox').prop('name', 'checkbox_units[' + size_un + '][]'); console.log($($class + ':last input:checkbox').prop('name')); }); }); A: Your code always clears the value of all the checkboxes it adds: $clone.find('input').val('').prop('checked', false); It's working fine, though it's quite confusing. The alert correctly shows the checkboxes that are checked, but since your code has set the value to '' for each of them, well, it's empty. If you change it like this: $clone.find('input').prop('checked', false); it shows the values to be the same as the original checkboxes. You might want to think about using "data-" attributes instead of the "class" string for storing things like that "add_units" class name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: create a sort and then retrieve first n method for a List where T: IComparable I want to write a generic method with the following signature : IList<T> Sort<T> (IList<T> list) where T: IComparable <T> that returns a sorted list. sorry for the incomplete original post. so I want to sort the list and then select the first n elements that would be List<T> temp = new List<T>(list); temp.Sort(); List<T> temp2 = new List<T>(temp); temp2.Take(count); the complete question would be how to do that without double - copying the initial list. there would be 2 cases : the list has dupes and I want to retrieve the first n distinct values the list has dupes and I want to retrieve the first n values. for the first case a distinct should be applied also - so a new "third "copy of list to be avoided. of course the answer posted by guffa is accepted, because the OP at first was incomplete. A: Create a new List<T> from the input and sort it: public IList<T> Sort<T> (IList<T> list) where T: IComparable <T> { List<T> temp = new List<T>(list); temp.Sort(); return temp; } The Sort method will use the default comparer when you don't specify one, which uses the IComparable<T> implementation if there is one. Edit: To answer the edited question: You have to copy the list twice if you want to preserve the input and return a list. You could get around the second copying if you return IEnumerable<T> instead of IList<T>. Then you can return a deferred result that reads from the first copy of the list. The drawback is of course that it will keep the entire first list in memory although you only use a part of it. Anyway, the version returning an IList<T> would be something like: public IList<T> Sort<T> (IList<T> list, int cnt, bool distinct) where T: IComparable <T> { IEnumerable<T> temp = list.OrderBy(t => t); if (distinct) { temp = temp.Distinct(); } return temp.Take(cnt).ToList(); } For the version returning an IEnumerable<T> you would just not do the .ToList() in the last step.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle widgets buttons I'm starting with widgets and got a very nice tutorial on the internet, got the example run perfectly, but when i tried to change somethings I got stuck. The thing is: I just want to change the image from my imageButton when i press it, I've tried somethings but nothing seems to work. I didn't get how the RemoteView and Intent works exactly. So if someone can explain it shortly I would appreciate it =) Here's the code: public class HelloWidget extends AppWidgetProvider { private ImageButton wifi; public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget"; public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget"; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); Intent configIntent = new Intent(context, ClickOneActivity.class); configIntent.setAction(ACTION_WIDGET_CONFIGURE); Intent active = new Intent(context, HelloWidget.class); active.setAction(ACTION_WIDGET_RECEIVER); PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0); remoteViews.setOnClickPendingIntent(R.id.button_wifi, actionPendingIntent); remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent); appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); } @Override public void onReceive(Context context, Intent intent) { // v1.5 fix that doesn't call onDelete Action final String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { final int appWidgetId = intent.getExtras().getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) { this.onDeleted(context, new int[] { appWidgetId }); } } else { // check, if our Action was called if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) { Toast.makeText(context, "Teste", Toast.LENGTH_LONG).show(); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); remoteViews.setInt(R.id.button_wifi, "toogleOnOff", R.drawable.icon); } super.onReceive(context, intent); } } } There's a lot of the tutorial code i got as you can see =p Thx since now A: Looks like you need to understand a little more about RemoteViews. When you call functions like setOnClickPendingIntent, setInt, etc. on the RemoteViews object it basically just stores these operations and arguments internally. Then when the widget is displayed it just plays those operations back to construct the widget's views. So after giving the RemoteViews to the AppWidgetManager by calling updateAppWidget, you can't change them again unless you rebuild the whole RemoteViews and call updateAppWidget again. As an answer to your question, you want to use a state list as the background for the button. There's a good example here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unexpected nextLine() behaviour in Java I'm new to java, the nextLine(); doesn't work once and it does all of the other times. I'm confused :( I use eclipse in case you need to know. package tuna; import java.util.Scanner; public class Calculater { public static void main (String args []) { Scanner uno = new Scanner(System.in); System.out.println("How many differant numbers do you want to use? (up to four, minimum two)"); double two = uno.nextDouble(); if (two == 2){ System.out.println("2"); System.out.println("Enter first number: "); double fnum = uno.nextDouble(); System.out.println(fnum); System.out.println("Enter second number: "); double snum = uno.nextDouble(); System.out.println(snum); System.out.println("Enter number operation (Say plus, minus, divide or times. No capitials please)"); String op = uno.nextLine(); . above the uno.nextLine doesn't work. Why? if (op.equals("plus")){ System.out.println(fnum + snum); } } double three; double four; } } EDIT: What I mean by 'it doesn't work' is that after "Enter number operation (Say plus, minus, divide or times. No capitials please)" is printed in the output, I can't type anything in. When you run it says how many numbers do you want? I type 2 and enter. Then it says enter first number. I say 1 and enter. Then it says enter second number. I say 1 and enter. Then it says what number operation. It doesn't let you type even though there is a nextLine(); in there. If you add another nextLine(); in there you can type, but if you type plus, nothing happens, where it should print the first number add the second number. A: After you have read what you want from a line, you need to call nextLine() to get the remaining line (even if its empty) A: If you input: 3.5<enter> 2<enter> divide<enter> Then uno.nextDouble(); consumes 3.5 and leaves <enter> 2<enter> divide<enter> Then uno.nextDouble(); consumes <enter>2 and leaves <enter> divide<enter> Next uno.nextLine(); just consumes <enter>. You need to call uno.nextLine(); again in order to consume the remaining divide<enter>.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Avoiding "Unique field" conflicts in inheritance My situation I have an entity model with a base class ItemBase which defines an ID, a name and a few other properties. The "ID" column is the identity, the "Name" colum is an unique field in the base table. This base class is also defined as an abstract class. So yes, it is a table in the database, but in EF4 I cannot create instances of this base class. And I have five different entities that inherit from the base class. (Item1, Item2...Item5) So all of them inherit the properties of ItemBase and additional properties are stored in an alternate table. One table per type. Quite nice, actually! My problem An object of type Item2 could have the same name as an object of Item5. This would cause a problem since they would both end up with a record in the ItemBase table, and the Name field would be in conflict. That's just nasty. So if the Item2 class contains brands of television manufacturers and Item5 contains lists of smartphone manufacturers then "Samsung" cannot be added in both entity sets. I need a solution that will work around this problem, while keeping it simple. (And without adding the Name field to all child tables, because YUCK!) Suggestions? Way to solve this? Because "Name" is in the base table and defined as 'Unique', I will end up with conflicts when two different entity classes have the same name. I need a solution where "Name" is in the base table, yet it's unique per child class only, not unique for the base class... I could alter the child entities to add a prefix to the name when writing to the table, and removing it again when reading from the table. Or I add another field to the base table indicating the child class linked to it, and make "name"+"link" unique, instead of just "Name". Both solutions aren't very pretty and it's unclear to me how to implement one of those. So is there a better solution or else, how do I implement this nicely? A: It cannot be solved by unique column. The unique key would need to be placed over two columns - one specifying the Name and one specifying the type of derived entity but that is not possible with the inheritance type you selected (Table-per-type) because EF will not create and maintain that additional column for you. That would be possible only with Table-per-hierarchy inheritance where all five child entities are stored in the same table as base class and there is discriminator column to differ among them. To solve this with your current design you must either use trigger on base table with some query logic to find if name is unique per child or handle this completely in your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sidebars with 100% height I have uploaded example here: http://vizakenjack.narod2.ru/testpage2.html My problem is sidebars with 100% height. If the content is only 1 line of text, sidebars should fill all the screen. Otherwise, if the content is more that screen, sidebars should scroll down to the end of page. I have tried to set position:relative to body. Sidebars are ok when content is a big article, but when article is small, they aren't fit to 100% height. A: Classic case for http://www.alistapart.com/articles/holygrail/. Read it, bookmark it, keep it nearby at all times.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wrong strlen output I have the following piece of code in C: char a[55] = "hello"; size_t length = strlen(a); char b[length]; strncpy(b,a,length); size_t length2 = strlen(b); printf("%d\n", length); // output = 5 printf("%d\n", length2); // output = 8 Why is this the case? A: it has to be 'b [length +1]' strlen does not include the null character in the end of c strings. A: You never initialized b to anything. Therefore it's contents are undefined. The call to strlen(b) could read beyond the size of b and cause undefined behavior (such as a crash). A: b is not initialized: it contains whatever is in your RAM when the program is run. A: For the first string a, the length is 5 as it should be "hello" has 5 characters. For the second string, b you declare it as a string of 5 characters, but you don't initialise it, so it counts the characters until it finds a byte containing the 0 terminator. UPDATE: the following line was added after I wrote the original answer. strncpy(b,a,length); after this addition, the problem is that you declared b of size length, while it should be length + 1 to provision space for the string terminator. A: Others have already pointed out that you need to allocate strlen(a)+1 characters for b to be able to hold the whole string. They've given you a set of parameters to use for strncpy that will (attempt to) cover up the fact that it's not really suitable for the job at hand (or almost any other, truth be told). What you really want is to just use strcpy instead. Also note, however, that as you've allocated it, b is also a local (auto storage class) variable. It's rarely useful to copy a string into a local variable. Most of the time, if you're copying a string, you need to copy it to dynamically allocated storage -- otherwise, you might as well use the original and skip doing a copy at all. Copying a string into dynamically allocated storage is sufficiently common that many libraries already include a function (typically named strdup) for the purpose. If you're library doesn't have that, it's fairly easy to write one of your own: char *dupstr(char const *input) { char *ret = malloc(strlen(input)+1); if (ret) strcpy(ret, input); return ret; } [Edit: I've named this dupstr because strdup (along with anything else starting with str is reserved for the implementation.] A: Actually char array is not terminated by '\0' so strlen has no way to know where it sh'd stop calculating lenght of string as as its syntax is int strlen(char *s)-> it returns no. of chars in string till '\0'(NULL char) so to avoid this this we have to append NULL char (b[length]='\0') otherwise strlen count char in string passed till NULL counter is encountered
{ "language": "en", "url": "https://stackoverflow.com/questions/7628222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When a user updates an iOS app, does application:didFinishLaunchingWithOptions: get called? I've looked at the docs but am still unsure. Will application:didFinishLaunchingWithOptions: get called again after the user updates their app from the App Store and then launches the app again? As I understand it, this method only gets called on first launch and then again if the user kills the app. But what about after an update from the App Store? A: According to me it is definitely called again. What if your update brings a new implementation right in the mentioned method? So it have to be called.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Kohana 3.2 does not load the config files I am developing a web app using Kohana 3.2 with the following modules loaded: * *useradmin *auth *database *orm *pagination *oauth *kohana-email On my development machine (Mac OS X Lion with Apache) everything its fine. On my web server running ubuntu 10.04 with nginx 1.1.0 the config files are not loaded. This comes to effect when i try to login. Kohana gives me the following error: A valid hash key must be set in your auth config. If I have a look at Kohana::$config, it is empty. Which gives me the conclusion that the my configurations are not loaded. Does anyone have an idea what can cause such a behavior. My directory looks like this application/ ├── bootstrap.php ├── cache ├── classes │   ├── controller │   │   ├── … │   └── model ├── config │   ├── auth.php │   ├── database.php │   └── pagination.php ├── i18n │   └── … ├── logs │   └── … ├── messages └── views └── template └── default.php EDIT: For I suppose the error must be in my server environment, here is my nginx configuration. server { listen 80; root /srv/www/; index index.php; location / { try_files $uri /index.php?$query_string; } location /index.php { fastcgi_param KOHANA_ENV development; fastcgi_pass unix:/var/run/php-fastcgi/php-fastcgi.socket; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root/index.php; include /etc/nginx/fastcgi_params; } } A: The syntax has been changed a little in 3.2 Kohana::$config will stay empty until you actually load the config file into it, with: Kohana::$config->load('auth') This has been addressed in the user guide in the migration from 3.1.x section.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need assistance with NSIndexPath in the method below why indexPath.Row always return 0??? - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. [cell.textLabel setText:[mainItems objectAtIndex:indexPath.row]]; return cell; } mainItems is a NSMutableArray and has 5 items ("item 1", "item 2",...) the View does get 5 items... but they are all "Item 1" and NOT item 1, item 2... what am i doing wrong? A: My guess is that you're returning the wrong value in your implementation of -numberOfSectionsInTableView, and the table view is asking you for the 0th row of 5 sections. Table views have sections, and each section has rows. Many table views only have one section, but many rows in that section. It sounds like you have one section, with 5 rows. Be sure that you return the correct values in each of: - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{ "language": "en", "url": "https://stackoverflow.com/questions/7628229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can specializations of a template function be virtual? Something like, for example, class A { template<typename T> T DoStuff(); template<> virtual int DoStuff<int>() = 0; }; Visual Studio 2010 says no, but I get a funny feeling that I simply messed up the syntax. Can explicit full specializations of a member function template be virtual? A: Explicit specializations aren't legal within a class. Even if you could make it a partial specialization you would still run into the "templates can't be virtual" problem. n3290, § 14.5.2 states: A member function template shall not be virtual. And gives this example: template <class T> struct AA { template <class C> virtual void g(C); // error virtual void f(); // OK }; Before going on to state that member function templates do not count for virtual overrides too. A: According to C++98 Standard member function template shall not be virtual. http://www.kuzbass.ru:8086/docs/isocpp/template.html. -3- A member function template shall not be virtual. [Example: template <class T> struct AA { template <class C> virtual void g(C); // error virtual void f(); // OK }; A: You can get a similar effect by overloading your function template with a regular non-template virtual function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to catch top level failures on an EventMachine server? I have an EventMachine server that I am monitoring with monit. Sometimes it crashes, and I am trying to figure out why, but it is unclear to me how I can just log all top level failures. I tried code like this: begin EventMachine::run do EventMachine::start_server('0.0.0.0', PORT, MyServer) end rescue Exception => e puts "FAILURE: #{e.class}: #{e}" end but that does not seem to ever catch errors. I suspect it might be something like running out of memory, which I am tracking separately, but still I would like this server to log its proximate cause of failure if possible. A: If you want a catch-all error handler, try EM.error_handler. Example from the docs: EM.error_handler{ |e| puts "Error raised during event loop: #{e.message}" } You may also want more fine-grained error handling, in which case you can use the errback mechanism (see Deferrable). So for example you could have in your reactor loop: EventMachine::run do server = EventMachine::start_server('0.0.0.0', PORT, MyServer) server.errback { # handle error thrown by server here } end For this to work, include Deferrable in your MyServer, then whenever you want to raise an error, call fail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to protect files on your website I will have clients upload pdf files with sensitive information. I'm planning on having the directory outside public_html. When a client want to download his/her file they will get a php link that will authenticate them. Is more I can do to protect such files? A: * *Place the files outside docroot, *make the temporary links (www.oink.com/abd73df10e92/whatever.pdf) expire, *never direct link the files, use a php wrapper to readfile out the contents *never use the stored filename, *make sure the files have the least permissions *if the files are really sensitive, provide them over only HTTPS A: Yeah - you can implement "one-time-download" links: from a valid user session, you generate a link which, when accessed, does a server-side redirect to the file in question. In your link handler you verify, via session cookies (or whatever mechanism) that the person visiting the link is authorized to access the file in question. A: I don't see anything wrong with that approach. You could require a login password and make the only available download links the ones associated with the user's account. This would also be done with SSL of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css positioning with display or float , can I get this structure using display property Given this HTML: <div id="div1"> <div id="div1a"></div> <div id="div1b"></div> <div id="div1c"></div> <div id="div1d"></div> </div> <div id="div2a"></div> Can I get this structure using CSS display property? A: Sure, it can be done with the following CSS: /* Height of the top box. Change as needed to suit your layout */ #div1a { height: 50px; } /* 3 left side boxes. Again, alter the height/width as needed. If you change the width, you'll need to update the margin-left on #div2a as well. */ #div1b, #div1c, #div1d { width: 100px; height: 60px; /* This bit causes them to float to the left in a vertical row of boxes */ float: left; clear: both; } /* Increased height of the last box on the left */ #div1d { height: 200px; } /* Main content box on the right. min-height can be changed as needed. The margin makes room for the 3 boxes floating down the left side. You read its properties as margin: top right bottom left; */ #div2a { min-height: 365px; margin: 0 20px 0 140px; } /* Generic margin/padding for all <div>'s */ div { margin: 5px; padding: 5px; } /* Remove the generic margin for #div1 */ #div1 { margin: 0; } Demo of it in action. A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type='text/css'> .mask{ position: relative; overflow: hidden; margin: 0px auto; width: 100%; background-color: #f4f4f4 } .header{ float: left; width: 100%; background-color: #f4f4f4 } .colleft{ position: relative; width: 100%; right: 84%; background-color: #f4f4f4 } .col1{ position: relative; overflow: hidden; float: left; width: 82%; left: 101%; background-color: #e6e6e6 } .col2{ position: relative; overflow: hidden; float: left; width: 14%; left: 3%; background-color: #e6e6e6 } .footer{ float: left; width: 100%; background-color: #b4caf7 } body { padding: 0px; margin: 0px; font-size: 90%; background-color: #e7e7de } </style> </head> <body> <div class="mask"> <div class="header"> DIV1A </div> <div class="colleft"> <div class="col1"> DIV2A </div> <div class="col2"> <div id="div1b">DIV1B</div> <div id="div1c">DIV1C</div> <div id="div1d">DIV1D</div> </div> </div> <div class="footer"> footer </div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7628236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: git pull with new latest tag info on the file been trying to find out if there is a way to pre-write the tag version inside a file, so each time when i pull the code from repo, it should write the latest tag version number automatically. so i would know, which guy is using that file from which version.. is there a way to put tag information on a file, so when i retrive the file it pre-write the current tag id on it? i have search many places, but cant find proper answer.. some way using git describe and some say use hook.. A: Did you mean something like this? git describe --tags > version.txt A: You can check man gitattributes, particularly the filter section. A: I guess you are misunderstanding some concept on tag. You can say, a tag is an alias of a particular SHAsum of a commit. You can also checkout the file to a particular point through its SHAsum git checkout <Shamsum of a point> -- <path to file> or by tagname git checkout <tagname> -- <path to file> you can always keep track which one did the correction, or made commit on that particular file. git blame -- <path to file> (the latest version) or git log -- <path to file> to see all the commits on that particular file Hope this help
{ "language": "en", "url": "https://stackoverflow.com/questions/7628242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Intrincate sites using htmlunit I'm trying to dump the whole contents of a certain site using HTMLUnit, but when I try to do this in a certain (rather intrincate) site, I get an empty file (not an empty file per se, but it has an empty head tag, an empty body tag and that's it). The site is https://www.abcdin.cl/abcdin/abcdin.nsf#https://www.abcdin.cl/abcdin/abcdin.nsf/linea?openpage&cat=Audio&cattxt=TV%20y%20Audio&catpos=03&linea=LCD&lineatxt=LCD%20& And here's my code: BufferedWriter writer = new BufferedWriter(new FileWriter(fullOutputPath)); HtmlPage page; final WebClient webClient = new WebClient(BrowserVersion.INTERNET_EXPLORER_8); webClient.setCssEnabled(false); webClient.setPopupBlockerEnabled(true); webClient.setRedirectEnabled(true); webClient.setThrowExceptionOnScriptError(false); webClient.setThrowExceptionOnFailingStatusCode(false); webClient.setUseInsecureSSL(true); webClient.setJavaScriptEnabled(true); page = webClient.getPage(url); dumpString += page.asXml(); writer.write(dumpString); writer.close(); webClient.closeAllWindows(); Some people say that I need to introduce a pause in my code, since the page takes a while to load in Google Chrome, but I set long pauses and it doesn't work. Thanks in advanced. A: Just some ideas... Retrieving that URL with wget returns a non-trivial HTML file. Likewise running your code with webClient.setJavaScriptEnabled(false). So it's definitely something to do with the Javascript in the page. With Javascript enabled, I see from the logs that a bunch of Javascript jobs are being queued up, and I get see corresponding errors like this: EcmaError: lineNumber=[49] column=[0] lineSource=[<no source>] name=[TypeError] sourceName=[https://www.abcdin.cl/js/jquery/jquery-1.4.2.min.js] message=[TypeError: Cannot read property "nodeType" from undefined (https://www.abcdin.cl/js/jquery/jquery-1.4.2.min.js#49)] com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot read property "nodeType" from undefined (https://www.abcdin.cl/js/jquery/jquery-1.4.2.min.js#49) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:601) Maybe those jobs are meant to populate your HTML? So when they fail, the resulting HTML is empty? The error looks strange, as HtmlUnit usually has no issues with JQuery. I suspect the issue is with the code calling that particular line of the JQuery library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switching between multiple Cameras using Emgu CV I have a quick question: I need to switch between the two camera on a tablet. Front and Back. By default, the Front camera is always used by Emgu CV. Thanks. A: Ok. There is a different constructor. I was building upon the 7 line demo for Emgu CV. Using the correct overloaded constructor, this is what did the trick for me: private Capture _capture; private void InitCapture(Int32 _camIndex) { try { if (_capture != null) { Application.Idle -= ProcessFrame; } _capture = new Capture(_camIndex); Application.Idle += ProcessFrame; } catch (NullReferenceException excpt) { XtraMessageBox.Show(excpt.Message); } } private void ProcessFrame(object sender, EventArgs arg) { Image<Bgr, Byte> frame = _capture.QueryFrame(); ImageBoxCapture.Image = frame; } private void CharmsBarBase_ButtonTop01Click(object sender, EventArgs e) { InitCapture(0); } private void CharmsBarBase_ButtonTop02Click(object sender, EventArgs e) { InitCapture(1); } Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: method="post" enctype="text/plain" are not compatible? When I use <form method="post" enctype="text/plain" action="proc.php"> form data can not be sent to proc.php file properly. Why? What is the problem? Why I can't use text/plain encoding with post but I can use it with get method? A: [Revised] The answer is, because PHP doesn't handle it (and it is not a bug): https://bugs.php.net/bug.php?id=33741 Valid values for enctype in <form> tag are: application/x-www-form-urlencoded multipart/form-data The first is the default, the second one you need only when you upload files. @Alohci provided explanation why PHP doesn't populate $_POST array, but store the value inside a variable $HTTP_RAW_POST_DATA. Example of what can go wrong with text/plain enctype: file1.php: <form method="post" enctype="text/plain" action="file2.php"> <textarea name="input1">abc input2=def</textarea> <input name="input2" value="ghi" /> <input type="submit"> </form> file2.php: <?php print($HTTP_RAW_POST_DATA); ?> Result: input1=abc input2=def input2=ghi No way to distinguish what is the value of input1 and input2 variables. It can be * *input1=abc\r\ninput2=def, input2=ghi, as well as *input1=abc, input2=def\r\ninput2=ghi No such problem when using the other two encodings mentioned before. The difference between GET and POST: * *in GET, the variables are part of URL and are present in URL as query string, therefore they must be URL-encoded (and they are, even if you write enctype="text/plain" - it just gets ignored by the browser; you can test it using Wireshark to sniff the request packets), *when sending POST, the variables are not part of URL, but are sent as the last header in HTTP request (POSTDATA), and you can choose whether you want to send them as text/plain or application/x-www-form-urlencoded, but the second one is the only non-ambiguous solution. A: HTML5 does define how to format form data submitted as text/plain here: https://w3c.github.io/html/sec-forms.html#plain-text-form-data. At the bottom of that section, it says: Payloads using the text/plain format are intended to be human readable. They are not reliably interpretable by computer, as the format is ambiguous (for example, there is no way to distinguish a literal newline in a value from the newline at the end of the value). So it not unreasonable that PHP does not attempt to interpret it and only makes it available in raw form. To me, that seems the correct approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Confused about "this" operator in Java Though I'm trying to understand why "this" is needed, I'm very confused about its purpose. For instance, I coded the following: public static void main (String args[]) { SandboxClass1 temp = new SandboxClass1(1,2,3); System.out.println(temp.getX()); System.out.println(temp.getY()); System.out.println(temp.getZ()); System.out.println("----------------------------"); SandboxClass1 temp2 = new SandboxClass1(4,5,6); System.out.println(temp2.getX()); System.out.println(temp2.getY()); System.out.println(temp2.getZ()); } public class SandboxClass1 { private int x = 1; private int y = 1; private int z = 0; public SandboxClass1(int x, int y, int zz) { this.x = x; this.y = y; z = zz; } public int getX() { return(this.x); } public int getY() { return(this.y); } public int getZ() { return(this.z); } } Why do I need to code "this.z = zz" when I could just as well write, "z = zz"? A: You don't, in this case. It's only required when you must eliminate ambiguity, like when parameters and instance variables share a name. Some people prefer to use "this" to remove conceptual ambiguity and explicitly state that the code references an instance variable. (On a side note, the parentheses around the return values are unnecessary and a bit noisy, IMO.) A: It has the same effect. this is needed if there is a local variable which overrides a field of the class; then you get the local variable and not the class field. An additional advantage you can indicate the variables better. If there is a this; it's a field; local variable otherwise. A: In your SandboxClass1 constructor, you have two pairs of variables each called x and y. There's the x and y declared on the object itself ("private int x = 1"), and the separate x and y that are parameters to the constructor ("int x"). The local (parameter) variable shadows the class variable. So if in the constructor you just did x = x; the assignment would have no effect. The keyword this is a reference to the object that the method/constructor was called on. In the statement this.x = x; you're using it to assign to the other x at class level. By qualifying the name, you can tell them apart. It's not necessary to use this with the z/zz assignment because they have different names. It's also not necessary in the getX/Y/Z methods because there are no local variables in those methods shadowing the relevant class variables. It does no harm though. A: In the SandboxClass1 constructor two of the parameters (x and y) hide class variables because they are the same name. If you want to assign the class variable x to any value while in the code>SandboxClass1 constructor, you must address it using this.x to tell the compiler that "I want to assign the class scope variable named x, and not the method scope variable named x". The same applies to y. Since the parameter z does not hide the class scope variable named zz you do not need to tell the compiler the scope of the zz variable, the class scope zz is the only recognized variable so that is the one that gets assigned. A: the keyword this is used to refer to an attribute that is in the class. The keyword this was created to distinguish between class attributes and method parameters. like this: public class human { public void setName(String name) { // the first name is a reference to the class attribute name this.name = name; // the second name is a reference to the method parameter name } // definition of the class attribute name private String name; } when you use the keyword this it refers to the name variable inside the class heres an example where you don't need to use this: public class Human { public void setName(String myName) { name = myName } private String name; } see now there is only 1 variable named name and there is only one variable named myName. In the other example there was 2 variables named name. One was a class attribute and one was a method parameter. A: 'this' operator just refines that property/field belongs to class you're working in. It's useful whe you have, for example, two variables with the same name: this.zz = zz; A: Unlike, say, Objective-C, "this" is optional when the method or variable is local, and there is no other conflicting use of the same name. It comes in handy in conflicting-name cases, though, such as in methods that set instance variables such as void setOnionCount(int onionCount) where you would like to use "onionCount" for the formal parameter but still have "onionCount" as the instance variable name. In such a case you can do this.onionCount = onionCount; and everyone is happy (except, I suppose, those in the Peanut Gallery who'll object to this technique). "this" is also absolutely necessary in cases where you need to pass a reference to the current object to some other class, of course. A: hey this is use to provide reference of invoking object. That i.e say suppose ur class is box then if you want to provide it's object then you can provide it within the class box using this keyword. class Box { int x; public Box(int x){ this.x = x; } } here in this case if your object is ob (i.e Box ob = new Box(1)) then the reference it will be passed to the itself. Note: you cannot use this keyword outside of the class. If you use so then it will give reference of another class. for complete detail on this keyword refer following link http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7628253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xsl for ordering subnodes of xml Here is sample xml <Data version="2.0"> <Group> <Item>3</Item> <Item>1</Item> <Item>2</Item> </Group> <Group> <Item>7</Item> <Item>5</Item> </Group> </Data> And for ordering nodes in Group by Item value I tried to use the following xsl: <xsl:template match="/Data"> <xsl:apply-templates select="Group"> <xsl:sort select="Item" /> </xsl:apply-templates> </xsl:template> But get only values, even without sorting: 3 1 2 7 5 So the questions are: 1. why sorting not work 2. How to keep all nodes and keep structure of xml? A: This is what you want: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="Group"> <xsl:copy> <xsl:apply-templates select="@*"/> <xsl:apply-templates select="Item"> <xsl:sort select="text()" /> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet> The first template is the "Identity Template" (Google it) which copies input to output unchanged. Then for the Group node we copy it to the output (<xsl:copy>), copy its attributes, then copy the nested Item nodes after sorting them. They get copied because the inner <xsl:apply-templates select="Item"> ends up using the Identity template since there's no more-specific template for Item nodes. Note that if Group nodes can contain other stuff besides Item nodes, you'll have to make sure it gets copied as well. The template above would discard them. A: @Jim's answer is basically correct. However, applied to a slightly more realistic XML document, such as this: <Data version="2.0"> <Group> <Item>3</Item> <Item>1</Item> <Item>10</Item> <Item>2</Item> </Group> <Group> <Item>7</Item> <Item>5</Item> </Group> </Data> the result produced is clearly not what you want (10 comes before 2 and 3): <?xml version="1.0" encoding="utf-8"?> <Data version="2.0"> <Group> <Item>1</Item> <Item>10</Item> <Item>2</Item> <Item>3</Item> </Group> <Group> <Item>5</Item> <Item>7</Item> </Group> </Data> Here is a correct solution (that is also slightly shorter): <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="Group"> <Group> <xsl:apply-templates select="*"> <xsl:sort data-type="number"/> </xsl:apply-templates> </Group> </xsl:template> </xsl:stylesheet> when this transformation is applied on the same XML document (above), the wanted, correct result is produced: <Data version="2.0"> <Group> <Item>1</Item> <Item>2</Item> <Item>3</Item> <Item>10</Item> </Group> <Group> <Item>5</Item> <Item>7</Item> </Group> </Data> Explanation: Use of the data-type attribute of <xsl:sort> to specify that the sort keys value should be treated as number, not as (the default) string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: New to IIS, looking for a way to handle logs and sessions upon a deploy Deploying a ASP.Net application via Teamcity and a Nant scripts. Currently I am zipping up the directory from the local git repository (after building) and copying up to the test machine, Renaming the current web home directory and dropping in the new one. (with some scripts to get the web.config in place) The question I have is how to handle the log and sessions directories. I want them in the current deployed directory but don't want to have to copy them from the old to new one. I was debated about having them stored in a different directory then the web home directory and just placing a shortcut pointing at that directory (would be in git so it would get deployed with everything else). In linux I have a link (ln) doing this very thing for me. Is their a cleaner solution? Am I going about this the wrong way? A: Instead of renaming the current web directory, copy it and then use NAnt's <delete /> task to delete the web directory excluding the log and session directories. Then simply unzip the new web application. For example: <delete> <fileset basedir="${PublishLocation}"> <include name="**/*"/> <exclude name="**/Logs/**/*" /> <exclude name="**/Sessions/**/*" /> </fileset> </delete>
{ "language": "en", "url": "https://stackoverflow.com/questions/7628260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alias Methods and Performance Concerns In order to improve code readability, sometimes I use "alias methods". These are basically methods that all do the same thing (at least in the base class; derived classes may do it differently) with different names, that enhance code readability for the class user depending on the context. Consider the code below for an example: template <typename T> class Foo { public: T bar() { /* Lots of stuff here */ } inline T bar_alias1() { return this->bar(); } inline T bar_alias2() { return this->bar(); } }; Of course, if Foo::bar() was a small function, one would simply duplicate the code in all the alias methods. However, since the code may be relatively large, code duplication should be avoided, hence why the alias methods are declared as inline. But I know that the compiler does not guarantee that any function declared as inline would actually end up being expanded at compile time. So my question is, am I introducing any performance overhead by creating these alias methods? In the code below: Foo<BIG_OBJECT> foo; BIG_OBJECT bo1 = foo.bar(); BIG_OBJECT bo2 = foo.bar_alias1(); Would calling foo.bar() be faster than calling foo.bar_alias1() assuming the object being passed is relatively large? Are there redundant copies of the object being made when Foo::bar_alias1() calls Foo::bar()? I'm using Visual Studio 2010 as my compiler. A: Assuming the aliased functions are inlined - and they should given the size. There shouldn't be any performance overhead. The code-size won't increase either if the compiler decides to omit the function code and inline all calls to it. (I'm referring to the inlining of bar_alias1(), bar() itself won't necessarily be inlined if it's large.) However, this doesn't apply if the functions are virtual. In C, I would do this more directly with preprocessor, but I'm not sure how appropriate that is in C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Building and creating related objects via the association: how to set the foreign key of a nested model? I am using Ruby on Rails 3.1.0. I am trying to save a nested model having an attribute that is intended to store the foreign key of the parent model. At the creation time of the parent model I would like to set that attribute value to the parent model id value. In my model I have: class Article < ActiveRecord::Base has_many :article_category_relationships has_many :categories, :through => :article_category_relationships # Accept nested model attributes accepts_nested_attributes_for :articles_category_relationships end class Category < ActiveRecord::Base has_many :article_category_relationships has_many :articles, :through => :article_category_relationships end # The join model: class ArticleCategoryRelationship < ActiveRecord::Base # Table columns are: # - article_id # - category_id # - user_id # - ... belongs_to :category belongs_to :article end In my view I have the following: ... <% @current_user.article_categories.each do |article_category| %> <%= check_box_tag 'article[articles_category_relationships_attributes][][category_id]', article_category.id, false %> <% end %> In my controller I have: def create @article = Article.new(params[:article]) ... end In my case, the article_id (related to the ArticleCategoryRelationship nested model) should be set to the @article.id value after the Article creation and the problem is that the Ruby on Rails framework seems do not set that value at the creation time. In few words, considering my case, I would like to attach the foreign key automatically. Just to know, the generated params when the form is submitted is: "article"=>{"title"=>"Sample title", "articles_category_relationships_attributes"=>[{"category_id"=>"8"}, {"category_id"=>"9"}, {"category_id"=>"10"}] } Is it possible to "auto"-set the foreign key (article_id) of the nested model? If so, how can I do that? A: try using : @a_particular_article.article_category_relationships.build(params[:something]) you can see here for more info, and might want to have a look at nested attributes and at validates_associated A: In my opinion, you just CAN'T do that. * *If you want to save articles_category_relationships, you need a article_id for each of them. *And, when you save article, rails will first validate article and all sub-objects. This means article.valid? must be true before you can save any record. *Since article does not have an id before save to db, article_id in any of articles_category_relationships is empty. Therefore, article.valid? will always be false as long as you need to CREATE new article and its sub-objects at the same time *To summarize, here is the steps of rails: * *validate article itself, success!(NOTE: note saved) *validate articles_category_relationship for each of article.articles_category_relationships, article_id not provided, fail! What you can do * *create article first *assign params to this created article *update with params
{ "language": "en", "url": "https://stackoverflow.com/questions/7628262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make Heritrix to continue crawl process on domains found and are not in seed list How to make Heritrix to continue crawl process on domains found and are not in seed list? I mean make it to not to stop after crawled over all Domains in seeds list. and continue the crawling process for each link it found in the crawling process. A: It's been a while since I last worked with Heritrix, but if memory serves me well, you'll need to change the max-link-hops in your settings/profile. The larger you make max-link-hops, the more steps ("hops") Heritrix makes from the seed(s) you have defined. A: By default Heritrix is configured to only crawl URLs on the domains that are in your seed list. Some additional material is also usually crawled as embedded material, hosted elsewhere, is also fetched. If you would like Heritrix to crawl anything it comes across, you'll need to modify the scope. The scope is composed of a series of decide rules. Each rule can ACCEPT, REJECT or pass on a URL. The last rule to either ACCEPT or REJECT wins. Typically, the first rule in the list is a blanket reject all, then followed by a SurtPrefixDecideRule that rules in all URLs that match the SURT list. The SURT list is typically built using the seed list. You can however configure the SURT list manually be specifying your own, or (if you really want everything), you can simply remove it and the reject all rule and add an accept all decide rule to the top. More on configuring Heritrix 3 scoping. A: You can also set the surt decide rule 'NotonDomains' to true. This will crawl all domains which is not on the seedlist.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android) can i set a default activity that runs right after installing in my app, there is two activity and i want to make activity1 to the starting activity after installation. But now the RUN button (is showed right after packgae installing) is disabled. below is the manifest file. thanks. <activity ...1> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity ...2> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> </intent-filter> </activity> A: android) can i set a default activity that runs right after installing No activity "runs right after installing". The user has to launch it from the launcher. below is the manifest file No, it is not. That is not even valid XML. Also, note that your third <intent-filter> is invalid. Not only are you missing any category (you need at least DEFAULT for activities), but ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED are not activity actions. I am going to take a guess that you really mean to ask: "I have two activities, both described as ACTION_MAIN/CATEGORY_LAUNCHER, and now the Run button does not work -- what can I do?" The answer would be "either remove the ACTION_MAIN/CATEGORY_LAUNCHER <intent-filter> from one of them, or mark one of the two as disabled (android:enabled="false") and enable it later on using PackageManager." A: I think the problem is the second: <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> You shouldn't have 2 activities flagged as the MAIN and LAUNCHER activity. Try removing it within activity2. Check out: http://developer.android.com/reference/android/content/Intent.html the intentfilter s are discussed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automatically silence the sound volume of Android Phone programmatically? I'm developing an application that can turn off the sound of Android Phone automatically. How can I detect the volume of the sound and turn it off programmatically? if (hour == myTime.getHour() && minute == myTime.getMinute()) { if (Settings.getSetMyTime(this)) showNotificationAlarm(R.drawable.icon, "It's time to work"); ///so, i want to add the silet function here..help me, please? } Thanks in advance. A: Have a look at the AudioManager, especially the getStreamVolume and setStreamVolume methods EDIT You can also use the method Nikola Despotoski provided with setRingerMode A Service is a child of a Context so you can call directly getSystemService See the updated code below (untested): if (hour == myTime.getHour() && minute == myTime.getMinute()) { if (Settings.getSetMyTime(this)) showNotificationAlarm(R.drawable.icon,"It's time to work"); AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE); am.setRingerMode(AudioManager.RINGER_MODE_SILENT); } A: Register for AUDIO_SERVICE and then use the AudioManager to control the volume up/down or set profiles. Or if you want to listen for changes in the Audio focus then make your Activity implements AudioManager.OnAudioFocusChangeListener. Override unimplemented method. Create switch that will take care of types of changes. Like: @Override public void onAudioFocusChange(int focusChange) { switch(focusChange) { case AudioManager.AUDIOFOCUS_GAIN: //do something break; case AudioManager.AUDIOFOCUS_LOSS: break; } Or if you want to listen for changes on the audio output, like unplugging the headphones (switching to phone speaker) use ACTION_AUDIO_BECOMING_NOISY sticky broadcast http://developer.android.com/reference/android/media/AudioManager.html#ACTION_AUDIO_BECOMING_NOISY http://developer.android.com/reference/android/media/AudioManager.html#RINGER_MODE_SILENT See here Edit: This is the solution. There was no need to handle AudioFocus but just set different ringer profile or adjusting volume if (hour == myTime.getHour() && minute == myTime.getMinute()) { if (Settings.getSetMyTime(this)) showNotificationAlarm(R.drawable.icon, "It's time to work"); AudioManager audiomanager =(AudioManager)YourActivityName.this.getSystemService(Context.AUDIO_SERVICE); audiomanager.setRingerMode(AudioManager.RINGER_MODE_SILENT); //or adjust volume here instead setting silent profile for the ringer }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery place p content into attribute this is my first time here... I have the following scenario: <div class="album-wrap"> <img src="picture.jpg" alt="Mickey"> <p class="caption">little mouse</p> </div> <div class="album-wrap"> <img src="picture2.jpg" alt="Donald"> <p class="caption">little duck</p> </div> Question is: how could I place the contents of class caption into alt attributes? Or maybe create another attribute and place the contents of caption class. Thanks. A: Loop through each container, and get the contents of the p element using .text(). Then, assign this value to the alt attribute using .attr(). $(".album-wrap").each(function(){ var caption = $("p.caption", this).text(); $("img", this).attr("alt", caption); }) A: Replace the alt contents with the text of the caption. $('.caption').each( function() { var $this = $(this), $img = $(this).prev('img'); $img.attr('alt', $this.text() ); }); Append the text of the caption to the alt contents. $('.caption').each( function() { var $this = $(this), $img = $(this).prev('img'), alt = $img.attr('alt'); $img.attr('alt', alt + ': ' + $this.text() ); }); A: I would loop through the img elements and set the alt attributes to the inner text of their respective, sibling p.caption elements. $('.album-wrap img').each(function() { var $img = $(this); $img.attr('alt', $img.siblings('.caption').text()); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7628282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using TextField to search from a txt file xcode I am trying to make a simple iphone program that will allow me to search a keyword when entered into a textfield and then search for it by clicking a rect button. I have searched the site and there is nothing that relates to my current situation. to reiterate, I have a textfield where I would like to enter some text and search for it by clicking a rect button. I have the information i want to search for in a txt file. What is the appropriate way to to go about doing this in xcode for iphone. I appreciate the help, thanks. A: If I understand your question correctly, You are trying to find a user defined phrase in a text file. What you should do is read the file to an NSString, and then search the string for the user defined string. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/SearchingStrings.html Googled it quickly and found an example (Not written by me!): NSString *searchFor = @"home"; NSRange range; for (NSString *string in stringList) { range = [word rangeOfString:searchFor]; if (range.location != NSNotFound) { NSLog (@"Yay! '%@' found in '%@'.", searchFor, string); } } If I missunderstood you, please update your question so it is better understandable. A: Try this: -(void)searchWord:(NSString *)wordToBeSearched{ NSString* path = [[NSBundle mainBundle] pathForResource:@"wordFile" ofType:@"txt"]; NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; NSString *delimiter = @"\n"; NSArray *items = [content componentsSeparatedByString:delimiter]; NSString *character = @" "; BOOL isContain = NO; for (NSString *wordToBeSearched in items) { isContain = ([string rangeOfString:wordToBeSearched].location != NSNotFound); } return isContain; } You can go here for more details
{ "language": "en", "url": "https://stackoverflow.com/questions/7628284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gem not found after migration 2 -> 3 I migrated a rails 2 project to rails 3. I use several gems, and i migrated it to Gem file, installing them with bundle. But i get the following error: NameError (undefined local variable or method `acts_as_rateable' for #<Class:0x10322fc00>): But the gem is correctly installed. Any hint? I am struggling with this...
{ "language": "en", "url": "https://stackoverflow.com/questions/7628290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ocaml equivalent for Lisp's let*? I'd rather use let ... and ... and ... in than nested let's when possible, but the normal let syntax doesn't allow this for expressions that depend on each other. Not allowed: let encrypt password = let seed = int 16 and keys = xlat seed (length password) and plaintext = map code (explode password) in map2 logxor plaintext keys Does OCaml have an equivalent to Lisp's let*, which does allow this? A: Nested let's don't need nested indentation, so that's good enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Browsers act different on anchor with image on MVC3 Razor world! I have a odd thing with an "a" tag. The big idea is rendering something like this: <a href="/*Retrieve an original sized image from database*/"><img src="/*Retrieve an original sized image and resize to thumbnail*/"/> </a>. This is what I need to implement some jQuery zooming image plugins. I have 2 methods - one simply gets image form DB, another makes a thumbnail. The problem is different browser behavior to my actions: FF, Chrome, Opera shows an original image in another window (as expected). Safari offers to download a jpg file called "GetImageThumbnail" and IE offers to download unknown file called GetImageThumbnail (opens as jpeg image). Here is anchor href text: "/Image/GetFullSizedImage?goodId=20" - same on all browsers. This is helper in View: @Html.GetImageLinkWithInnerImage(Model.Id). Here is a helper implementation(might be useful for folks who want to make anchors and images in helper methods:) public static MvcHtmlString GetImageLinkWithInnerImage(this HtmlHelper helper, int goodid) { var controller = helper.ViewContext.Controller as Controller; if (controller != null) { var urlHelper = controller.Url; var photoUrl = urlHelper.Action("GetFullSizedImage", "Image", new { goodId = goodid }); var anchorBuilder = new TagBuilder("a"); anchorBuilder.MergeAttribute("href", photoUrl + " "); var innerPhotoUrl = urlHelper.Action("GetImageThumbnail", "Image", new { goodId = goodid }); var imgBuilder = new TagBuilder("img"); imgBuilder.MergeAttribute("src", innerPhotoUrl); imgBuilder.MergeAttribute("alt", "Фото товара"); anchorBuilder.InnerHtml = imgBuilder.ToString(TagRenderMode.SelfClosing); return MvcHtmlString.Create(anchorBuilder.ToString()); } return null; } And method retrieves image from DB: public FileContentResult GetFullSizedImage(int goodId) { byte[] imageData = _db.GetGood(goodId).Image; if (imageData != null) { int imageWidth; int imageHeight; var imageFile = GetImageFromBytes(imageData, out imageWidth, out imageHeight); return ImageReadyFileContentResult(imageWidth, imageFile, imageHeight); } return NoPhotoFileContentResult(); } This is an HTML output: <a href="/Image/GetFullSizedImage?goodId=20 "><img alt="Фото товара" src="/Image/GetImageThumbnail?goodId=20" /></a> What am I doing wrong? A: In "ImageReadyFileContentResult()" method, specify the content type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: USB device found on embedded device but unable to mount I have a embedded device running linux 2.6.27 on an arm machine. The kernel and system is working correctly AFIK. I plugged in a USB flash drive and it detects the drive (following output). scsi 0:0:0:0: Direct-Access Kingston DataTraveler II PMAP PQ: 0 ANSI: 0 CCS sd 0:0:0:0: [sda] 2014208 512-byte hardware sectors (1031 MB) sd 0:0:0:0: [sda] Write Protect is off sd 0:0:0:0: [sda] Assuming drive cache: write through sd 0:0:0:0: [sda] 2014208 512-byte hardware sectors (1031 MB) sd 0:0:0:0: [sda] Write Protect is off sd 0:0:0:0: [sda] Assuming drive cache: write through sd 1:0:0:0: [sda] Attached SCSI removable disk I can see that it creates device node is created under sda but I cant find any sda device in /dev/. But I can see it under /sys/sda. I tried mounting using the following command: mount -t vfat /dev/sda/ /mnt/ This fails saying /dev/sda no file found (as it's not there in /dev). Any help will be appreciated. Thanks. A: As far as I know you need udev for dynamic device node creation. If udev is present on the system, check if you have custom rules at /etc/udev/rules.d/.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: background image on a java gui Possible Duplicate: How to set background image in Java? I am trying to put a background image on my java gui, and I can't figure out how to do it. I've looked around and tried some code but I can't get it to work. I have the imageicon setup but I don't understand where I'm suppose to put this at. Please help! A: Read the section from the Swing tutorial on How to Use Icons for an example of displaying an icon. Then, depending on your requirement, Background Panel explains how you can then use the JLabel with the icon as a background image. A: Could this solve your problem? It's an explanation code which shows how you can put a background-image to a panel :) http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7628306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails instance variable based on time? Quick question. If I have a Model, say Charities, that has a start_date and an end_date attribute, how can I set that to be the current_charity from a method in the Controller? I know I'll have to do some kind of Charities.find(params[:something]), and will just have to set that current_charity equal to one that's start_date is >= the current date, and who's end_date is <= the current date (there is only one "current" one at a time). I've usually just found a Model by the params[:id], so this is new to me. Thank you! A: Add a scope method in your model: def self.current now = Time.now where("start_date <= ? AND ? <= end_date", now, now).first end Then in your controller: current_charity = Charity.current A: Quick answer: search for the charity whose end_date is nil. Longer answer: Your data model may not match your desired semantics. It seems to me that start_date is irrelevant here -- isn't the current charity the one whose end_date hasn't happened yet? In general, one way to get the most recent X is to fetch all X's, sorted by descending date, and take the first one (or in SQL terms, use LIMIT 1). In ActiveRecord, it's something like this: Charity.order("end_date DESC").first though I'm a bit rusty on my Rails 3 AR syntax, and I don't think that query will solve your actual problem (though it does look kind of cool, amirite?). Another solution is to denormalize -- add a current boolean field, and a before_save filter that sets self[:current] based on the logic you described. EDIT: Actually, that won't work here, since time marches on, and what is current will change outside the scope of an individual model's data. My best advice is to write a lot of unit tests! Time-based logic is very tricky and it's easy to miss an edge case. A: Remember to add indexes in your database for columns that you will often be using in searches. Add indexes by adding a db migration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I fixed my dilemma with the looping issue. But How can I make it so I dont have to press R? As in, any other key pressed will loop? import java.util.Scanner; public class CurrencyConversion{ public static void main(String[] args){ // declare and initialize variables double dollars = 0; //double euro = 0; // declare scanner Scanner scan = new Scanner(System.in); int loopVal = 0; boolean loop = true; while( loopVal < 1 && loop == true){ //Prompt user for dollar amount System.out.print("Enter the dollar amount $"); dollars = scan.nextDouble(); loopVal ++; loop = false; while( loopVal == 1 && loop == false){ System.out.print("Press Q to quit,or R to resume"); String input = scan.nextLine(); if( input.equalsIgnoreCase("Q")){ break; } // end if one if (input.equalsIgnoreCase("R")) { loop = true; loopVal = 0; }// end else } // end second while } // end first while }// end main method }// end class A: First, your code is case sensitive - "Q" would work but 'q' would not. You should use input.equalsIgnoreCase("Q") to avoid this. Second, you're not doing anything when "input == Q" - perhaps you want to simply use break to escape your while loop in that case? Be careful without {}'s around your if...only the first line after the if is executed if you don't wrap that in {}'s. I think you want something like this: while( loopVal == 1 && loop == false){ System.out.print("Press Q to quit, any other key to resume "); String input = scan.nextLine(); if ( input.equalsIgnoreCase("Q")) { loop = false; } else { // whatever else } } A: Java doesn't understand input != "Q" , remember that String is a class in Java. rather - use public boolean equalsIgnoreCase or similar. See this - http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals%28java.lang.Object%29 Also here, Compare strings example - http://www.roseindia.net/java/beginners/CompString.shtml
{ "language": "en", "url": "https://stackoverflow.com/questions/7628308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: python: creating list from string I have list of strings a = ['word1, 23, 12','word2, 10, 19','word3, 11, 15'] I would like to create a list b = [['word1',23,12],['word2', 10, 19],['word3', 11, 15]] Is this a easy way to do this? A: Try this: b = [ entry.split(',') for entry in a ] b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ] A: input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15'] output = [] for item in input: items = item.split(',') output.append([items[0], int(items[1]), int(items[2])]) A: More concise than others: def parseString(string): try: return int(string) except ValueError: return string b = [[parseString(s) for s in clause.split(', ')] for clause in a] Alternatively if your format is fixed as <string>, <int>, <int>, you can be even more concise: def parseClause(a,b,c): return [a, int(b), int(c)] b = [parseClause(*clause) for clause in a] A: If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this: b = [] for x in a: temp = [] items = x.split(",") for item in items: try: n = int(item) except ValueError: temp.append(item) else: temp.append(n) b.append(temp) This is longer than the other answers, but it's more versatile. A: I know this is old but here's a one liner list comprehension: data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15'] [[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data] or [int(item) if item.isdigit() else item for items in data for item in items.split(', ')]
{ "language": "en", "url": "https://stackoverflow.com/questions/7628311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to read schema of a PostgreSQL database I installed an application that uses a postgreSQL server but I don't know the name of the database and the tables it uses. Is there any command in order to see the name of the database and the tables of this application? A: If you are able to view the database using the psql terminal command: > psql -h hostname -U username dbname ...then, in the psql shell, \d ("describe") will show you a list of all the relations in the database. You can use \d on specific relations as well, e.g. db_name=# \d table_name Table "public.table_name" Column | Type | Modifiers ---------------+---------+----------- id | integer | not null ... etc ... A: Using the psql on Linux you can use the \l command to list databases, \c dbname to connect to that db and the \d command to list tables in the db. A: Short answer: connect to the default database with psql, and list all databases with '\l' Then, connect to you database of interest, and list tables with '\dt' Slightly larger answer: A Postgresql server installation usually has a "data directory" (can have more than one, if there are two server instances running, but that's quite unusual), which defines what postgresl calls "a cluster". Inside it, you can have several databases ; you usually have at least the defaults 'template0' and 'template1', plus your own database(s).
{ "language": "en", "url": "https://stackoverflow.com/questions/7628312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# get set javascript equivalent is there an equivalent in javascript to the following C# code public class Class { public string str { get; set; } } I am trying to do something like this var list = function () { this.settings = { id: 1 }; this.id = //something } var List = new list(); alert(List.id); //alerts 1 List.id = 5; // should set this.settings.id = 5 alert(List.settings.id); // alerts 5 Although this answer is good for the c# class, I still cant reference the id as follows var list = function() { this.settings = { _id: 0, get id() { return this._id; }, set id(x) { this._id = x; } }; this.id = this.settings.id; } var List = new list(); document.write(List.id + "<br />"); List.id += 10; document.write(List.settings.id + "<br />"); which is probably because this.settings.id only passes the value back to this.id and not the actual object A: This wiki article explains Object.defineProperties in detail http://en.wikipedia.org/wiki/Property_(programming)#JavaScript A: Yes, John Resig has a great writeup on it, the basic idea is: function Field(val){ var value = val; this.__defineGetter__("value", function(){ return value; }); this.__defineSetter__("value", function(val){ value = val; }); } Sample: http://jsfiddle.net/mu6jf/ A: var o = { _p: 5, get p() { return this._p; }, set p(x) { this._p = x; } }; Example usage - jsFiddle.net Defining Getters and Setters - developer.mozilla.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7628320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding the same existing field twice(more than once) within same content type I want to reuse the same existing field more than once within the same content type. Assume that ContentType1 has a field Phone-Number. Now I want to use the existing field Phone-Number from ContentType1 within ContentType2, but three times. Assume that I want to have contact numbers of three people in the ContentType2. So I want to use the existing field Phone-Number thrice. It doesn't allow, as once I add the existing field it doesn't appear next time. I tried to export and import. But that didn't work either A: A content type can only have a particular field added to it once - this is by design and cannot be changed without some serious hacking of the module. You can change the field's settings to allow for multiple values, I think this is as close as you're going to get though. A: Yes you cannot add the same existing field multiple time in same content type. You can Use the every existing field only once in every content type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Constructor with by-value parameter & noexcept In this example code: explicit MyClass(std::wstring text) noexcept; Is the use of noexcept here correct? wstring can potentially throw on construction but does the throw happen before we are in the constructor or while we are in the constructor? EDIT: Suppose this can be generalised to any function taking a by-value parameter. A: The construction and destruction of function parameters happens in the context of the caller. So no, if the construction of text throws, that is not a violation of noexcept. Soon folks would comment and ask for a spec quote :) So I will give you 5.2.2p4 The initialization and destruction of each parameter occurs within the context of the calling function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: adding a dynamic button on a MCGrid i want to modify the line in the code below ($g->addColumn('button','check_out') to $g->addColumn('button','check_in') if the field instock is 'N' This way the button calls a different function depending on if the tool is instock. I do have the functions in the model as well already. <?php class page_index extends Page { function init(){ parent::init(); $page=$this; $g=$page->add('MVCGrid'); $tool=$g->setModel('Tools', array('number','name','description','instock')); $g->addColumn('button','check_out'); $g->addPaginator(20); $g->dq->order('number asc'); if($_GET['check_out']){ $tool->loadData($_GET['check_out']); $tool->check_out()->update(); $g->js()->reload()->execute(); } if($_GET['check_in']){ $tool->loadData($_GET['check_in']); $tool->check_in()->update(); $g->js()->reload()->execute(); } } } A: Look into implementation of format_button() inside "atk4/lib/Grid" and create your own function just like that. You'll also need to extend "Grid" to add this function. You will also need to look into init_button() function which slaps jQuery UI button() function on the whole column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compare two columns to find unmatched records in MySQL I have a MySQL table with 2 columns and each column has thousands of records For Example 15000 Email addresses in Column1 and 15005 Email addresses in column 2 How to find those 5 records from 15005 which are unmatched in column1? I wish MySql query to compare both columns and give result of only 5 unmatched records Thanks A: Richard, it's highly unusual to find matching/missing rows from one column in a table compared against another column in the same table. You can think of a table as being a collection of facts, with each row being one fact. Converting values into predicates is how we understand the data. The value "12" in one table may mean "there exists a day on which 12 widgets were made," or "12 people bought widgets on Jan. 1," or "on Jan. 12, no widgets were sold," but whatever the table's corresponding predicate is, "12" should represent a fact. It's common to want to find the difference between two tables: "what facts are in B that aren't in A?" But in a table with two columns, each row should conceptually be a fact about that pair of values. Perhaps the predicate for the row (12, 13) might be "on Jan. 12, we sold 13 widgets." But in that case I doubt you'd be asking for this information. So, if (12,13) is really two of the same predicate -- "someone in district 12 bought widgets, and also, someone in district 13 bought widgets" -- in the long run life will be easier if those are one column, not two. And if it's two different predicates, it would make more sense for them to be in two tables. SQL's flexible and can handle these situations, but you may run into more problems later. If you're interested in more about this subject, searching on "normalization" will find you way more than you want to know :) Anyway, I think the query you're looking for uses a LEFT JOIN to compare the table against itself. I added the values 1-15000 to col1 and 1-15005 to col2 in this table: CREATE TABLE `foo` ( `col1` int(11) DEFAULT NULL, `col2` int(11) DEFAULT NULL, KEY `idx_col1` (`col1`), KEY `idx_col2` (`col2`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; mysql> select count(distinct col1), count(distinct col2) from foo; +----------------------+----------------------+ | count(distinct col1) | count(distinct col2) | +----------------------+----------------------+ | 15000 | 15005 | +----------------------+----------------------+ 1 row in set (0.01 sec) By giving the same table two names, I can compare its two columns against each other, and find the col2 values that have no corresponding col1 values -- in those cases, f1.col1 will be NULL: mysql> select f2.col2 from foo as f2 left join foo as f1 on (f2.col2=f1.col1) where f1.col1 is null; +-------+ | col2 | +-------+ | 15001 | | 15002 | | 15003 | | 15004 | | 15005 | +-------+ 5 rows in set (0.03 sec) Regarding Mosty's solution yesterday, I'm not sure it's correct. I try not to use subqueries, so I'm a little out of my depth here. But it doesn't seem to work for at least my attempt to replicate your data set: mysql> select col2 from foo where col2 not in (select col1 from foo); Empty set (0.02 sec) It works if I exclude the 5 NULLs from the subquery, which suggests to me that "NOT IN (NULL)" doesn't necessarily work the way one might think it works: mysql> select col2 from foo where col2 not in (select col1 from foo where col1 is not null); +-------+ | col2 | +-------+ | 15001 | | 15002 | | 15003 | | 15004 | | 15005 | +-------+ 5 rows in set (0.02 sec) The main reason I avoid subqueries in MySQL is that they have unpredictable performance characteristics, or at least, complex enough that I can't predict them. For more information, see the "O(MxN)" comment in http://dev.mysql.com/doc/refman/5.5/en/subquery-restrictions.html and the advice on the short webpage http://dev.mysql.com/doc/refman/5.5/en/rewriting-subqueries.html . A: Not sure if I got it right... but would it be something like? select column2 from table where column2 not in (select column1 from table)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: make img draggable in td elements foreach($photos as $photo) { $lastChild = ""; if( $count%3 == 0 && $count != 0 ) echo "</tr><tr>"; $count++; ?> <td> <a href="<?php echo ($photo['source'])?>" title="<?php echo ($photo['name'])?>"> <img id="thumb" class="thumb" src="<?php echo ($photo['picture'])?>"> </a></td> This is the script for draggable. Ive done this but it still does not work only the first one does the foreach loop affects? $thumb.draggable({ revert: "invalid", // when not dropped, the item will revert back to its initial position helper: "clone", }); im unable to set ui-draggable to all the img src other than the first img. any one can help? A: Use <img class="thumb" src="<?php echo ($photo['picture'])?>"> instead of <img id="thumb" class="thumb" src="<?php echo ($photo['picture']); ?>" /> in your PHP and $('.thumb').draggable({ instead of $thumb.draggable({ in your jQuery. This should fix it. If you absolutely need IDs on the images for any reason, make them unique like this: <img id="thumb-<?php echo $count; ?>" class="thumb" src="<?php echo ($photo['picture'])?>">
{ "language": "en", "url": "https://stackoverflow.com/questions/7628338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Wrap a div from H2 until last paragraph I want to wrap a <div> FROM THE BEGINNING of the <H2> up until the next <H2>, but it is only starting on the first paragraph. This is what I have, which ALMOST does the job: $('h2:contains("test")').nextUntil('h2').wrapAll('<div class="wrapper" />'); Here's my HTML: /* from here */ <h2 class='test'>Include this in the wrap</h2> <p>this</p> <p>and this</p> <p>and this</p> /* to here */ <h2 class='next'>before this</h2> A: I would try: $("h2.test").nextUntil("h2").andSelf().wrapAll('<div class="wrapper" />'); It does seem to do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# trim string with ip address and port Possible Duplicate: string split in c# Hello guys i am getting connected ip address from socket which is looks like this: >> "188.169.28.103:61635" how i can put ip address into one string and port into another? Thanks. A: Personally I'd use Substring: int colonIndex = text.IndexOf(':'); if (colonIndex == -1) { // Or whatever throw new ArgumentException("Invalid host:port format"); } string host = text.Substring(0, colonIndex); string port = text.Substring(colonIndex + 1); Mark mentioned using string.Split which is a good option too - but then you should probably check the number of parts: string[] parts = s.Split(':'); if (parts.Length != 2) { // Could be just one part, or more than 2... // throw an exception or whatever } string host = parts[0]; string port = parts[1]; Or if you're happy with the port part containing a colon (as my Substring version does) then you can use: // Split into at most two parts string[] parts = s.Split(new char[] {':'}, 2); if (parts.Length != 2) { // This time it means there's no colon at all // throw an exception or whatever } string host = parts[0]; string port = parts[1]; Another alternative would be to use a regular expression to match the two parts as groups. To be honest I'd say that's overkill at the moment, but if things became more complicated it may become a more attractive option. (I tend to use simple string operations until things start getting hairy and more "pattern-like", at which point I break out regular expressions with some trepidation.) A: I would use string.Split(): var parts = ip.Split(':'); string ipAddress = parts[0]; string port = parts[1]; A: Try String.Split: string[] parts = s.Split(':'); This will put the IP address in parts[0] and the port in parts[1]. A: string test = "188.169.28.103:61635"; string [] result = test.Split(new char[]{':'}); string ip = result[0]; string port = result[1];
{ "language": "en", "url": "https://stackoverflow.com/questions/7628342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the handle of a method in an Object (class inst) within MATLAB I'm trying to grab a method handle from within an object in MATLAB, yet something in the sort of str2func('obj.MethodName') is not working A: The answer is to get a function handle as @Pablo has shown. Note that your class should be derived from the handle class for this to work correctly (so that the object is passed by reference). Consider the following example: Hello.m classdef hello < handle properties name = ''; end methods function this = hello() this.name = 'world'; end function say(this) fprintf('Hello %s!\n', this.name); end end end Now we get a handle to the member function, and use it: obj = hello(); %# create object f = @obj.say; %# get handle to function obj.name = 'there'; %# change object state obj.say() f() The output: Hello there! Hello there! However if we define it as a Value Class instead (change first line to classdef hello), the output would be different: Hello there! Hello world! A: One could also write fstr = 'say'; obj.(fstr)(); This has the advantage that it does not require a handle class to work if the object (obj) is modified. A: Use @. The following code works for me: f = @obj.MethodName A: No other answer mimics str2func('obj.MethodName'). Actually, this one doesn't either, not exactly. But you can define an auxillary function like so: function handle = method_handle(obj, mstr) handle = @(varargin) obj.(mstr)(varargin{:}); end Then method_handle(obj, 'MethodName') returns a handle to obj.MethodName. Unfortunately, you cannot pass the variable name of obj as a string - eval("obj") will be undefined in the function's scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: error during reformatvob I'm doing vob migration from Solaris to RHEL, out of 24 vobs 23 vobs migrated successfully except one pvob which is giving following error. db_dumper.54: Error: Unexpected error from database library (8) in "../db__dump.c" line 2835 db_dumper.54: Error: Error from libdb (8) cleartool: Error: Could not dump database. cleartool: Error: Trouble dumping versioned object base "/vobstg/pvob.vbs". dbcheck status, Processing delete chain: 0 records on delete chain. Processing records: 100% Database consistency check completed 0 errors were encountered in 0 records/nodes Check for HyperSlink and got following error cleartool checkvob -hlinks -hltype hltype:HyperSlink vob:/vob/pvob cleartool: Error: Hyperlink type not found: "HyperSlink". Stuck in the migration A: It can help knowing at what stage the dp_dumb was before exiting in error, like in this thread. But the usual course of action is to compressed a locked pvob content, and send it to IBM for analysis. The HyperSlinks aren't an issue here (as they would when making a replica). As mention in this IBM support thread: IBM support resolved this, one of the activity had spacial character which caused this. Now reformat vob works. Yet to start the sync with master site. A: Issue is with special character in activity, IBM gave me tool to fix it. Now things are normal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hotswapping / Edit and continue for C/C++, Linux I'm looking for an IDE that supports a (Visual Studio's) Edit and continue -like feature. I know Netbeans has it for Java (called hotswapping, Fix and continue), but can not find anything about an implementation for C/C++ for Linux systems. Any help would be very much appreciated. A: To the best of my knowledge, this feature is not available in the GCC toolchain. The closest you'll get is the gdb's rewind, but that's not the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Codeigniter: Paypal IPN and csrf_protection I'm working with codeigniter-paypal-ipn and have csrf_protection enabled. This seems to block the access from Paypal to my IPN controller. If i disable csrf_protection it works just fine, with csrf_protection enabled, paypal IPN service throws a 500 Internal Server Error. Is there a way to solve this without disabling the csrf_protection? If not, can i disable the csrf_protection just for that controller? Thanks. A: Alex the creator of codeigniter-paypal-ipn here. At the moment I'm not aware of a way to get the IPN post working with csrf_protection enabled. If you look at how another language/framework does it, e.g. django-paypal IPN - they add a CSRF exemption to the specific IPN controller. As imm says, this type of fine-grained control won't be available in CodeIgniter till a version with this pull request is merged (if you can't wait, try caseyamcl's approach below as it doesn't involve hacking CI core...) I've updated my project's README to make the CSRF situation clearer. A: Someone asked a similar question on http://ellislab.com/forums/viewthread/200625/, disabling csrf for a single controller will be available in the next release. A: I know the question has been answered, but I did it in a similar way without hacking the CI core. I added the following to my application/config/config.php file: $config['csrf_ignore'] = array('api'); The array can include any paths you like. The example above will apply to any paths that begin with 'api'. Then, I added the following file: application/core/MY_Input.php: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Input extends CI_Input { function _sanitize_globals() { $ignore_csrf = config_item('csrf_ignore'); if (is_array($ignore_csrf) && count($ignore_csrf)) { global $URI; $haystack = $URI->uri_string(); foreach($ignore_csrf as $needle) { if (strlen($haystack) >= strlen($needle) && substr($haystack, 0, strlen($needle)) == $needle) { $this->_enable_csrf = FALSE; break; } } } parent::_sanitize_globals(); } } /* EOF: MY_Input */
{ "language": "en", "url": "https://stackoverflow.com/questions/7628353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Convert UUID to hex string and vice versa A UUID in the form of "b2f0da40ec2c11e00000242d50cf1fbf" has been transformed (see the following code segment) into a hex string as 6232663064613430656332633131653030303030323432643530636631666266. I want to code a reverse routine and get it back to the original format as in "b2f0...", but had a hard time to do so, any help? byte[] bytes = uuid.getBytes("UTF-8"); StringBuilder hex = new StringBuilder(bytes.length* 2); Formatter fmt = new Formatter(hex); for (byte b : bytes) fmt.format("%x", b); A: final String input = "6232663064613430656332633131653030303030323432643530636631666266"; System.out.println("input: " + input); final StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length(); i += 2) { final String code = input.substring(i, i + 2); final int code2 = Integer.parseInt(code, 16); result.append((char)code2); } System.out.println("result: " + result); It prints: input: 6232663064613430656332633131653030303030323432643530636631666266 result: b2f0da40ec2c11e00000242d50cf1fbf A: Here you go: import java.util.Formatter; class Test { public static void main(String[] args) { String uuid = "b2f0da40ec2c11e00000242d50cf1fbf"; byte[] bytes = uuid.getBytes(); StringBuilder hex = new StringBuilder(bytes.length * 2); Formatter fmt = new Formatter(hex); for (byte b : bytes) { fmt.format("%x", b); } System.out.println(hex); /******** reverse the process *******/ /** * group the bytes in couples * convert them to integers (base16) * and store them as bytes */ for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } /** * build a string from the bytes */ String original = new String(bytes); System.out.println(original); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ninject - Kernel in static class? Is it right at all to "wrap" a StandardKernel with the required NinjectModules in a static class in a separate, shared library, and use that same library whenever injection is needed (instead of instantiating a new kernel everytime)? Edit: I am trying to use Ninject from within the WCF service I am developing at the moment. (Please bear with me if what I am saying is completely rubish since I just started learning about DI and IoC containers) A: See https://github.com/ninject/ninject.extensions.wcf . This extension will create the WCF service using the Ninject kernel. That way you can use constructor injection instead of using the Service Locator pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to fix a non responding ext.list? I've got a problem with an Ext.List: You press a button on the main menu and are shown the list. Everything on it works fine and it let's you choose, where to go deeper inside the app. No problems so far. But if you then go back to the main menu by pressing a "back"-button and reenter the page, that shows this Ext.List, it doesn't work anymore: you can't select an entry of the list. The "back"-button removes the list, if you return to the main menu this way: setTimeout(function(){page.removeAll();},100); What's my mistake? Do you know a better method than "page.removeAll()" that really kills this Ext.List to let it then be completely recreated when I choose to see it in my main menu? Thanks in advance, you guys have the best tips and tricks. A: It's hard to tell without seeing your code but I suspect that there is a javascript error somewhere in the program flow that you described. If you display the javascript console in either Chrome or Firefox it should show the error. Depending upon how the function that creates the list is defined it would normally recreate the list upon page/function entry and there should be no need to 'kill' the list explicitly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSP with Servlet - Bean unable to convert Date value from input field After a lot of research I've been unable to find a resolution. I have a JSP page backed by a servlet that I'm setting up to run on the Google App Engine. I've created a bean (Client) to facilitate the transfer of my form fields between the JSP and the servlet. This has been working fine in most cases. As a part of my servlet, I do some validation on the user-entered form values. If there is validation error I use the RequestDispatcher to forward the request back to the JSP page so that an error message can be shown. When this happens, I get the following error: org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to convert string "02-10-2011" to class "java.util.Date" for attribute "appointmentDate": Property Editor not registered with the PropertyEditorManager Here are the segments of my code that may be of interest: public class Client { public Client() {} private long clientId; private String name; private String address; private String homePhone; private String cellPhone; private String workPhone; private String fax; private String city; private String postalCode; private String emailAddress; private String directions; private String style; private String decoratingThemes; private String comments; private String referralSource; private boolean emailList; private Date appointmentDate; public long getClientId() { return clientId; } public void setClientId(long clientId) { this.clientId = clientId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getHomePhone() { return homePhone; } public void setHomePhone(String homePhone) { this.homePhone = homePhone; } public String getCellPhone() { return cellPhone; } public void setCellPhone(String cellPhone) { this.cellPhone = cellPhone; } public String getWorkPhone() { return workPhone; } public void setWorkPhone(String workPhone) { this.workPhone = workPhone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getDirections() { return directions; } public void setDirections(String directions) { this.directions = directions; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public String getDecoratingThemes() { return decoratingThemes; } public void setDecoratingThemes(String decoratingThemes) { this.decoratingThemes = decoratingThemes; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getReferralSource() { return referralSource; } public void setReferralSource(String referralSource) { this.referralSource = referralSource; } public boolean isEmailList() { return emailList; } public void setEmailList(boolean emailList) { this.emailList = emailList; } public Date getAppointmentDate() { return appointmentDate; } public void setAppointmentDate(Date appointmentDate) { this.appointmentDate = appointmentDate; } } The bean declaration on the page: <jsp:useBean id="Client" class="com.HC.RaveDesigns.Entity.Client" scope="session"/> The method forwarding the request. private void dispatchError(String error, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("error",error); RequestDispatcher rd = req.getRequestDispatcher("ManageClient.jsp"); rd.forward(req,resp); } A: This is because user sends you String not Date, and this is your job to convert this text into Date. The fastest fix will be: * *change the parameter type in setter type to String *convert string to Date inside this setter. Example: public void setAppointmentDate(String appointmentDate) { DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); this.appointmentDate = df.parse(appointmentDate); } Additionally, you should change getter in the same way or use fmt:formatDate like @duffymo has suggested. Also remember to handle date parse exception - Never trust user input A: Use JSTL <fmt:formatDate> in your JSPs. You should be using JSTL. You need to use DateFormat to parse that String into a java.util.Date: DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); formatter.setLenient(false); Date d = formatter.parse("02-10-2011");
{ "language": "en", "url": "https://stackoverflow.com/questions/7628368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FileNotFoundException for bean definition file happens only online, not on localhost When I published a war file for an application that works locally with Eclipse WTP, I had a FileNotFoundException for the bean.xml file with my beans definitions. SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [META-INF/spring/beans.xml]; nested exception is java. io.FileNotFoundException: class path resource [META-INF/spring/beans.xml] cannot be opened because it does not exist at Caused by: java.io.FileNotFoundException: class path resource [META-INF/spring/beans.xml] cannot be opened because it does not exist ... I created the war file with mvn war:war and copied in the webapps folder of Tomcat 7. beans.xml is located in src/main/resources/META-INF/spring/beans.xml and I've the following in my pom.xml: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <webResources> <resource> <directory>src/main/resources</directory> </resource> </webResources> </configuration> </plugin> In the war file beans.xml gets packaged in META-INF/spring/beans.xml In my web.xml I've: <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:META-INF/spring/beans.xml</param-value> </context-param> However the file is not found. How to solve the problem? UPDATE: as Matthew Farwell suggested, is bean.xml is not packaged in the right location, so it's not in the class path, I think it's specified with maven-war-plugin parameters, now I try to look at its documentation. If someone knows it would be helpful. UPDATE 2: As explained in maven-war-plugin documentation, there is an optional parameter called targetPath. I tried and after changing maven-war-plugin configuration adding targetPath it gets packaged correctly. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1.1</version> <configuration> <webResources> <resource> <directory>src/main/resources</directory> <targetPath>WEB-INF/classes</targetPath> </resource> </webResources> </configuration> </plugin> UPDATE 3: About Ryan Stewart's suggestion, I started my initial pom setup using roo, but after that I've done many changes and I'm not using roo any more. The directory src/main/resources is not mentioned in any other places in pom.xml (I've used grep), however the only setting that looks suspicious to me is: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.5</version> <configuration><encoding>UTF-8</encoding></configuration> </plugin> I've commented out that plugin, but nothing changed, then I commented out the configuration part of maven-war-plugin, but src/main/resources was not added to the war anymore, so for now I've added it back and I'm uploading it to test it online (it's still a staging server actually, not the final one anyway). UPDATE 4 Ryan Stewart suggested that the problem was that I was running "mvn war:war" instead of "mvn package", and that was indeed the problem. With my targetPath, the resources appeared in WEB-INF/classes, but there weren't any classes there. I was fighting an uphill battle, while instead the simpler solution was to remove the configuration part as in update 3, and use "mvn package" to build the war file. Thank you to both of you Ryan and Matthew, not only I solved my problem, but I've also learnt something more about Maven. A: In a war, / is not part of the classpath for a webapp. The classpath includes /WEB-INF/classes and all of the jars in /lib. See Apache Tomcat 6.0 - Class Loader HOW-TO WebappX — A class loader is created for each web application that is deployed in a single Tomcat instance. All unpacked classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application, are made visible to this web application, but not to other ones. The other web servers will have similar rules. If you wish to reference something as part of the classpath, put it in WEB-INF/classes. A: I have to assume you have another part of the POM that's excluding the file in question from being processed as a classpath resource, else it should be working. Either * *Stop doing that, and it'll work fine--the content of src/main/resources becomes classpath resources by default--or *remove the classpath: from your path. Without that prefix, the path given in contextConfigLocation will be resolved against the root of the WAR file, and it will correctly find your file in META-INF/spring. If you take path 1, then you should remove the webResources section, or you'll end up with the file in two places--not problematic, but potentially confusing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write a data in plist? I have followed this answer to write data to the plist How to write data to the plist? But so far my plist didn't change at all. Here is my code :- - (IBAction)save:(id)sender { NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"]; NSString *drinkName = self.name.text; NSString *drinkIngredients = self.ingredients.text; NSString *drinkDirection = self.directions.text; NSArray *values = [[NSArray alloc] initWithObjects:drinkDirection, drinkIngredients, drinkName, nil]; NSArray *keys = [[NSArray alloc] initWithObjects:DIRECTIONS_KEY, INGREDIENTS_KEY, NAME_KEY, nil]; NSDictionary *dict = [[NSDictionary alloc] initWithObjects:values forKeys:keys]; [self.drinkArray addObject:dict]; NSLog(@"%@", self.drinkArray); [self.drinkArray writeToFile:path atomically:YES]; } Do I need to perform something extra? I am new to iPhone SDK so any help would be appreciated. A: You are trying to write the file to your application bundle, which is not possible. Save the file to the Documents folder instead. NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; path = [path stringByAppendingPathComponent:@"drinks.plist"]; The pathForResource method can only be used for reading the resources that you added to your project in Xcode. Here's what you typically do when you want to modify a plist in your app: 1. Copy the drinks.plist from your application bundle to the app's Documents folder on first launch (using NSFileManager). 2. Only use the file in the Documents folder when reading/writing. UPDATE This is how you would initialize the drinkArray property: NSString *destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; destPath = [destPath stringByAppendingPathComponent:@"drinks.plist"]; // If the file doesn't exist in the Documents Folder, copy it. NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:destPath]) { NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"]; [fileManager copyItemAtPath:sourcePath toPath:destPath error:nil]; } // Load the Property List. drinkArray = [[NSArray alloc] initWithContentsOfFile:destPath];
{ "language": "en", "url": "https://stackoverflow.com/questions/7628372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Spring 3 in jar configuration (auto configuration) I'm looking for some kind of "best practice" informations about Spring jar configuration. I have a web project (war) and I need connect some jar libraries - my jars which contains additional functions. These jars contains Spring services. But when I connect jar, the service class did not work, because Spring don't know about that. So I need to tell Spring about this by “package auto scan” configuration inside my jar. The final solution must be war project (main functions) and some additional jars which contains other functions. When I add jar into war project, I don't want to change configuration in applicationContext.xml (in war). I want minimal dependency to war project. I was thinking, when if I place applicationContext.xml to META-INF folder in jar it will be auto loaded by Spring, but it is not. Do you know how can i solve this? May be some kind of “after startup dynamic configuration” :-). thanx A: If you are trying to load annotated beans from the jars into your war's Spring context, you can set up a component scan in the war's context xml file to scan the packages in the jars. If you are trying to load beans defined in XML files from the jars, you can include them using something like this in your war's Spring context xml file: <import resource="classpath:path/to/config/in/jar/beans-from-jar.xml"/> You shouldn't need to have your jar know anything about your war this way. You just scan the annotated beans and/or import the config from the jar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Script to pull an image from a Website I have a website on which I want to post the current xkcd comic. xkcd provides a link for embedding, but each link has a unique name for each comic. For example, http://imgs.xkcd.com/comics/hotels.png is today's comic. Is there any way to write a simple script to grab the latest comic from their website? Currently I'm just manually updating the URL on my site which is painful. A: Randall provides RSS and Atom feeds for recent XKCDs. Parse one of those to get the latest comics. A: Consider the problem for a moment. Where is the name of the current comic image shown? It's shown on the xkcd home page. You could write a script to retrieve the home page, search through the HTML for the current image link, and use that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter data from model? I have two models: class ModelOne(models.Model): something = models.TextField[...] class ModelTwo(models.Model): other_something = models.TextField[...] ref = models.ForeignKey(ModelOne) And I want to write function in ModelOne which return me all related objects from ModelTwo. It's important: In ModelOne. How to do it? A: Invoke self.modeltwo_set.all().
{ "language": "en", "url": "https://stackoverflow.com/questions/7628384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: displaying image from sqlite error I have saved an image in sqlite and i am trying to retrieve it and displaying it in a QLabel using this code. connect(ui.tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(getImage(QModelIndex,QModelIndex))); void smith::getImage() { ....... QModelIndex index = ui.tableView->currentIndex(); QString sqlQuery = QString("SELECT image FROM %1 WHERE id=:id").arg(tableName); query.prepare(sqlQuery); QSqlRecord recordz = tableModel->record(index.row()); query.bindValue(":id", recordz.value("id").toInt()); query.exec(); tableModel->select(); QByteArray array = query.value(0).toByteArray(); QBuffer buffer(&array); buffer.open( QIODevice::ReadOnly ); QImageReader reader(&buffer, "PNG"); QImage image = reader.read(); if( image.isNull() ) { QMessageBox::about(this, tr("Image Is Null"), tr("<h2>Image Error</h2>" "<p>Copyright &copy; 2011." "<p>Message Box To Check For " " Errors " )); } ui.imageLabel->setPixmap( QPixmap::fromImage(image)); } The project compiles without any errors but the image won't show. A: I'd suggest adding some error-checking to your code, to narrow down where the error occurs. For example, the documentation for QImageReader::read() says that if the image can't be read, the resultant image is null, and it tells you how to find out what the error was. So after your call to reader.read(), check image.isNull(). And earlier on, check array.size() to make sure that you really got a value back from the database. And the check the result returned by buffer.open( QIODevice::ReadOnly ) - the docs say it will return false if the call failed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Echo results of mysql query with php I have this query $people = "SELECT name FROM people"; $people = mysql_query($people) or die(mysql_error()); $row_people = mysql_fetch_assoc($people); $totalRows_people = mysql_num_rows($people); I can echo the results within a unordered list using a while loop like this <ul> <?php {do { ?> <li><?php echo $row_people['name'];?></li> <?php } while ($row_people = mysql_fetch_assoc($people));}?> </ul> But I can't used this as my html does not allow it. <ul> <li class="first"> <a href="?name=kate">Kate</a> <li> <li class="second"> <a href="?name=john"><img src="john.jpg" />John</a> <li> <li class="third"> <a href="?name=max"><span>Max</span></a> <li> </ul> My question is how can echo the name that was retrieved from the database into the appropriate place within this html? Thanks for your help. A: Try this: <?php $people = "SELECT name FROM people"; $people = mysql_query($people) or die(mysql_error()); if(mysql_num_rows($people) > 0){ ?> <ul> <?php while ($row_people = mysql_fetch_assoc($people)){ ?> <li><?php echo htmlentities($row_people['name']);?></li> <?php } ?> </ul> <?php } ?> A: You'll just have to create a renderer for each "type" of user (assuming you have a type property on the user rows) or based on their attributes. For example, let's say you're going to have to filter based on the attributes: <?php function render_simple($person) { return '<a href="?' . $person['name'] . '">' . $person['name'] . '</a>'; } function render_with_image($person) { return '<a href="?' . $person['name'] . '"><img src="' . $person['image'] . '.jpg"/>' . $person['name'] . '</a>'; } function render_special($person) { return '<a href="?' . $person['name'] . '"><span>' . $person['name'] . '</span></a>'; } function render_person($person) { if ($person['image']) { return render_with_image($person); } if ($person['special']) { return render_special($person); } return render_simple($person); } $i = 0; while ($row_people = mysql_fetch_assoc($people)){ ?> <li class="index<?php echo ++$i; ?>"> <?php echo render_person($person); ?> </li> <?php } ?> This should work, with the exception that instead of class names first, second, etc, you'll now have index1, index2, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression - need to get string from html comment I need to get string from comment in HTML file, I was trying to do it with DOM, but I didn't find good solution with this method. So I want to try it with regular expressions, but I can't find satisfactory solution. Please, can you help me? This is what I need: <!--adress-"String here I need to get"--> Thanks in advance for answer A: Look into $matches after this code preg_match('~<!--adress-"(.*?)"-->~msi', $string, $matches); A: HTML comments are regular; you can just match <!--adress-"([^">]+)"--> and get the first group. This assumes that the comments are always well-formed and always have a quoted string containing no quotes. A: It will be more accurate: $regex = '<!--(.+?)-"{0,1}(.+?)"{0,1}-->'; preg_match_all($regex, $html, $matches_array); Just do the var_dump($matches_array) and see results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting an Android Button visible after a certain period of time? I have a button that I don't want to be clickable until a certain amount of time has run (say, 5 seconds?) I tried creating a thread like this continueButtonThread = new Thread() { @Override public void run() { try { synchronized(this){ wait(5000); } } catch(InterruptedException ex){ } continueButton.setVisibility(0); } }; continueButtonThread.start(); But I can't modify the setVisibility property of the button within a different thread. This is the error from the LogCat: 10-02 14:35:05.908: ERROR/AndroidRuntime(14400): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Any other way to get around this? A: The problem is that you can touch views of your activity only in UI thread. you can do it by using runOnUiThread function. I would like to suggest you to use handler.postDelayed(runnable, 5000)` A: You must update your view from UI-thread. What you are doing is you are updating from non-ui-thread. Use contextrunOnUiThread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub }}); or use handler and signalize hand.sendMessage(msg) when you think is right time to update the view visibility Handler hand = new Handler() { @Override public void handleMessage(Message msg) { /// here change the visibility super.handleMessage(msg); } }; A: You can use the postDelayed method from the View class (A Button is a child of View) A: here is simple answer i found Button button = (Button)findViewBYId(R.id.button); button .setVisibility(View.INVISIBLE); button .postDelayed(new Runnable() { public void run() { button .setVisibility(View.VISIBLE); } }, 7000);
{ "language": "en", "url": "https://stackoverflow.com/questions/7628402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java/JavaScript graph layout library that supports node size Could anyone please suggest a Java or JavaScript library to layout a graph. The main requirement is that it should support graph layout algorithm taking into account a node size. I myself found a list of Java libraries to work with graphs and already tried JUNG, but I wasn't been able to find any graph layout implementations for JUNG that would take into account a node size. As a result some nodes happen to be too close so they're overlapping. P.S.: I think it should be pointed out that I only look for a library to layout the graph (i.e. determine its nodes positions). Calculated node positions will be then transfered from the server to a client requested the layout using http. P.P.S.: a JavaScript library would be as good. I already tried arbor.js and it didn't work out for me because it doesn't take into account a node size. A: is this what you are looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7628407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How does %NNN$hhn work in a format string? I am trying out a classic format string vulnerability. I want to know how exactly the following format string works: "%NNN$hhn" where 'N' is any number. E.g: printf("%144$hhn",....); How does it work and how do I use this to overwrite any address I want with arbitrary value? Thanks and Regards, Hrishikesh Murali A: It's a POSIX extension (not found in C99) which will simply allow you to select which argument from the argument list to use for the source of the data. With regular printf, each % format specifier grabs the current argument from the list and advances the "pointer" to the next one. That means if you want to print a single value in two different ways, you need something like: printf ("%c %d\n", chVal, chVal); By using positional specifiers, you can do this as: printf ("%1$c %1$d\n", chVal); because both format strings will use the first argument as their source. Another example on the wikipedia page is: printf ("%2$d %2$#x; %1$d %1$#x",16,17); which will give you the output: 17 0x11; 16 0x10 It basically allows you to disconnect the order of the format specifiers from the provided values, letting you bounce around the argument list in any way you want, using the values over and over again, in any arbitrary order. Now whether you can use this as an user attack vector, I'm doubtful, since it only adds a means for the programmer to change the source of the data, not where the data is sent to. It's no less secure than the regular style printf and I can see no real vulnerabilities unless you have the power to change the format string somehow. But, if you could do that, the regular printf would also be wide open to abuse.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing a url in a form from page to servlet drops part of query string If I have a form on a JSP like this: <form action = "/myApp/myServlet?rssFeedURL=${rssFeedURL}' />" method = "post"> <input type = "button" value = "See data for this RSS feed."/> </form> What I find is that if the variable ${rssFeedURL} has no query string, then the server receives it properly, e.g.: http://feeds.bbci.co.uk/news/rss.xml But if a query string exists, e.g.: http://news.google.com/news?ned=us&topic=m&output=rss I expect that it is to do with the encoding of the '&' character. Can anyone advise? The server receives only: http://news.google.com/news?ned=us My pages are charset=UTF-8 encoded. A: You need to URL-encode request parameters. Otherwise they will be interpreted as part of the initial request URL. JSTL offers you the <c:url> for this. <c:url var="formActionURL" value="/myApp/myServlet"> <c:param name="rssFeedURL" value="${rssFeedURL}" /> </c:url> <form action= "${formActionURL}" method="post"> ... An alternative is to create an EL function which delegates to URLEncoder#encode().
{ "language": "en", "url": "https://stackoverflow.com/questions/7628410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grammar - RegEx - containing five vowels (aeiou) I am trying to learn regular expression. I have L = {a, b, x, y, z, i, o, u, e, c} I want to construct a regular expression that describes a strings that contain the five vowels in alphabetical order (aeiou). All strings will have at least one of all five vowels. Do I have to lay them out in order as they are in the set? like a(b*x*y*z*i*o*u*ec*)iou or can I mix them up like: aeiou(b*x*y*z*c*) Since, they are not in order in the set, does that mean the first solution is what I am looking for? A: In most regex languages, you'll need something like: [^aeiou]*a[^aeiou]*e[^aeiou]*i[^aeiou]*o[^aeiou]*u[^aeiou]* That much is essentially uniform. You then have to deal with 'start of word' and 'end of word' issues, which depend on the context and the regex language. With one word per line, you can simply use '^' to start and '$'. Using your preferred notation and knowing that the complete alphabet used consists of the 10 letters, and assuming you can do grouping, then you can write: (b*c*x*y*z*)*a(b*c*x*y*z*)*e(b*c*x*y*z*)*i(b*c*x*y*z*)*i(b*c*x*y*z*)*u(b*c*x*y*z*)* The (b*c*x*y*z*)* part says zero or more repeats of "zero or more b's followed by zero or more c's, ..., followed by zero or more z's". This does what you require; but it also demonstrates why character class notation is such a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ajax ModelpopupExtender Cant work I am using modelpopupextender in asp.net and this code is working window is popup sucessfuly but cancel button can't work; can anybody tell me why? <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager> <asp:Button ID="buttonOpen" runat="server" style="display:none" ></asp:Button> <asp:Panel ID="Panel3" runat="server" BackColor="#99CCFF" Height="269px" Width="350px" style="display:none"> <table width="100%" style="border:Solid 3px #D55500; width:100%; height:100%" cellpadding="0" cellspacing="0"> <tr style="background-color:#333399"> <td colspan="2" style=" height:10%; color:White; font-weight:bold; font-size:larger" align="center">Time Details</td> </tr> <tr> <td> <asp:Label ID="Label19" runat="server" Text="Time From"></asp:Label> </td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="Label20" runat="server" Text="Time To"></asp:Label> </td> <td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Label ID="Label21" runat="server" Text="Number of Slots"></asp:Label> </td> <td> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> </td> </tr> <tr> <td> <asp:Button ID="Button1" runat="server" Text="Add" /> </td> <td> <asp:Button ID="btnCancel" runat="server" Text="Cancel" /> </td> </tr> </table> </asp:Panel> <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" OnCancelScript="btnCancel" PopupControlID="panel3" TargetControlID="buttonOpen" BackgroundCssClass="modalBackground"> </asp:ModalPopupExtender> A: You need to set the CancelControlID property, not the OnCancelScript property (unless you want to execute a script after the cancel button is clicked). So for your scenario, do this: <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="btnCancel" PopupControlID="panel3" TargetControlID="buttonOpen" BackgroundCssClass="modalBackground"> </asp:ModalPopupExtender>
{ "language": "en", "url": "https://stackoverflow.com/questions/7628413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving lots of dictionaries and arrays My game comes with lots of .plist files containing many dictionaries, arrays, etc. They are about each party member's stats, info, etc. A singleton is in charge of reading all those files and provide the necessary data for my game to run. The game, at many points, will edit such values from the singleton, like a hero's level, stats, etc. Eventually, the player will be given the option to "save" the game. My original idea was to basically tell the singleton to "overwrite" the .plist files within the project with the new edited data (the new data might have changes in stat entries etc, or even brand-new dictionaries representing new party members etc) and done. But, I don't know how to do that, or even if it is possible. I heard about NSUserDefaults, but I don't know if it suitable for what I am aiming, considering that the amount of dictionaries and arrays will be quite big, and that it is possible to keep adding up more dictionaries and arrays in the future. Imagine that the party can have as many members as you wish, for instance. *Note: there are no multiple save files/profiles. When you press save, it saves, without asking anything else. A: NSUserDefaults is not suitable for any substantial amount of data. Just write the plist to the documents directory, specify atomic:YES to insure the entire file is written. - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag If YES, the array (or dictionary) is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the array is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing. This method exists for both NSArray and NSDictionary, Obtain the document directory: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; BOOL status = [NSDictionary writeToFile:filePath atomically:YES]; NSDictionary could have ten NSArray depending on the top element of the plist. Consider using CoreData.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Algorithm or api to create Intrusion Detection System inputs Hello I want to develope Intrusion detection system using neural network. I know there are 41 inputs. ( I know this from the Dataset which I used to train the neural network) . I need help how to capture this 41 inputs in live connection. Please somebody help me or atleast guide me in the correct direction. Thank you for your answers in advance... A: What you are trying to do is feature extraction or reduction on your input data. As input data I could imagine logs from a firewall, captured packets, ... And as features you could have things like failed login attempts per time unit, number of connections, ... But if you want to have your system work with the training you feed it, you need to have the same distribution of the features in the data you process, as you have trained it on (or at least very similar). So to make matters short and simple : if you want to use the training data you cite, you need to get to know exactly which data they worked on gathering the training data, and exactly how they preprocessed it. A: I have answered your other question (http://stackoverflow.com/questions/7587657/building-intrusion-detection-system-but-from-where-to-begin) more thoroughly. But I repeat here. Read this article to learn more about how it (KDD99) is constructed Article (Lee2000framework) Lee, W. & Stolfo, S. J. A framework for constructing features and models for intrusion detection systems ACM Trans. Inf. Syst. Secur., ACM, 2000, 3, 227-261
{ "language": "en", "url": "https://stackoverflow.com/questions/7628415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you have an OR in a WHERE statement inside a mysql query? Is it possible to have an OR inside a WHERE statement in a mysql query as I have done below. $query = mysql_query("SELECT * FROM fields WHERE post_id=$id OR post_id="" order by id desc") or die(mysql_error()); This produces a server error when run on my site. Any thoughts on how I could accomplish this? Thanks in advance. A: Yes you can have an OR. What is the type of post_id? If post_id is a character type: "SELECT * FROM fields WHERE post_id='$id' OR post_id='' order by id desc" If it's an integer then it can't be equal to the empty string. Did you mean post_id IS NULL instead? A: What is the error? It looks like you have not escaped the double quote in the query. It should be: $query = mysql_query("SELECT * FROM fields WHERE post_id=$id OR post_id=\"\" order by id desc") or die(mysql_error()); A: what are the errors.. as such ur query is fine but u string problems with all these double quotes.. try something like this.. $query = mysql_query("SELECT * FROM fields WHERE post_id = " . $id . " OR post_id='' order by id desc") or die(mysql_error());
{ "language": "en", "url": "https://stackoverflow.com/questions/7628418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List all child nodes of a parent node in a treeview control in Visual C# I have a treeview control, and it contains a single parent node and several child nodes from that parent. Is there a way to obtain an array or list of all the child nodes from the main parent? i.e. getting all the nodes from treeview.nodes[0], or the first parent node. A: You can add to a list recursively like this: public void AddChildren(List<TreeNode> Nodes, TreeNode Node) { foreach (TreeNode thisNode in Node.Nodes) { Nodes.Add(thisNode); AddChildren(Nodes, thisNode); } } Then call this routine passing in the root node: List<TreeNode> Nodes = new List<TreeNode>(); AddChildren(Nodes, treeView1.Nodes[0]); A: public IEnumerable<TreeNode> GetChildren(TreeNode Parent) { return Parent.Nodes.Cast<TreeNode>().Concat( Parent.Nodes.Cast<TreeNode>().SelectMany(GetChildren)); } A: You could do something like this .. to get the all nodes in tree view .. private void PrintRecursive(TreeNode treeNode) { // Print the node. System.Diagnostics.Debug.WriteLine(treeNode.Text); MessageBox.Show(treeNode.Text); // Print each node recursively. foreach (TreeNode tn in treeNode.Nodes) { PrintRecursive(tn); } } // Call the procedure using the TreeView. private void CallRecursive(TreeView treeView) { // Print each node recursively. TreeNodeCollection nodes = treeView.Nodes; foreach (TreeNode n in nodes) { PrintRecursive(n); } } would you pls take alook at this link . http://msdn.microsoft.com/en-us/library/wwc698z7.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7628419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Should I create individual properties in a class or just a method to set the values? I am learning vb.net and I am having trouble wrapping my head around the following... I can create several properties of a custom class and get/set values or I can create a method to set them all at once. If each property is going to allow read and write should I just make a method to assign values all at once? I assume that I am missing a very important piece here. Example: I can create 2 properties: Public Class Employee Public Property LastName as string Get Return strLastName End get Set(ByVal value as string) strLastName= value End Set End Property Public Property FirstName as string Get Return strFirstName End get Set(ByVal value as string) strFirstName= value End Set End Property End Class or I can create a method: Public Class Employee Public Sub AddEmployee(ByVal strLastName, ByVal strFirstName) LastName = strLastName FirstName = strFirstName End Sub End Class I apologize for such a noob question, but any insight is greatly appreciated. thank you! A: If you only have a single method, you will have to use it even if you only want to change the value of a single field. Additionally, in such a method, if you need to validate the input, you will need to write quite a lot of code for validation that is not relevant to all of the fields. If values must be updated together, use a method to update them together and do not provide setters. The reality of things is that how to do this depends on what you are modelling in your class. There are no hard and fast rules that say that properties are better than methods or vice versa. A: There is no reason not to support both properties and a method that sets multiple properties. Commonly, a constructor is used to create an instance of the class and to set some properties. In VB, naming a class method "New" defines it as a constructor. In your example, if you rename your AddEmployeee method to New, you will have a perfectly fine constructor. Then you program can create new instances as such: Dim emp1 as New Employee("Burdell", "George")
{ "language": "en", "url": "https://stackoverflow.com/questions/7628432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DWORD and unsigned int I'm getting this error and can't correct it. Any help is appreciated. Thanks. error C2440: '=' : cannot convert from 'DWORD *' to 'unsigned int' IntelliSense: a value of type "DWORD *" cannot be assigned to an entity of type "unsigned int" using namespace std; typedef vector<WIN32_FIND_DATA> tFoundFilesVector; std::wstring LastWriteTime; int getFileList(wstring filespec, tFoundFilesVector &foundFiles) { WIN32_FIND_DATA findData; HANDLE h; int validResult=true; int numFoundFiles = 0; h = FindFirstFile(filespec.c_str(), &findData); if (h == INVALID_HANDLE_VALUE) return 0; while (validResult) { numFoundFiles++; foundFiles.push_back(findData); validResult = FindNextFile(h, &findData); } return numFoundFiles; } void showFileAge(tFoundFilesVector &fileList) { unsigned int fileTime,curTime, age; tFoundFilesVector::iterator iter; FILETIME ftNow; __int64 nFileSize; LARGE_INTEGER li; li.LowPart = ftNow.dwLowDateTime; li.HighPart = ftNow.dwHighDateTime; CoFileTimeNow(&ftNow); curTime = ((_int64) &ftNow.dwHighDateTime << 32) + &ftNow.dwLowDateTime; for (iter=fileList.begin(); iter<fileList.end(); iter++) { fileTime = ((_int64)iter->ftLastWriteTime.dwHighDateTime << 32) + iter- >ftLastWriteTime.dwLowDateTime; age = curTime - fileTime; cout << "FILE: '" << iter->cFileName << "', AGE: " << (INT64)age/10000000UL << " seconds" << endl; } } int main() { string fileSpec = "*.*"; tFoundFilesVector foundFiles; tFoundFilesVector::iterator iter; int foundCount = 0; getFileList(L"*.c??", foundFiles); getFileList(L"*.h", foundFiles); foundCount = foundFiles.size(); if (foundCount) { cout << "Found "<<foundCount<<" matching files.\n"; showFileAge(foundFiles); } return 0; } Its on this line..... A: The error is here: curTime = ((_int64) &ftNow.dwHighDateTime << 32) + &ftNow.dwLowDateTime; dwHighDateTime and dwLowDateTime are already of type int. Yet you are taking the address of them. Therefore the assignment to curTime becomes pointer to int. What you want is this: curTime = ((_int64) ftNow.dwHighDateTime << 32) + ftNow.dwLowDateTime; Second Issue: curTime and fileTime are only 32-bits. You need to make them 64-bit integers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: instanceof in SpEL i have a class with the method: Code: List<Entity> getData() {...} and some classes which extends Entity: Project, Phase, Invoice, Payment. and i would like to do something like this: @PostFilter("filterObject instanseof Project ? filterObject.manager == principal : filterObject instanceof Phase ? filterObject.project.manager == principal : filterObject instanceof Invoice ? filterObject.phase.project == principal : filterObject instanceof Payment ? filterObject.invoice.phase.project.manager == principal : true") is it a legal? or how to use "instanceof" correctly? A: The correct syntax for SpEL would be like filterObject instanceof T(Project). (Please see SpEL section 6.5.6.1 - Relational operators)
{ "language": "en", "url": "https://stackoverflow.com/questions/7628437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Fancy thumbnail hover effect I'm using a script - for a pretty small image gallery within a tabbed content area. I'm using; http://www.sohtanaka.com/web-design/fancy-thumbnail-hover-effect-w-jquery/ But customized to almost a fourth the size, only 3 images, and realigned to have the thumbs sit directly below the 'main view' image area. I've done it successfully, and visually it's great. The thumbs are about 50px, that expand to about 60px on hover and when clicked - it takes the main view area with the correct image as it's supposed too. Problem is, and is really weird as I've used this script over and over again - for some reason the parameters of the 3 thumbs are duplicated above the main view as well - but the actual images are not visible. When a user put their mouse above the main view - anywhere between the 50px 60px square/rectangle parameter - the hover of the below images appear. I've been going through the code over and over again - I know it's something stupid - if anyone could throw me a suggestion that'd be great. Here's a screenshot visual of the situation - check it out; http://tinypic.com/r/2nt8o7t/7 The mark-up: <!-- Thumb Gall Mark-Up --> <div class="containerslide"> <ul class="thumb"> <li><a href="img/appimg_1.jpg"><img src="img/appimg_1.jpg" alt="" /></a></li> <li><a href="img/appimg_2.jpg"><img src="img/appimg_2.jpg" alt="" /></a></li> <li><a href="img/appimg_3.jpg"><img src="img/appimg_3.jpg" alt="" /></a></li> </ul> <div id="main_view"> <img src="img/appimg_1.jpg" alt="" /></a><br /> </div> </div> <!--End Thumb Gall Mark-Up--> The query: <script src="js/modernizr.custom.37797.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function(){ //Larger thumbnail preview $("ul.thumb li").hover(function() { $(this).css({'z-index' : '10'}); $(this).find('img').addClass("hover").stop() .animate({ marginTop: '0px', marginLeft: '0', top: '360px', left: '0', width: '65px', overflow: 'hidden', height: '80px', padding: '3px' }, 200); } , function() { $(this).css({'z-index' : '0'}); $(this).find('img').removeClass("hover").stop() .animate({ marginTop: '0', marginLeft: '0', top: '360px', left: '0', width: '60px', overflow: 'hidden', height: '60px', padding: '3px' }, 200); }); //Swap Image on Click $("ul.thumb li a").click(function() { var mainImage = $(this).attr("href"); //Find Image Name $("#main_view img").attr({ src: mainImage }); return false; }); }); </script> The CSS; <!--minSlide Show Styles --> * { padding: 0;} img {border: none;} .containerslide { margin-top: -71px; } ul.thumb {     float: left;     list-style: none outside none;     padding: 12px;     width: 360px; } ul.thumb { width: 360px; } ul.thumb li { padding: 3px; float: left; position: relative; width: 60px; height: 60px; } ul.thumb li img { width: 60px; height: 60px; border: 1px solid #ddd; padding: 3px; background: #f0f0f0; position: absolute; left: 0; -ms-interpolation-mode: bicubic; margin-top: 365px; } ul.thumb li img.hover { background:url(thumb_bg.png) no-repeat center center; border: none; } #main_view {     float: left;     margin-left: -217px;     margin-top: 41px;     padding: 9px 0; } <!-- End Slide Show Styles --> A: I see an unnecessary a tag here, <div id="main_view"> <img src="img/appimg_1.jpg" alt="" /></a><br /> </div> What is this doing there. Maybe this is creating an issue and disturbing the whole script, please post a fiddle, if issue still persists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delphi case statement for integer ranges I have a function which is being passed an integer value, representing a step value. There are 5 seperate conditions I want to test for: Value =0 Value =1 Value =-1 Value >1 Value <-1 Currently this is implemented as a set of if statements, and I would like to change this for a case statement. I have no problems with the specific value cases, or even a limited range (say 1..10) but how do i write a case representing Value >1 , or Value <-1? A: var MyValue: integer; ... case MyValue of Low(Integer)..-2: beep; -1: beep; 0: beep; +1: beep; 2..High(Integer): beep; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7628446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I fix a Thread Leak in a JSF application? I have an ApplicationScoped bean that fires up a separate Thread to do some background work. The Thread has a method for cleanly terminating it called terminate(). If not terminated via that method it runs in an infinite loop, and sleeps for a while if it finds it has nothing to do. The thing is I am in development mode (Netbeans -> Maven) and each time I recompile the application, the Maven plug-in un-deploys and redeploys the application (most conveniently I must say) but the background Thread from the last deployment hangs around. It eventually terminates with an Exception because it wakes up from its sleep and tries to access a JPA EntityManager that isn't there anymore. I would prefer to automatically call the terminate() method when the application is stopped. Is there some way to implement a listener that will do that at the JSF 2.0 specification level? If not, how about at the Servlet level? This is using GlassFish 3.1.1. A: Add a @PreDestroy method to you bean which will run when your application is undeployed or stopped and it can stop the background thread, like this: import javax.annotation.PreDestroy; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; @ApplicationScoped @ManagedBean public class AppBean { public AppBean() { System.out.println("new AppBean()"); } @PreDestroy public void preDestory() { // call thread.terminate() here System.out.println("preDestory"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does boost::crc_32_type generate any exceptions? Assuming that BufferLenght is >=0 and *Buffer is a valid buffer will the following code generate exceptions? What about if Buffer is invalid? Are there any cases where it can generate exceptions and how to handle them? unsigned CRC32(const void *Buffer, unsigned BufferLength) { boost::crc_32_type result; result.process_bytes(Buffer, BufferLength); return result.checksum(); } A: Boost CRC looks to be exception neutral. * *no exceptions are documented *no exceptions are thrown from crc.hpp
{ "language": "en", "url": "https://stackoverflow.com/questions/7628451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook PHP SDK get access token using php I am using the following code to post to Facebook: require('facebook.php'); $fb = new Facebook(array('appId' => 'MY APP ID','secret' => 'MY APP SECRET','cookie' => true)); $result = false; $feed_dir = '/401868882779/feed/'; //to the UID you want to send to $acToken = "MY ACCESS TOKEN"; $url = 'URL'; $link = $url . 'event.php?id=' . $id; if (isset($picture)) { $picture = $url . 'uploads/' . $picture; } else { $picture = $url . 'images/blank100x70.png'; } $msg_body = array('access_token' => $acToken,'name' => $noe_unsecured,'message' => $link,'link' => $link,'description' => $description_unsecured,'picture' => $picture); try { $result = $fb->api($feed_dir, 'post', $msg_body); } catch (Exception $e) { $err_str = $e->getMessage(); } but I need to update the access token manually every time it changes. I am sure there's solution but I cant find it.. I tried lots of scripts and nothing worked. A: Depending on when you perform the wall post, you might need to request the offline_access permission. This will convert your access_token into a format that does not expire so there would be no need to refresh the token. A: It is possible. Check: http://developers.facebook.com/docs/reference/php/facebook-setAccessToken/ A: A simple solution...remove the access_token! You simply don't need it as long as you got the publish_stream permission! A: I believe there are multiple methods to do this: - you can use the method already provided in the PHP SDK getAccessToken which returns the current access token being used by the sdk instance, more info at this url. - However you need not use an access token to call the api() method, once you ask the user for the publish_stream permission, as already mentioned by @ifaour. Hence you can do something like this example, scroll to the subheading Post a link to a User's wall using the Graph API. - Then, you have another three options i) either get a new access token using the method here, if you are posting when the user is currently using your app, otherwise you can try the next 2 options ii) get offline access iii) i'm not sure of this, but you might want to try with an app access token which can be obtained this way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rolling apply to subset of a vector I want to apply a function to progressive subsets of a vector in R. I have looked at what i could find, and the apply and friends aren't quite there, and rollapply does not work on straight vectors, only zoo/ts objects. vapply <- function(x, n, FUN=sd) { v <- c(rep(NA, length(x))) for (i in n:length(x) ) { v[i] <- FUN(x[(i-n+1):i]) } return(v) } Is there something built in that is equivalent? Is there a better way to do it? I am trying to avoid dependencies on 3rd party libraries as I the code needs to be standalone for distribution. A: With your choice of function name, I just HAD to make a version that actually uses vapply internally :) ...it turns out to be about 50% faster in the example below. But that of course depends a lot on how much work is done in FUN... # Your original version - renamed... slideapply.org <- function(x, n, FUN=sd) { v <- c(rep(NA, length(x))) for (i in n:length(x) ) { v[i] <- FUN(x[(i-n+1):i]) } return(v) } slideapply <- function(x, n, FUN=sd, result=numeric(1)) { stopifnot(length(x) >= n) FUN <- match.fun(FUN) nm1 <- n-1L y <- vapply(n:length(x), function(i) FUN(x[(i-nm1):i]), result) c(rep(NA, nm1), y) # Why do you want NA in the first entries? } x <- 1:2e5+0 # A double vector... system.time( a <- slideapply.org(x, 50, sum) ) # 1.25 seconds system.time( b <- slideapply(x, 50, sum) ) # 0.80 seconds identical(a, b) # TRUE
{ "language": "en", "url": "https://stackoverflow.com/questions/7628463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Efficiency of Google Geocoding with Dispatch Queue - How to Improve - iPhone I have a Google Map view in my app which is populated with pins via geocoding. I am using the below code to create a dispatch queue which then queries Google for the longitude and latitude for each place in my app. The problem is that although the below code works to some extent, it seems to miss a large percentage of items on its first run through. These items are added to the array "failedLoad" as per the code below. At the moment I am running a second method to add the places in failedLoad which is called whenever the ViewDidLoad method is called. However this is a poor solution as even after this second method is run there are still items in failedLoad and also I would prefer for all the pins to load without relying on ViewDidLoad (which is only called if the user taps on a pin, then returns from the detail view screen which is presented). Can anyone suggest a good way of improving this process ? Thank you -(void)displayPlaces { for (PlaceObject *info in mapLocations) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^ { // GET ANNOTATION INFOS NSString * addressOne = info.addressOne; NSString * name = info.name; NSString * postCode = info.postCode; NSString * addressTwo = [addressOne stringByAppendingString:@",London,"]; NSString * address = [addressTwo stringByAppendingString:postCode]; NSError * error; NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString ] encoding:NSASCIIStringEncoding error:&error]; NSArray *listItems = [locationString componentsSeparatedByString:@","]; double latitude = 0.0; double longitude = 0.0; if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) { latitude = [[listItems objectAtIndex:2] doubleValue]; longitude = [[listItems objectAtIndex:3] doubleValue]; } else { NSLog(@"Error %@",name); [failedLoad addObject : info]; } CLLocationCoordinate2D coordinate; coordinate.latitude = latitude; coordinate.longitude = longitude; MyLocation *annotation = [[[MyLocation alloc] initWithName:name address:address coordinate:coordinate] autorelease]; dispatch_sync(dispatch_get_main_queue(), ^{ // ADD ANNOTATION [mapViewLink addAnnotation:annotation]; }); }); } A: GCD is great but you should never use threading techniques if the SDK already offers an asynchronous API for this. In your case, never use stringWithContentsOfURL: as it is a synchronous & blocking code (which is probably why you switch to using GCD to make it in the background) while NSURLConnection has an asynchronous API. always use this asynchrounous API instead when you need to do any network request. This is better for many reasons: * *one being that it's an API already designed for this in the SDK (even if you will probably need to create a class like MyGeocoder that sends the request, handle the response, parse it, and return the value in an asynchronous way) *but the most significant reason to prefer the asynchronous API (over using the synchronous stringWithContentsOfURL + GCD) is that NSURLConnection is integrated with the NSRunLoop and schedules the retrieval of the socket data on the runloop, avoiding to create a lot of useless threads for that (and threads are evil if you use it where it is not strictly needed). *And finally, as NSURLConnection lifecycle is handled by the RunLoop itself, the delegate methods are already called on the main thread. GCD is always better than using NSThreads directly, but using Runloop scheduling for things that are already made for in the SDK, especially NSURLConnections is always better both for performance (avoid thread scheduling issues), multithreading issues and much more. [EDIT] For example if you don't want to implement the class yourself, you can use my sample OHURLLoader class and use it this way: NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSURL* url = [NSURL URLWithString:urlString]; NSURLRequest* req = [NSURLRequest requestWithURL:url]; OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req]; [loader startRequestWithCompletion:^(NSData* receivedData, NSInteger httpStatusCode) { NSString* locationString = loader.receivedString; NSArray *listItems = [locationString componentsSeparatedByString:@","]; ... etc ... // this callback / block is executed on the main thread so no problem to write this here [mapViewLink addAnnotation:annotation]; } errorHandler:^(NSError *error) { NSLog(@"Error while downloading %@: %@",url,error); }];
{ "language": "en", "url": "https://stackoverflow.com/questions/7628464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pyQt v4 rowsMoved Signal Im pretty new to Qt and have been trying to create a UI where the user will have rows of information and each row represents a stage in a pipeline. Iam trying to achieve that a user can drag and drop the different rows and that will change the order in which the steps occur. I have achieved the drag and drop of the rows using : self.tableView.verticalHeader().setMovable(True) Iam now trying to get the Signal"rowsMoved" to work but cant seem to get it to work in my custom model and delegate. If anyone knows of a way to get this working or of a way to not use this Signla and use another signal to track which row has moved and where it is now moved to. It will be a great help! :) Thanks everyone CODE BELOW class pipelineModel( QAbstractTableModel ): def __init_( self ): super( pipelineModel, self ).__init__() self.stages = [] # Sets up the population of information in the Model def data( self, index, role=Qt.DisplayRole ): if (not index.isValid() or not (0 <= index.row() < len(self.stages) ) ): return QVariant() column = index.column() stage = self.stages[ index.row() ] # Retrieves the object from the list using the row count. if role == Qt.DisplayRole: # If the role is a display role, setup the display information in each cell for the stage that has just been retrieved if column == NAME: return QVariant(stage.name) if column == ID: return QVariant(stage.id) if column == PREV: return QVariant(stage.prev) if column == NEXT: return QVariant(stage.next) if column == TYPE: return QVariant(stage.assetType) if column == DEPARTMENT: return QVariant(stage.depID) if column == EXPORT: return QVariant(stage.export) if column == PREFIX: return QVariant(stage.prefix) if column == DELETE: return QVariant(stage.delete) elif role == Qt.TextAlignmentRole: pass elif role == Qt.TextColorRole: pass elif role == Qt.BackgroundColorRole: pass return QVariant() # Sets up the header information for the table def headerData( self, section, orientation, role = Qt.DisplayRole ): if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return QVariant( int(Qt.AlignLeft|Qt.AlignVCenter)) return QVariant( int(Qt.AlignRight|Qt.AlignVCenter)) if role != Qt.DisplayRole: return QVariant() if orientation == Qt.Horizontal: # If Orientation is horizontal then we populate the headings if section == ID: return QVariant("ID") elif section == PREV: return QVariant("Previouse") elif section == NEXT: return QVariant("Next") elif section == NAME: return QVariant("Name") elif section == TYPE: return QVariant("Type") elif section == DEPARTMENT: return QVariant("Department") elif section == EXPORT: return QVariant("Export Model") elif section == PREFIX: return QVariant("Prefix") elif section == DELETE: return QVariant("Delete") return QVariant( int( section + 1 ) ) # Creates the Numbers Down the Vertical Side # Sets up the amount of Rows they are def rowCount( self, index = QModelIndex() ): count = 0 try: count = len( self.stages ) except: pass return count # Sets up the amount of columns they are def columnCount( self, index = QModelIndex() ): return 9 def rowsMoved( self, row, oldIndex, newIndex ): print 'ASDASDSA' # ---------MAIN AREA--------- class pipeline( QDialog ): def __init__(self, parent = None): super(pipeline, self).__init__(parent) self.stages = self.getDBinfo() # gets the stages from the DB and return them as a list of objects tableLabel = QLabel("Testing Table - Custom Model + Custom Delegate") self.tableView = QTableView() # Creates a Table View (for now we are using the default one and not creating our own) self.tableDelegate = pipelineDelegate() self.tableModel = pipelineModel() tableLabel.setBuddy( self.tableView ) self.tableView.setModel( self.tableModel ) # self.tableView.setItemDelegate( self.tableDelegate ) layout = QVBoxLayout() layout.addWidget(self.tableView) self.setLayout(layout) self.tableView.verticalHeader().setMovable(True) self.connect(self.tableModel, SIGNAL("rowsMoved( )"), self.MovedRow) # trying to setup an on moved signal, need to check threw the available slots # self.connect(self.tableModel, SIGNAL(" rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex ,int)"), self.MovedRow) # trying to setup an on moved signal, need to check threw the available slots A: What you want is to subclass the QTableView, and overload the rowMoved() SLOT class MyTableView(QtGui.QTableView): def __init__(self, parent=None): super(MyTableView, self).__init__(parent) self.rowsMoved.connect(self.movedRowsSlot) def rowMoved(self, row, oldIndex, newIndex): # do something with these or super(MyTableView, self).rowMoved(row, oldIndex, newIndex) def movedRowsSlot(self, *args): print "Moved rows!", args Edited To show both overloading rowMoved slot, and using rowsMoved signal A: Note: Components connected to this signal use it to adapt to changes in the model's dimensions. It can only be emitted by the QAbstractItemModel implementation, and cannot be explicitly emitted in subclass code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove all whitespaces from NSString I've been trying to get rid of the white spaces in an NSString, but none of the methods I've tried worked. I have "this is a test" and I want to get "thisisatest". I've used whitespaceCharacterSet, which is supposed to eliminate the white spaces. NSString *search = [searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; but I kept getting the same string with spaces. Any ideas? A: This may help you if you are experiencing \u00a0 in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it. NSString* yourString = [yourString stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""]; When yourString was the current phone number. A: stringByReplacingOccurrencesOfString will replace all white space with in the string non only the starting and end Use [YourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] A: This for me is the best way SWIFT let myString = " ciao \n ciao " var finalString = myString as NSString for character in myString{ if character == " "{ finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "") }else{ finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "") } } println(finalString) and the result is : ciaociao But the trick is this! extension String { var NoWhiteSpace : String { var miaStringa = self as NSString if miaStringa.containsString(" "){ miaStringa = miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "") } return miaStringa as String } } let myString = "Ciao Ciao Ciao".NoWhiteSpace //CiaoCiaoCiao A: - (NSString *)removeWhitespaces { return [[self componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""]; } A: I prefer using regex like this: NSString *myString = @"this is a test"; NSString *myNewString = [myString stringByReplacingOccurrencesOfString:@"\\s" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [myStringlength])]; //myNewString will be @"thisisatest" You can make yourself a category on NSString to make life even easier: - (NSString *) removeAllWhitespace { return [self stringByReplacingOccurrencesOfString:@"\\s" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [self length])]; } Here is a unit test method on it too: - (void) testRemoveAllWhitespace { NSString *testResult = nil; NSArray *testStringsArray = @[@"" ,@" " ,@" basicTest " ,@" another Test \n" ,@"a b c d e f g" ,@"\n\tA\t\t \t \nB \f C \t ,d,\ve F\r\r\r" ,@" landscape, portrait, ,,,up_side-down ;asdf; lkjfasdf0qi4jr0213 ua;;;;af!@@##$$ %^^ & * * ()+ + " ]; NSArray *expectedResultsArray = @[@"" ,@"" ,@"basicTest" ,@"anotherTest" ,@"abcdefg" ,@"ABC,d,eF" ,@"landscape,portrait,,,,up_side-down;asdf;lkjfasdf0qi4jr0213ua;;;;af!@@##$$%^^&**()++" ]; for (int i=0; i < [testStringsArray count]; i++) { testResult = [testStringsArray[i] removeAllWhitespace]; STAssertTrue([testResult isEqualToString:expectedResultsArray[i]], @"Expected: \"%@\" to become: \"%@\", but result was \"%@\"", testStringsArray[i], expectedResultsArray[i], testResult); } } A: stringByTrimmingCharactersInSet only removes characters from the beginning and the end of the string, not the ones in the middle. 1) If you need to remove only a given character (say the space character) from your string, use: [yourString stringByReplacingOccurrencesOfString:@" " withString:@""] 2) If you really need to remove a set of characters (namely not only the space character, but any whitespace character like space, tab, unbreakable space, etc), you could split your string using the whitespaceCharacterSet then joining the words again in one string: NSArray* words = [yourString componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString* nospacestring = [words componentsJoinedByString:@""]; Note that this last solution has the advantage of handling every whitespace character and not only spaces, but is a bit less efficient that the stringByReplacingOccurrencesOfString:withString:. So if you really only need to remove the space character and are sure you won't have any other whitespace character than the plain space char, use the first method. A: That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""]; It will replace empty space with no space and empty field is taken care of by below method: searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; A: Easy task using stringByReplacingOccurrencesOfString NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""]; A: Use below marco and remove the space. #define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] in other file call TRIM : NSString *strEmail; strEmail = TRIM(@" this is the test."); May it will help you... A: pStrTemp = [pStrTemp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; A: I strongly suggest placing this somewhere in your project: extension String { func trim() -> String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } func trim(withSet: NSCharacterSet) -> String { return self.stringByTrimmingCharactersInSet(withSet) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7628470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: How to limit the content of XML feeds I save in an array? Is there any way to still make use of all the feeds but instead of loading all the 25 posts of every feed (<entry></entry> or <item></item>), to get the first 10 posts of every feed. $feeds = array('',''); //a looot of inputs $entries = array(); foreach ($feeds as $feed) { $xml = simplexml_load_file($feed); $xml->registerXPathNamespace('f', 'http://www.w3.org/2005/Atom'); $entries = array_merge($entries, $xml->xpath('/f:feed/f:entry | /rss/channel//item')); } A: Try this: $entries = array(); foreach ($feeds as $feed) { $xml = simplexml_load_file($feed); $xml->registerXPathNamespace('f', 'http://www.w3.org/2005/Atom'); $entries = array_merge($entries, $xml->xpath('/f:feed/f:entry[position() <= 10] | /rss/channel//item[position() <= 10]') ); } This uses position().
{ "language": "en", "url": "https://stackoverflow.com/questions/7628472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to profile a C++ function at assembly level? I have a function that is the bottleneck of my program. It requires no access to memory and requires only calculation. It is the inner loop and called many times so any small gains to this function is big wins for my program. I come from a background in optimizing SPU code on the PS3 where you take a SPU program and run it through a pipeline analyzer where you can put each assembly statement in its own column and you minimize the amount of cycles the function takes. Then you overlay loops so you can minimized pipeline dependencies even more. With that program and a list of all the cycles each assembly instruction takes I could optimize much better then the compiler ever could. On a different platform it had events I could register (cache misses, cycles, etc.) and I could run the function and track CPU events. That was pretty nice as well. Now I'm doing a hobby project on Windows using Visual Studio C++ 2010 w/ a Core i7 Intel processor. I don't have the money to justify paying the large cost of VTune. My question: How do I profile a function at the assembly level for an Intel processor on Windows? I want to compile, view disassembly, get performance metrics, adjust my code and repeat. A: There are some great free tools available, mainly AMD's CodeAnalyst (from my experiences on my i7 vs my phenom II, its a bit handicapped on the Intel processor cause it doesn't have access to the direct hardware specific counters, though that might have been bad config). However, a lesser know tool is the Intel Architecture Code Analyser (which is free like CodeAnalyst), which is similar to the spu tool you described, as it details latency, throughput and port pressure (basically the request dispatches to the ALU's, MMU and the like) line by line for your programs assembly. Stan Melax gave a nice talk on it and x86 optimization at this years GDC, under the title "hotspots, flops and uops: to-the-metal cpu optimization". Intel also has a few more tools in the same vein as IACA, avaibale under the performance tuning section of their experimental/what-if code site, such as PTU, which is (or was) an experimental evolution of VTune, from what I can see, its free. Its also a good idea to have read the intel optimization manual before diving into this. EDIT: as Ben pointed out, the timings might not be correct for older processors, but that can be easily made up for using Agner Fog's Optimization manuals, which also contain many other gems. A: You might want to try some of the utilities included in valgrind like callgrind or cachegrind. Callgrind can do profiling and dump assembly. And kcachegrind is a nice GUI, and will show the dumps including assembly and number of hits per instruction etc. A: From you description it sounds like you problem may be embarrassingly parallel, have you considered using ppl's parallel_for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7628476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Best practise for displaying multiple controls which require an extended class? If I want to display a MapView inside my Activity I would have to extend my Class from MapActivity. If I want to display a Tabbed interface I would have to extend my Class from TabActivity. Similar is the case with some other controls which require user class to extend from a specific class. Let's say inside my Activity I want to display both a MapView for displaying Google Map and a TabView to display some other data. I can't do it directly because Java doesn't support multiple inheritance. My question is how can I achieve this scenario? How can I display multiple controls inside my activity where each require your class to extend from a specific class. Is it possible first of all? If yes, what are the best practises to achieve this scenario? Update I want to achieve this I am using Map and Tab for sake of an example. I would like to know how you can tackle this scenario in general? A: You could build it via object composition. Initially I am not sure how to get the Activity started and add it to the layout, but then I found out about LocalActivityManager which allow you to embed other Activity as your view. Note that this class is deprecated since API Level 11. In any case here are the steps to embed other Activity that require extension as a View: * *Create a LocalActivityManager to enable creation of Activity within Activity *Start the activity that you want to embed and get the View via getDecorView() *Add the View in your layout The following is my test code that I tried within my Activity @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create local activity manager so that I could start my activity LocalActivityManager localActivityManager = new LocalActivityManager(this, true); // dispatch the onCreate from this manager localActivityManager.dispatchCreate(savedInstanceState); // layout to hold the activity, optionally this could be set through XML file LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); this.addContentView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); // start the activity which is in this example is an extension of a TabActivity Intent tabIntent = new Intent(this, DummyTabActivity.class); Window tabWindow = localActivityManager.startActivity("tabView", tabIntent); View tabView = tabWindow.getDecorView(); // start the activity that extends MapActivity Intent mapIntent = new Intent(this, DummyMapView.class); Window mapViewWindow = localActivityManager.startActivity("mapView", mapIntent); View mapView = mapViewWindow.getDecorView(); // dispatch resume to the Activities localActivityManager.dispatchResume(); // add to the tabView, optionally you could use other layout as well layout.addView(tabView); // add to the mapView, optionally you could use other layout as well layout.addView(mapView); } My limited experiments show that object composition via the above method will achieve what you are trying to do. Having said that, I am not sure how common this approach is. Without your question, I wouldn't probably look for the above method, but your use case is interesting and might be applicable for future use. I will look into Fragment and see if I could do the same with it and update my answer if it is applicable. A: In this case it's simple: You can use the MapActivity within the TabActivity (it's designed to manage activities as tabs). As general approach I always prefer to use views and nest them in an activity. I never use such things like ListActivity. They should make things easier but often look like a bad design decision to me. I never faced the fact that I had to combine two activities (expect TabActivity). You can take a look at this question. It seems that activities never meant to be used that way. I think the situation which you describe is the reason why fragments where introduced.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the POSIX c99 utility usually implemented as on Linux systems? I am curious what the POSIX c99 utility is usually implemented as in GNU/Linux distributions. I realize that this is really a question that should be answered by each distribution's documentation, but both the manpage on my openSUSE 11.4 install and Ubuntu's manpage basically just list similar information as the POSIX standard, without specifying what the compiler actually is (i.e., is it GCC, Clang or something else). So does anyone know what the common practice is? My guess would be that it is a wraper for gcc with the -std=c99 option, perhaps with -pedantic added to conform more closely with the C99 standard. A: Usually, it's indeed a wrapper for gcc -std=c99, though it might select a compiler based on the environment variable CC. You can check for yourself by doing file /usr/bin/c99 and reading it if it's a shell script, or checking where it points to if it's a symlink.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Paged list and CursorLoader I need to implement paged list, that uses Loader to get Cursor from ContentProvider. I have footer and when user clicks it - I need to add next records to list. How can I refresh data in the list, using Loader? Or what should I do here? A: I think you should read this article about Loaders in Android first, to get a better understanding of how Loaders can be used in Android. You can even find LoaderCursor example with source codes under Android ApiDemos section in this article.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: boost::variant single storage guarantee My goal is to guarantee single storage on all my variant types: according to 'never empty' guarantee from Boost::variant, we need to override boost::has_nothrow_copy for each bounded type. But a bit later the documentation mentions something about 'boost::blank' and if that type is bound, variant will set that value rather than try to nothrow default copy constructors. what is not clear is if adding boost::blank in the bounded type list will avoid the requirement of overriding/specializing has_nothrow_copy with the other types? A: I believe that is made clear. Here is the relevant section from the boost documentation: Accordingly, variant is designed to enable the following optimizations once the following criteria on its bounded types are met: For each bounded type T that is nothrow copy-constructible (as indicated by boost::has_nothrow_copy), the library guarantees variant will use only single storage and in-place construction for T. If any bounded type is nothrow default-constructible (as indicated by boost::has_nothrow_constructor), the library guarantees variant will use only single storage and in-place construction for every bounded type in the variant. Note, however, that in the event of assignment failure, an unspecified nothrow default-constructible bounded type will be default-constructed in the left-hand side operand so as to preserve the never-empty guarantee. Since boost::blank is nothrow default constructible, the second clause applies. And it sounds like Boost has special-cased this particular type to be chosen in favor of all others, so that instead of it being unspecified which default constructible type will be instantiated the type is guaranteed to be boost::blank if that's an option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7628498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: save the screen change history in lightswitch app is there any easy way to track what is changed on a lightswitch app screen? i have a form that shows information about a customer (listdetail). When I save it, i want to write to a history table what was changed. A: found the answer here. Just use the following code in the _updating, _inserting events for the controls. Private Sub Employees_Updating(entity As Employee) Dim change = entity.EmployeeChanges.AddNew() change.ChangeType = "Updated" change.Employee = entity change.Updated = Now() change.ChangedBy = Me.Application.User.FullName Dim newvals = "New Values:" Dim oldvals = "Original Values:" For Each prop In entity.Details.Properties.All(). OfType(Of Microsoft.LightSwitch.Details.IEntityStorageProperty)() If prop.Name <> "Id" Then If Not Object.Equals(prop.Value, prop.OriginalValue) Then oldvals += String.Format("{0}{1}: {2}", vbCrLf, prop.Name, prop.OriginalValue) newvals += String.Format("{0}{1}: {2}", vbCrLf, prop.Name, prop.Value) End If End If Next change.OriginalValues = oldvals change.NewValues = newvals End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7628499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }