text
stringlengths
8
267k
meta
dict
Q: Sending images from gallery to Web Service using SOAP I have trawled the net and can't find any documentation on sending images (or any attachments) to a Web Service using SOAP. I have been sending text data fine but I now need to send images from the gallery along with the text data, which poses another problem - making two or more async tasks at once. I will need to make 4 calls in total IF the record to send has an image affiliated with it; * *Send the text data. *Check if the file already exists on the server. *Send the file. *Link the file with a record on the server using a u_id sent back from the server. I was advised to use a Base64 method to convert the file to a String then send it but I have a feeling theres a cleaner way of doing it using SOAP (no pun intended). Any feedback greatly appreciated. * Please note that I was using a httpClient but had to change to using SOAP also I'm relatively new to Android so forgive me if I've said anything stupid here. A: There are three ways of sending attachments with SOAP. * *base64Binary *SwA - SOAP with Attachments *MTOM base64Binary sends the attachments as base64 inline in the SOAP message. i.e. The Attachment in embedded in the SOAP Message. Bloats the message by 33%. SWA sends the Attachment outside the SOAP message (The SOAP message contains a reference to the attachment). But the SOAP infoset does not contain the attachment. MTOM Provides the best of both world. The Attachment is sent outside the SOAP message with a reference to it but the attachment appears as if it is embedded in the SOAP message (The SOAP infoset contains the attachment) Due to the fact that attachments sent using MTOM appear as it the attachment is part of the SOAP message it allows you to use other WS-* QOS (Quality of Service) attributes. For e.g MTOM messages can be signed and encrypted using WS-Security. Thus this provides a mechanism to send Secured Attachments without the need for additional specs. This example shows how to use MTOM with Apache AXIS2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to remove a blank line after removing an unwanted line in perl? For example, I want to remove unwanted line with bbbb aaaa bbbb cccc dddd I use the following perl regular expression to accomplish this. $_ =~ s/bbbb//g; The problem here is that a blank line is stays, for example aaaa cccc dddd I need to remove the unwanted text line and also the blank line. A: You could simply include the newline in your regular expression: $_ =~ s/bbbb\n//g; This will result in: aaaa cccc dddd A: It seems to me that if you are reading this line by line you could just have your loop do this: my @foo = ( "aaaa\n", "bbbb\n", "cccc\n", "dddd\n" ); foreach my $line ( @foo ) { next if ( $line =~ /^bbbb$/ ); # now do something with a valid line; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP DomDocument removing an element scrambles HTML I am having issues removing a node using PHP DomDocument. I have some HTML like so: <!DOCTYPE HTML "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Test</title> <script id="fr21" type="text/javascript" src="jquery.min.js"></script> </head> <body> </body> </html> I attempt to remove the script node like so: $jquery_node = $doc->getElementById('fr21'); $head_node = $jquery_node->parentNode; $head_node->removeChild($jquery_node); I then try to view the HTML by echo: echo $doc->saveHTML().'<br><br>'; The HTML then becomes this: <!DOCTYPE HTML> <html> <body><p>-//W3C//DTD HTML 4.0 Transitional//EN"&gt;</p> <body> </body> </html> What just happened? The HTML has been mangled? Am I not removing the node correctly? The weird thing is when I calculate the xPath for the jquery node it is shown as if its attached to the body node rather than the head node? /html[1]/body[1]/script[1] A: try this: $script_0 = $doc->getElementsByTagName('script')->item(0); $doc->removeChild($script_0); A: If you look at the errors, you will see that it says: Warning: DOMDocument::loadHTML(): DOCTYPE improperly terminated in Entity, line: 1 Change the DOCTYPE to read <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> and it will work as expected: demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7545355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use regular expression to extract bit in middle of a string Using PHP PCRE regular expressions I want to extract the centre part of a string where the parts either side may or may not occur. I.e. n bedroom property type in some town I want to extract 'property type' using one regular expression. I do not know all the possibilities for property type but what is consistent is the start bit (its always '\d bedroom') and the end bit (its always 'in some town'). Also, either the start or end bits (or both) may not be present. I.e. the subject strings could be one of ... 6 bedroom ground floor flat in Edinburgh house in Manchester 3 bedroom apartment So want to extract 'ground floor flat', 'house', and 'apartment' respectively. Something like this (which doesn't quite work).... (\s*\d+\s+bedrooms?\s*)?(.*?)(\s+in)? A: Add anchors to your regex and declare first ant last group to be not captured: /^(?:\s*\d+\s+bedrooms?\s*)?(.*?)(?:\s+in\s.*)?$/ A: This #(((?<bedroomCount>\d+)\s+bedroom)\s+)?(?<type>.+?)\s(in\s+(?<city>\w+))?\n#i works I think but you need an extra newline ad the end of the testing string. An example here
{ "language": "en", "url": "https://stackoverflow.com/questions/7545357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: multiple amount of asynchronous calls to web service in Silverlight, bind response to request I want to send multiple asynchronous calls to different web services with silverlight and be able to match the responses to each request. Lets say i have a list with n items in it. Every item represents a string URL of a web service. So you may have 2 services, but you also may have 7. Now, i have a GUI and when i press a button, the list with the URLs is iterated and to every service a request is sent. You do not know how many services you might call, so it has to be dynamic. I have solved the sending part, and i get all the responses, BUT with my solution there is no way to figure out which response refers to which request. private void startCall(object sender, RoutedEventArgs e) { var urls = {"http://this.is.the.first/service1", "http://this.is.thesecond/service2", "http://this.is.thethirt/service3"}; foreach (var item in urls) { WebClient wc = new WebClient(); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.DownloadStringAsync(new Uri(item)); } void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { list_ResponseFromServer.Add(e.Result.ToString()); } } In this example i have 3 services/items in the list. And i also get 3 responses to the handler void wc_DownloadStringCompleted, but i do not know in what order. Its obvious i want to have ListRequest(A,B,C,D,E) ListResponse(A,B,C,D,E) but i do not know if response A takes much longer than response B,C so I might get in my ListResponse(B,C,D,A,E) => what is FAIL I have seen some examples with 2 asynchronous calls, but they were all hardcoded. For every request, response they had several hardcoded methods/handlers. It would be great if someone could help me to solve this problem with a variable amount of multiple asynchronous calls to different webServices A: One approach would be to use a delegate to create a capture like this:- private void startCall(object sender, RoutedEventArgs e) { var urls = {"http://this.is.the.first/service1", "http://this.is.thesecond/service2", "http://this.is.thethirt/service3"}; foreach string item in urls) { Uri uri = new Uri(item); WebClient wc = new WebClient(); wc.DownloadStringCompleted += (s, args) => { if (args.Error == null) { // You can use the uri variable to determine which Uri this is a response to. // NOTE: don't use item variable here. list_ResponseFromServer.Add(args.Result); } }; wc.DownloadStringAsync(new Uri(item)); } } Edit: Response to comments By one means or another you need a way to corelate a response to the orignating request. The Silverlight API offers no built in mechanism to do that, there is no standard solution. So yes you need to write your own code to relate an asynchronous response to the originating Url if that is important to you. If you prefer to use the original string url then add another string variable inside the foreach code block and assign item to it. What it sounds like you are looking for is away to guarantee the order that the responses arrive in to match the order they are generated. The only way to do that is to issue each request only when the previous response has arrived. Whilst that is possible (I've written a series of blogs on the subject), I wouldn't recommend it as solution in this case. A: You can pass a custom object to DownloadStringAsync, so I change a little Anthony code: var urls = {"http://this.is.the.first/service1", "http://this.is.thesecond/service2", "http://this.is.thethirt/service3"}; var i = 0; var maxRequests = urls.Length; Dictionary<int, string> dict = new Dictionary<int,string>(); foreach (string item in urls) { WebClient wc = new WebClient(); wc.DownloadStringCompleted += (s, args) => { if (args.Error == null) { //add the the caller "id" and the response dict.Add((int)args.UserState, args.Result); } //here you test if it is the last request... if it is, you can //order the list and use it as you want if (dict.Count == maxRequests) { var orderedResults = dict.OrderBy(a => a.Key); } }; wc.DownloadStringAsync(new Uri(item), i++); } } A: for (int i = 0; i < urls.Count; i++) { if (uri.AbsoluteUri.ToString().Equals(urls[i])) { list_ResponseFromServer.RemoveAt(i); list_ResponseFromServer.Insert(i, args.Result); } } that was my fast hack how to bring responses into same order like the requests. If everything is unique you could use "break;" too
{ "language": "en", "url": "https://stackoverflow.com/questions/7545364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does this code segfault on 64-bit architecture but work fine on 32-bit? I came across the following C puzzle: Q: Why does the following program segfault on IA-64, but work fine on IA-32? int main() { int* p; p = (int*)malloc(sizeof(int)); *p = 10; return 0; } I know that the size of int on a 64 bit machine may not be the same as the size of a pointer (int could be 32 bits and pointer could be 64 bits). But I am not sure how this relates to the above program. Any ideas? A: Most likely because you're not including the header file for malloc and, while the compiler would normally warn you of this, the fact that you're explicitly casting the return value means you're telling it you know what you're doing. That means the compiler expects an int to be returned from malloc which it then casts to a pointer. If they're different sizes, that's going to cause you grief. This is why you never cast the malloc return in C. The void* that it returns will be implicitly converted to a pointer of the correct type (unless you haven't included the header in which case it probably would have warned you of the potentially unsafe int-to-pointer conversion). A: The cast to int* masks the fact that without the proper #include the return type of malloc is assumed to be int. IA-64 happens to have sizeof(int) < sizeof(int*) which makes this problem obvious. (Note also that because of the undefined behaviour it could still fail even on a platform where sizeof(int)==sizeof(int*) holds true, for example if the calling convention used different registers for returning pointers than integers) The comp.lang.c FAQ has an entry discussing why casting the return from malloc is never needed and potentially bad. A: This is why you never compile without warnings about missing prototypes. This is why you never cast the malloc return in C. The cast is needed for C++ compatibility. There is little reason (read: no reason here) to omit it. C++ compatibility is not always needed, and in a few cases not possible at all, but in most cases it is very easily achieved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: CodeIgniter word_wrap and I code So, I have this problem that when I word_wrap the text field. But when I word_wrapped, it didn't get the </i> so, it ended up with whole website got italic text. <?php echo word_limiter($news_item['text'], 10); ?> How do I fix that? ... Now i just realized that every tag HTML (i begin, but not end) I do, does still work? I just use the XSS fixer... Shouldn't it fix this as well? And more importantly how do I fix this, but I still want to allow clean HTML. (But they have to close the tag!!!!) > <John13> Hello [14:13] <John13> When I use the xss clean (function) It > doesn't prevent tags that ain't closed. How do I fix it? [14:14] > <John13> For example <b>blablabla.... (end of post) Now all rest of > text will be bold on the site. A: strip_tags() - "strip_tags — Strip HTML and PHP tags from a string" So try this <?php echo word_limiter(strip_tags($news_item['text']), 10); ?> EDIT: How to close unclosed HTML Tags?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is this script safe enough from sql injections? Is this script safe enough from sql injections? Or is it possible to improve it more efficiently? Because i am going to use it in public and don't know about this line "mysql_real_escape_string($_GET['user_id']);" Perhaps its possible to improve it more. <? $id = mysql_real_escape_string($_GET['id']); if ($id == 1) { $userinfo['user_id'] = mysql_real_escape_string($_GET['user_id']); $info = $db->fetchArray("SELECT points FROM ". PREFIX ."list WHERE user_id = '{$userinfo['user_id']}'"); if (!empty($info)) { $user_rank = UserRank($userinfo['user_id']); header('Content-type: image/png'); $points = $info['server_points']; $line = "empty"; $nr = "Number"; $font = 3; $font2 = 2; $width = ImageFontWidth($font)* strlen($nr) ; $width2 = ImageFontWidth($font)* strlen($points); $height = ImageFontHeight($font); $im = ImageCreateFrompng(SYS_USER .'/banner.png'); $points_text_color = imagecolorallocate($im, 225, 100, 112); $nr_text_color = imagecolorallocate ($im, 217, 153, 101); $line_color = imagecolorallocate ($im, 100, 123, 134); imagestring ($im, $font, 40, 18, $points, $points_text_color); imagestring ($im, $font2, 40, 11, $line, $line_color); imagestring ($im, $font2, 40, 4, $nr, $nr_text_color); imagestring ($im, $font, 60, 4, $user_rank, $nr_text_color); imagepng($im); } } A: for $id use function is_numeric(): if(is_numeric($id)) { // if id not numeric -> false else -> true ... } A: I would seriously consider using bind_param when interacting with sql variables. Your code is such a good example of strings coming from many different places which could possibly have been jeopardized. bind_param enforces that there are no injection attacks in the strings you pass in. If for anything, itll at least give you enough peace of mind not to worry so much to ask this question. Example: $name = "Robert ') DROP TABLE Students;"; //see: http://xkcd.com/327/ $conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database.'); $query = "SELECT id FROM Users WHERE name=?"; if ($stmt = $conn->prepare($query)) { $stmt->bind_param('s', $name); $stmt->execute(); $stmt->bind_result($result); while ($stmt->fetch()) { echo $result; } $stmt->close(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Why there is no error raised by compiler? I just found my compiler allowed me to write below code and did not raised any compile time error. Could anyone please enlighten me! double y = arcToFindPointOn.getCenterXY().y - arcToFindPointOn.getRadius()*Math.sin(theta);; Weird thing about above code line is semi-colon at the very end! Thanks! A: in other languages as well, like C# and C++, having an instruction with only ; means empty instruction and is allowed, generates no errors and simply does nothing. plenty of articles on this online, found this one: Multiple semicolons are allowed by the C# Compiler for statement termination This is a little weirdness inherited from C. In fact your example isn't a statement terminated by three semicolons, but three statements, two of which are empty. Occassionally it can be useful to use the empty statement in e.g. an if statement or a while loop, and then it would seem arbitrary to disallow it elsewhere. Besides, changing it now would be an unnecessary breaking change. A: Java also allows for the empty statement: ; which actually does nothing at all. In your example you just have one at the very end. A: The ";" is a delimiter, so the compiler can safely ignore the blank statement. However some IDEs help you optimize code and will not let you get away with this statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when using JDBC Driver- java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver I am trying to use the Microsoft SQL Server 2008 Type 4 JDBC Driver in a java desktop application. However when I run the program I get the following error-- java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver How do I overcome this error? The code looks to be OK as it is...Its a single sql statement to be executed into local sql server 2008 database. A: Make sure that the .jar containing this driver is in your CLASSPATH. Here's an article explaining how to setup this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting a string representation of a template parameter I want to be able to create a method in a templated class that returns the name of the type subsituted in the template parameter. eg: template <typename T> class CPropertyValueT { std::string GetTypeName() { return #T; } } This is possible with a preprocessor macro using #, I figured there must be a way with templates. Is this possible? A: You can use typeid(T).name(), though it will return decorated name of the type. If you're using GCC, then you can use GCC API, declared incxxabi.h header, to demangle the names. Here is an example (source): #include <exception> #include <iostream> #include <cxxabi.h> struct empty { }; template <typename T, int N> struct bar { }; int main() { int status; char *realname; // exception classes not in <stdexcept>, thrown by the implementation // instead of the user std::bad_exception e; realname = abi::__cxa_demangle(e.what(), 0, 0, &status); std::cout << e.what() << "\t=> " << realname << "\t: " << status << '\n'; free(realname); // typeid bar<empty,17> u; const std::type_info &ti = typeid(u); realname = abi::__cxa_demangle(ti.name(), 0, 0, &status); std::cout << ti.name() << "\t=> " << realname << "\t: " << status << '\n'; free(realname); return 0; } Output: St13bad_exception => std::bad_exception : 0 3barI5emptyLi17EE => bar<empty, 17> : 0 Another interesting link that describe demangling in GCC and Microsoft VC++: * *C++ Name Mangling/Demangling
{ "language": "en", "url": "https://stackoverflow.com/questions/7545377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How Does Case 5 executed in this Switch statement? I have a following code(which is taken from a C book): #include<stdio.h> int main( ) { int k=4,j=0; switch(k) { case 3: j=300; case 4: j=400; case 5: j=500; } printf("%d",j); } When i run the above code, I get output as 500, but I expected it to be 400, can anyone why it is been printed 500 rather than 400? (I am novice in C and I couldn't figure out what is the error in it!) A: You need to break; at the end of a case block. #include <stdio.h> int main() { int k = 4, j = 0; switch(k) { case 3: j = 300; break; case 4: j = 400; break; case 5: j=500; break; } printf("%d\n", j); } A: You need to break out of your cases otherwise it will run trough other cases: int main( ) { int k=4,j=0; switch(k) { case 3: j=300; break; case 4: j=400; break; case 5: j=500; break; } printf("%d",j); } So in your case it did execute j=400 and then went to case 5: and execute j=500 A: There's no break statement after case 4, so execution "falls through" to case 5.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Undefined symbols for armv7 on iOS 5: _aes_icm_advance_ismacryp I have one app I built with Xcode 4.2 for iOS 4.3, and I want to build it on Xcode 4.2 + iOS 5 beta 7 for Snow Leopard but I get the error below: Apple Mach-O Linker (Id) Error Undefined symbols for architecture armv7 "_aes_icm_advance_ismacryp", referenced from: I have one class contain the method aes_icm_advance_ismacryp. The architecture setting on iOS 4.3 was i386 so I tried to change it to i386 but Xcode won't let me. I tried this answer but didn't solve my problem. A: What do your build settings display for their architectures? It should look something like this (My screenshot is from Xcode 5 so it will not be exact): If you have nested project dependencies, you'll have to check those targets as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python class inheriting multiprocessing, trouble with accessing class members In short, say I have the following: import multiprocessing class Worker(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) print "Init" self.value = None def run(self): print "Running" self.value = 1 p = Worker() p.start() p.join() print p.value I'd expect the output to be: Init Running 1 Instead it is Init Running None Can someone explain to me why this is the case? What am I not understanding, and how should I go about doing it correctly? Thanks. A: The moment you say p.start(), a separate process is forked off of the main process. All variable values are copied. So the main process has one copy of p, and the forked process has a separate copy of p. The Worker modifies the forked process's copy of p.value, but the main process's p.value still is None. There are many ways to share objects between processes. In this case, perhaps the easiest way is to use a mp.Value: import multiprocessing as mp class Worker(mp.Process): def __init__(self): print "Init" mp.Process.__init__(self) self.num = mp.Value('d', 0.0) def run(self): print "Running" self.num.value = 1 p = Worker() p.start() p.join() print p.num.value Note that the mp.Value has a default value of 0.0. It can not be set to None.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to use 2 php handlers on one server? I am new to apache, PHP on linux. I have a server with PHP handler set as "CGI" I mean in phpinfo page where it says "SERVER API". Now I have to install new script on server and the script requires PHP handler as "APACHE 2 HANDLER" i.e. DSO if i am not wrong. There are scripts/live sites already running on the server. I am worried as what if after I change my server PHP handler from CGI to APACHE 2 HANDLER, my previously installed sites will have any bad effect in the matter of permissions issue or some other errors. I would like to know whether is this possible to use "CGI" and "APACHE 2 HANDLER" on single server ? if yes then how to ? thanks for your time, have a great day ahead
{ "language": "en", "url": "https://stackoverflow.com/questions/7545386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AudioServicesCreateSystemSoundID not playing mp3 files Can anyone answer how to play mp3 files using AudioServicesCreateSystemSoundID()? I tried but not working. I have used the following code snippet for playing mp3 NSURL *soundURL = [[NSBundle mainBundle] URLForResource:fileName withExtension:extension]; soundFileURLRef = (CFURLRef) [soundURL retain]; // Create a system sound object representing the sound file. AudioServicesCreateSystemSoundID ( soundFileURLRef,&soundFileObject); A: I had the same problem using this example. Maybe your sound sample is to big/long. NSString *path = [[NSBundle mainBundle] pathForResource:@"tap" ofType:@"aif"]; NSURL *url = [NSURL fileURLWithPath:path];AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &mBeep); AudioServicesPlaySystemSound(mBeep); It was not working because the audio file was to long. I tried with the sound from the apple example http://developer.apple.com/library/ios/#samplecode/SysSound/Introduction/Intro.html "tap.aif" and it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Improve SQL query using functions I am trying to improve query readability by using a function in SQL Server Express 2008. Here is a sample of what I'm trying to do. I have a table where we store a max temperatures reading per hour of the day, then I want to select all days where the max temperature between 8-10AM was greater than the max temp between 12-2PM So here is how it's like: DECLARE @TableA TABLE ([Date] DATE, [Time] TIME(0), HighTemp DECIMAL(6,2)); INSERT @TableA VALUES ('2011-09-10','08:00:00',38.15), ('2011-09-10','09:00:00',38.32), ('2011-09-10','10:00:00',38.17), ('2011-09-10','11:00:00',38.10), ('2011-09-10','12:00:00',38.05), ('2011-09-10','13:00:00',38.15), ('2011-09-10','14:00:00',38.30), ('2011-09-11','08:00:00',38.12), ('2011-09-11','09:00:00',38.09), ('2011-09-11','10:00:00',38.07), ('2011-09-11','11:00:00',38.15), ('2011-09-11','12:00:00',38.13), ('2011-09-11','13:00:00',38.11), ('2011-09-11','14:00:00',38.10), ('2011-09-12','08:00:00',38.30), ('2011-09-12','09:00:00',38.33), ('2011-09-12','10:00:00',38.35), ('2011-09-12','11:00:00',38.30), ('2011-09-12','12:00:00',38.25), ('2011-09-12','13:00:00',38.23), ('2011-09-12','14:00:00',38.20) select distinct [DATE] from @TableA maintbl where -- Select the high temp between 08:00:00-10:00:00 (select MAX(HighTemp) from @TableA tmptbl where tmptbl.Time >= '08:00:00' and tmptbl.Time <= '10:00:00' and maintbl.Date = tmptbl.Date) > -- Select the high between 12:00:00-14:00:00 (select MAX(HighTemp) from @TableA tmptbl where tmptbl.Time >= '12:00:00' and tmptbl.Time <= '14:00:00' and maintbl.Date = tmptbl.Date) The query runs well (fast) and the result for the above query should be: 2011-09-10 2011-09-12 Now, I have tried to simplify the query by using a function that retrieves the max tempreture in a certain day and time period, so the query is easier to read, like so: select distinct [DATE] from @TableA maintbl where GetPeriodHigh(maintbl.Date, '08:00:00', '10:00:00') > GetPeriodHigh(maintbl.Date, '12:00:00', '14:00:00') And the function is like so: CREATE FUNCTION [dbo].[GetPeriodHigh] ( @Date date, @From time, @To time ) RETURNS decimal(6,2) AS BEGIN declare @res decimal(6,2) select @res = MAX(high) from MyTable where Time >= @from and Time <= @to and Date = @Date return @res END The problem is that running the query using the function takes LOOONG time, actually I never saw it finishes, looks like it is in some sort of infinite loop... Any ideas why is that, and there is anything I can do to simplify my query? Thx. A: Scalar functions that do data access generally suck and are best avoided. They don't get expanded out by the optimiser and this basically enforces the function query as being the inner side of a nested loops join regardless of suitability. Making things worse you may well not have correct indexing to evaluate the Time >= @from and Time <= @to and Date = @Date predicate inside the function which means that for each row in the outer query you are enforcing 2 table scans via the function calls. This lack of indexes is also the case in your source example and it can be seen with the inline version that the query optimiser is able to effectively rewrite this as two MAX / GROUP BY queries with different WHERE clauses then merge join the results together. When the logic is in scalar UDFs this kind of transformation is not currently considered. Another approach you could try is SELECT [Date] FROM @TableA WHERE Time BETWEEN '08:00:00' AND '10:00:00' OR Time BETWEEN '12:00:00' AND '14:00:00' GROUP BY [Date] HAVING MAX(CASE WHEN Time BETWEEN '08:00:00' AND '10:00:00' THEN HighTemp END) > MAX(CASE WHEN Time BETWEEN '12:00:00' AND '14:00:00' THEN HighTemp END) A: To improve performance, try rewriting the scalar valued UDF as an inline table valued UDF. Some links : http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/05/23/reuse-your-code-with-cross-apply.aspx http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/04/21/not-all-udfs-are-bad-for-performance.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7545409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Buffer caache usage for symbolic link on linux when we create a symbolic link to a different file then an inode is used to store the filepath to the original file. So in this context if we create a symbolic link towards a large size file which is already in buffer cache then reading from symbolic link will find the file in buffer cache or not? A: Yes when the file is opened it will resolve the symlink and open the file it points to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to escape html? Im using jQuery Markitup to allow users to input html... So they can input stuff like: <h1>Foo</h1> <p>Foobar</p> However, I was watching http://railscasts.com/episodes/204-xss-protection-in-rails-3 and decided to try this piece of code into the input: <script>alert('test');</script> To my amazement, when I submitted the form and refreshed the page, the alert box came out. This is a security risk! This is what I have in my view: <div><%= comment.description.html_safe %></div> The above renders any html, but is also prone to xss. So I tried: <div><%= html_safe(comment.description).html_safe %></div> But the above does not render any html. It actually displays the html as text, which is not the desired behavior. I need to render the html and at the same time protect myself from xss. How do I go about this? A: Try <%= sanitize(comment.description) %> Update: To remove ALL tags use strip_tags
{ "language": "en", "url": "https://stackoverflow.com/questions/7545411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: size of array in c a simple question that bugs me. Say I have an array defined in main like so int arr[5]. Now, if I'm still inside main and I set int i = sizeof(arr)/sizeof(arr[0]) then I is set to be 5, but if I pass the array as a function parameter and do the exact same calculation in this function, I get a different number. Why is that? At first I thought its because in a function arr is a pointer, but as far as I know arr is a pointer inside main too! Also, if I do something very similar only I initialize the array dynamically, I get weird results: int *arr = (int*) malloc(sizeof(int) * 5); int length = sizeof(*arr) / sizeof(arr[0]); printf("%d\n",length); Here the output is 1. Any ideas why? Thanks in advance! A: This is because arr is now a pointer and it could point to a single int or an array of 1000 ints the function just does not know. You will have to pass the size of the array into the function. In main arr is declared as an int[5] and so the size can be calculated by the compiler. A: I didn't understand the first question (post some code, please), but for the second: sizeof(*arr) ; // is sizeof(int) as arr is of type "int *" sizeof(arr[0]) ; // is sizeof(int), as arr[0] is the first // item of an array of int Fact is, *arr and arr[0] mean exactly the same thing, but said differently. In fact, let say n is an index: *(arr + n) is the same than arr[n]. A: as far as I know arr is a pointer inside main too! That's the mistake. In main, where you defined int arr[5], arr is an array, not a pointer. Its size is equal to the size of the array, so 5*sizeof(int). When you passed it as a function parameter, that parameter had type int*, so inside the function, you were taking the size of an int* rather than an int[5]. Here the output is 1. Any ideas why? This time, arr really is a pointer, since you declared it int *arr. But either way, whether it's int *arr or int a[5], *arr and arr[0] mean exactly the same thing: the first element. So of course they have the same size, and sizeof(*arr) / sizeof(arr[0]) is 1. A: It's because of the difference between an array of known size and a pointer to an array of unknown size. sizeof is done at compile time and it's not possible for the compiler to tell the size of a dynamically created memory region in advance. A: You should understand the difference between static and dynamic arrays. Static arrays are types like int, float, double etc. They are different. Even int a[10]; has a different type from int b[11]; At compile time, the number of elements in static arrays are known and the sizeof operator returns the number of bytes they occupy. With pointers that were initialized, either to point to some variable, or to an allocated memory, it is at run-time that it would be apparent where they are pointing to and the compiler cannot determine what would be the size of that array in the future. Therefore, the sizeof a pointer gives you 4 (or 8 in 64bits systems for example). Note that sizeof operator works at compile-time and not at run-time. If you need to know the size of an allocated memory (through malloc), you have no choice but to save the size of the array in another variable, for example right after you did the malloc. A: C arrays don't store their own sizes anywhere, so sizeof only works the way you expect if the size is known at compile time. malloc() is treated by the compiler as any other function, so sizeof can't tell that arr points to the first element of an array, let alone how big it is. If you need to know the size of the array, you need to explicitly pass it to your function, either as a separate argument, or by using a struct containing a pointer to your array and its size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Strange error message when a class method is missing Possible Duplicate: GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()' I have been banging my head against a wall for a long time because of a strange ld error. So I reproduced it in a small test case to understand the issue. I declared a class and I derived another one in a header file: class BaseClass { public: BaseClass(){}; virtual void func(){}; }; class DerivedClass: public BaseClass { public: DerivedClass(); void func(); }; Then I defined the constructor but forgot to define func (voluntary here, but that actually what I did with a silly copy/paste...): DerivedClass::DerivedClass(){ cout << "Derived constructor" << endl; } //void DerivedClass::func(){ // cout << "Derived func" << endl; //} Then I get: undefined reference to `vtable for DerivedClass' Edit: And the message points the declaration of the consctructor! If I uncomment the definition of func, then I have no error. So my question: Why does the linker didn't tell me that the definition of func is missing? The solution might be obvious when you are experienced, but for a beginner like me it's not! Thanks for your help. A: vtable is created for the class that contains virtual function and for the classes derived from it.It means in your program vtable will be created for BaseClass and DerivedClass.Each of these vtables would contain the address of virtual function void func().Now note that DerivedClass doesn't contain the definition of void func(),hence its vtable contains the address of BaseClass's void func() function.That's why the compiler is giving error undefined reference to vtable for DerivedClass. A: It seems your compiler didn't generate a vtable for the DerivedClass. A vtable is basically a table that contains function pointers for every virtual function. By storing a pointer to the class's vtable (usually called vptr) for every object the correct virtual function to call can be determined at runtime. Although it is an implementation detail of the specific compiler, this is the usual way to implement virtual functions, which are bound at runtime and can therefore not be called like normal functions. My first guess would be that the compiler didn't generate a vtable for DerivedClass because it doesn't define any virtual functions so it uses the BaseClass's vtable. Although that's a bit strange, it is the only idea I can come up with. But I'm not that well-versed in compiler architecture and maybe somebody has a better solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing the hashing function on a pre-existing database I'm doing a bit of reading on hashing for passwords. I've seen that SHA-256 > MD5. This got me thinking about how an app may deal with changing from one hashing function to another. What happens if someone implements an app that hashes their passwords using MD5. They then decide that SHA-256 is the way to go. But of course the password hashes stored in the database are in MD5. What is the process for migrating the data in the database from one hashing function to another? A: It is not possible to "unhash" passwords (at least not in a general, efficient and reliable way -- you can guess some passwords, that's what attackers do, and you want to migrate from MD5 precisely because attackers may have some success at it). So the migration will be spread over time: some passwords will be hashed with MD5, other with SHA-256. When a password is to be verified: * *If the SHA-256 of that password is known, SHA-256 is used. This password is already migrated. *Otherwise, MD5 is used to check the password. If it matches, then the password is good, and, since the password is known by the app at that time, the app also hashes the password with SHA-256 and replaces the MD5 hash with the SHA-256 hash in the database. Thus, passwords are migrated dynamically; to get totally rid of MD5, you have to wait a long time and/or destroy accounts which have not been accessed for a long time. You need to be able to distinguish a MD5 hash from a SHA-256 hash, which is easy since they have distinct sizes (16 bytes for MD5, 32 bytes for SHA-256). YOu could also add a flag or any other similar gimmick. Please note that hashing passwords with a raw single application of a hash function is a pretty lousy way of doing it, security-wise, and replacing MD5 with SHA-256 will not really improve things. You hash passwords so that an attacker who gains read access to the database will not learn the passwords themselves. To really prevent the attacker from guessing the passwords, you also need "salts" (per-password random data, stored alongside the hashed password) and a suitably slow hash function (i.e. thousands, possibly millions, of nested hash function invocations). See this answer for details. The short answer: since you are envisioning migration, do the smart thing and migrate to bcrypt, not SHA-256 (see that answer on security.stackexchange).
{ "language": "en", "url": "https://stackoverflow.com/questions/7545431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using sprite images with setDragImage I'm trying to implement HTML5 Drag and Drop with a custom drag image, which appears behind the cursor. This can be done with setDragImage and works great with standalone images, i.e. created with new Image. However, to improve page loading speed, I'd like to combine those images into one image, using sprites and the background-position trick. To implement sprites for use in setDragImage of the drag and drop functionality, the fact that elements can be used as a drag image comes in handy: create a <div>, set its size and background image and position, and pass that div to setDragImage. However, it appears that those images must be visible in the DOM. It looks like a "screenshot" of the element is made when you call setDragImage with a DOM element, and when the element is either hidden or not part of the DOM, the screenshot is empty, and as a result no image is shown when dragging. Please have a look at this fiddle. Dragging the two text divs works fine with the drag image. However, after clicking the button to hide the image divs, dragging the text divs does not make the drag image show up anymore. I only need to have this working on Google Chrome. How can I use sprite images with HTML5 Drag and Drop (setDragImage) while the divs containing the sprites as background images are hidden or not in the DOM? Or, is there another technique of using sprites with setDragImage? A: If i was you i'd drop the sprite and use inline base64 encoded images. If all you wish to do is increase page load speed and skip the request overhead, then it should work just as fine, and you problem should be solved :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Thread interference with each other in their execution (using Handler) in Android In my App code I've extended the Button view (say it as DigiButton ) and overridden the onDraw() method. In onDraw() method I am setting the button text to some counter value. This counter value is decremented by 1 for every 500 ms by the Handler object (I am using Handler.run() method to update the counter value). Now I've created two instances of "DigiButton" with different initial values of counter in "DigiComponent" class. "DigiComponent" has a button whose onClick event starts running both the threads. I see some delay in the counter value update(on both the instances). I thought that each of the thread is interfering with the other thread execution. To confirm this I just started running only one "DigiButton" instance. Then the counter value got updated correct. Below is my code: class DigiButton extends Button{ private int counter; private Runnable handleRunnable; DigiButton(Context context,int val){ super(context); counter = val; initialize(); } private void initialize(int val){ digiHandler = new Handler(); handleRunnable = new Runnable(){ public void run(){ } }; } private void updateCounter(){ counter++; if(counter>0){ runCounter(); } } public void runCounter(){ digiHandler.postDelayed(handleRunnable, 500); } @Override protected void onDraw(Canvas canvas){ super.onDraw(canvas); setText(counter); } } public class DigiComponent extends Activity implements OnClickListener{ DigiButton thread1, thread2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); thread1 = new DigiButton(this,30000); thread2 = new DigitButton(this,20000); Button test = new Button(this); LinearLayout layout = new LinearLayout(this); layout.addView(thread1); layout.addView(thread2); layout.addView(test); test.setClickListener(this); setContentView(layout); } public void onClick(View v){ thread1.runCounter(); thread2.runCounter(); } } Is that my guess of thread execution interference is correct? If so how to avoid this? Is it something wrong with my thread handling code? Note: This delay in counter value update is worse when I press "Home" button to go out of the App and I open the App again. A: These are not separate threads. These are Runnables scheduled to run on the main UI thread. It gets worse when you press home because you are adding more and more Runnables to the queue (that reschedule themselves). You should look into AsyncTasks with the use of AsyncTask.publishProgress or just use a basic Thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Measuring Java method refactoring performance I was given a weird task. I have to refactor certain methods in a huge code base (the easy part) and provide performance gain reports. I should focus on speed of execution and memory usage. They want know the performance improvement by method! So I have a method like this: public void processHugeFile(File f) { long start = java.lang.System.currentTimeMillis(); // lots of hashmaps, lots of arrays, weird logic,... long end = java.lang.System.currentTimeMillis(); logger.log("performance comparison - exec time: " + (end - start)); } Then I have to refactor it: public void processHugeFile(File f) { long start = java.lang.System.currentTimeMillis(); // just lists, some primitives, simple logic,... long end = java.lang.System.currentTimeMillis(); logger.log("performance comparison - exec time: " + (end - start)); } In the end I just have to process the logs. But what about memory usage? I have tried getRuntime().totalMemory() - getRuntime().freeMemory() and the getHeapMemoryUsage().getUsed() but they don't seem to work. Also, JVM Profilers focus on objects not on methods and I am speaking of a fairly large code base. Can someone provide me some hints? Thank you very much. A: Broadly, refactoring is not a means to increase performance, but to improve readability and maintainability of a code base. (Which may then help you make optimizations and architectural changes with more confidence and ease.) I assume you're aware of this, and you mean that you're trying to clean up some slow code in the process. This is really a tool for a profiler, not for hand-instrumentation. You will never get precise measurements this way. For example, System.currentTimeMillis() calls add their own overhead and for short-lived methods could take longer than the method itself. Runtime can only help you get a crude picture of memory usage. I don't agree that profilers can't help. JProfiler for instance will happily graph heap size over time, include generation sizes. It will break down memory usage by allocation site, object type. It will show you performance bottlenecks by inclusive/exclusive time. And all of this without touching your code. You really, really want to use a profiler like JProfiler, not hand-coded stuff. A: You could use a profiler but also of use would be enabling Garbage Collection logging and then analysing the GC logs after you program has run. This will tell you how much memory was being used AND how much time was being spent doing Garbage Collection which is more useful than just knowing how much memory was used - for example if you notice any excessive GC or stop the world collections that affect throughput & latency requirements. A: Use profiler!!! Results may be distorted if you are doing it this way. If you are using for example Netbeans, it has built-in profiler. A: I'm puzzled by this requirement. I agree with Sean that refactoring is done for design reasons rather than performance reasons. There is no a priori reason to expect any performance increase in general, and if there is enough doubt about the benefits maybe it shouldn't be done at all. And maybe you should do an algorithmic analysis instead: this is easy enough most of the time, which gives you an a analytic result in Big-O terms: if there isn't a clearly visible advantage in Big-O then there probably isn't much of a performance advantage at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OData Linq problem I've created an application that exposes a self-hosted OData web service. The web service exposes a collection of objects named "Main". Each of these Main objects has a reference to a releated "Details" object, which is very large (many properties, nearly a hundred). I now use LinqPad to test my web service, which seems to work fine. Often I need information from both the "Main"-collection and the related "Details" object. This can be accomplished by running the following linq query: from m in Main.Expand( "Details" ) where m.ID==57 select m This correspons to the url: "http://MachineName:port/ServiceName/Main()?$filter=ID eq 57&$expand=Details" This query works fine and returns the full Main object and the full related Details object. However, the Details object is very large, and often I only need the value of a single single property from both of the objects. Manually, I can construct a url that gives me exacly that: "http://MachineName/ServiceName/Main()?filter=ID eq 57&$expand=Details&$select=Property1,Details/Property2" which returns xml containing only the value of Main.Property1 and the value of the related Details.Property2. Question: Why can't I create a linq query that does just that? When I try something like: from m in Main.Expand( "Details" ) where m.ID == 57 select new{ m.Property1, m.Details.Property2 } it gives me the an error message: "NotSupportedException: Cannot create projection while there is an explicit expansion specified on the same query." I have now given up using Linq to construct the query. But knowing the corrct url like above, how can i use that url directly in code (C# client) and how do I then access the result? A: Doesn't just from m in Main where m.ID == 57 select new { m.Property1, m.Details.Property2 } work for you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating Animated Launch Image I was wondering how one could create an animated launch image when the user opens up an iPhone app as opposed to using a simple Default.png I would like to make a small animation appear when the user opens the app. An example of this, is the Jamie Oliver app - the launch screen is animated and I have was wondering how this is done? A: A possibility is to set the first view as an identical full screen animating UIView (identical to the launch image), so that the transition is not perceived. This view can be removed after a couple of seconds or so. A: iPhone don't display animating image but there are one way that you have motion on splash or... As you know the gif file contain the number of images that play without stop, so For doing this in iphone you need png format of all scenes and display them on imageview, UIImageView have animationImages that you should add array of images name and animation duration and ... for set up this. splashImageView = [[UIImageView alloc] init]; NSMutableArray *splashImageArray = [[NSMutableArray alloc] initWithCapacity:IMAGE_COUNT]; // Build array of images, cycling through image names for (int i = IMAGE_COUNT; i > 0 ; i-=2) [splashImageArray addObject: [UIImage imageNamed: [NSString stringWithFormat:@"splash_000%d.png", i] ] ]; splashImageView.animationImages = [NSArray arrayWithArray:splashImageArray]; // One cycle through all the images takes 1.5 seconds splashImageView.animationDuration = 3.50; // Repeat forever splashImageView.animationRepeatCount = 1; splashImageView.startAnimating; splashImageView.frame = CGRectMake(0, 20, 320, 460); [window addSubview:splashImageView];
{ "language": "en", "url": "https://stackoverflow.com/questions/7545448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert .vsd file to .vdx How can I convert Visio binary file (.vsd extension) to Visio xml file(.vdx extension) in programming? Does Microsoft provide such C/C++ library ? A: Option 1: Use Visio application programmatically Any .NET language can control Visio through it's COM automation interfaces and use its SaveAs method. $visio = New-Object -ComObject Visio.InvisibleApp; $visio.Documents.Open(".\Drawing.vsd"); $visio.Documents.SaveAs(".\Drawing.vdx"); $visio.Quit(); SaveAs method on MSDN This option, obviously requires the Visio application to be installed. Option 2: Use a third party library I've never used it but apparently Aspose.Diagram for .NET can be used to convert these files. Microsoft Library? To answer your last question: No, Microsoft does not provide a C/C++ library to perform this conversion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: HTML file fetched using 'wget' reported as binary by 'less' If I use wget to download this page: wget http://www.aqr.com/ResearchDetails.htm -O page.html and then attempt to view the page in less, less reports the file as being a binary. less page.html "page.html" may be a binary file. See it anyway? These are the response headers: Accept-Ranges:bytes Cache-Control:private Content-Encoding:gzip Content-Length:8295 Content-Type:text/html Cteonnt-Length:44064 Date:Sun, 25 Sep 2011 12:15:53 GMT ETag:"c0859e4e785ecc1:6cd" Last-Modified:Fri, 19 Aug 2011 14:00:09 GMT Server:Microsoft-IIS/6.0 X-Powered-By:ASP.NET Opening the file in vim works fine. Any clues as to why less can not handle it? A: Because it is UTF-16 encoded as can be seen with the BOM of ff ee in the first two octets: $ od -x page.html | head -1 0000000 feff 003c 0021 0044 004f 0043 0054 0059 vim is smarter about it (because it is more Unicode era) than less. added: See Convert UTF-16 to UTF-8 under Windows and Linux, in C for what to do about it. Or use vim to write it back out with UTF-8 encoding. A: It's an UTF-16 encoded file. (Check with W3C Validator). You can convert it to UTF-8 with this command: wget http://www.aqr.com/ResearchDetails.htm -q -O - | iconv -f utf-16 -t utf-8 > page.html less usally knows UTF-8. edit: As @Stephen C reported, less in Red Hat supports UTF-16. It looks to me that Red Hat patched less for UTF-16 support. On the official site of the less UTF-16 support currently is an open issue (ref number 282). A: Firstly, it works for me. When I download the file using that file, I get a file that "less" shows me without any questions / problems. (I use RedHat Fedora 14.) Second, the "file" command reports "page.html" as: page.html: Little-endian UTF-16 Unicode HTML document text, with very long lines, with CRLF line terminators Maybe the UTF-16 encoding is the cause of the problems. (But why ... I don't know why it would work with my version of "less" and not yours.) @palacsint's solution works for me: wget http://www.aqr.com/ResearchDetails.htm -q -O - | \ iconv -f utf-16 -t utf-8 > page.html A: Very likely this HTML file contains UTF characters and your locale is not set correctly (export LANG=en_US.UTF8 LESSCHARSET=utf-8). It may also happen that HTML contains invalid characters. EDIT: After checking the file I clearly see it is UTF-16. So you need to correct your terminal settings correspondingly (although I was able to see the text correctly with UTF8 setting, perhaps my terminal program is smart).
{ "language": "en", "url": "https://stackoverflow.com/questions/7545459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Regex to check if a path go only down I want to test if a path given by the user go down like: my/down/path at the opposite of: this/path/../../go/up for security reasons. I already made this: return (bool)preg_match('#^([a-z0-9_-])+(\/[a-z0-9_-])*$#i', $fieldValue); But the user should be allowed to use the '.' in his path (like: my/./path, that not useful but he can) and I don't know how to consider it. I'm then looking for a secure regex to check this. Thanks edit: After viewing answers, yes it would be fine if the test check if the real path (removing '.' and '..') is a down path. A: You can simply check if the realpath of the user supplied path begins with the allowed path: function isBelowAllowedPath($allowedPath, $pathToCheck) { return strpos( realpath($allowedPath . DIRECTORY_SEPARATOR . $pathToCheck), realpath($allowedPath) ) === 0; } Demo on codepad Note that this will also return false for directories that do not exist below $allowedPath. A: You probably do not want to check that a path doesn't contain .. but instead want to check that if evaluated as whole, it doesn't go up. E.g. ./path/.. is still in ., even though it contains ... You can find an implementation of path depth validation in Twig: $parts = preg_split('#[\\\\/]+#', $name); $level = 0; foreach ($parts as $part) { if ('..' === $part) { --$level; } elseif ('.' !== $part) { ++$level; } if ($level < 0) { return false; } } return true; Twig does not use realpath for the validation, because realpath has issues with paths in Phar archives. Additionally realpath only works if the pathname already exists. A: The previous responses (including the accepted one) address path depth but not path traversal. Since the question specifically mentioned that this is for security, then casual checking such as that described so far may not be sufficient. For example, * *Do you care about traversing through hard or soft links below the current working directory? *Does the system you are on (or could potentially deploy to) support unicode? *How many things are evaluating the string in question before or after your PHP code sees it? The web server? The shell? Something else? Suppose I send your script a string like ./..%2f../? Is it important to your application that this string will take me up two levels? Or that the scripts provided in other answers will not catch this because it doesn't evaluate to ..? What about ./\.\./? If the path is parsed by splitting on both \ and / the script in the accepted answer won't catch it because each part will look like . which is simply the current directory. But a typical UNIX shell treats the \ as an escape character so passing it ./\.\./ is equivalent to ./../ and so the attacker can exploit the fact that the script combines tests for UNIX and Windows style paths. If by "security" you really mean you want to provide protection against casual mistakes and typos, then the other answers are probably sufficient. If you are programming for a hostile environment and want to prevent breaches from deliberate attacks then they barely scratch the surface and you would be well advised to go read up on secure programming at OWASP. I would start with their articles on Path Traversal and then read up on the other attacks they outline as well as how to avoid them and, more importantly, how to test for them. A: $folders = $explode('/', $path); if (in_array('..', $folders)) { print('Error: path contains ..'); } A: If you only want to restrict the user from going up in the path hierarchy, you can explicitly search for '..': if (1 === preg_match('/\.\./', $path)) { /* path contains .. */ } Which is also quicker than explode and in_array. Benchmarking: <?php $attempts = 100000; $path = 'my/path/with/../invalid'; $t = microtime(true); for ($i = 0; $i < $attempts; ++$i) { $folders = explode('/', $path); if (in_array('..', $folders)) { /* .. in path */ ; } } $end = microtime(true); printf("in_array: %f\n", $end - $t); $t = microtime(true); for ($i = 0; $i < $attempts; ++$i) { if (1 === preg_match('/\.\./', $path)) { /* .. in path */ ; } } $end = microtime(true); printf("preg_match: %f\n ", $end - $t); in_array: 0.088750 preg_match: 0.071547
{ "language": "en", "url": "https://stackoverflow.com/questions/7545468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Adding scroll bar in subplots within GUI How can I add scrollbar to the subplots? I have gone through many tutorials but they seem quite difficult to understand (ex: Scrolling Figure Demo) Any easier method to implement? My code looks like the following. It creates two figures ,one for multiple plots and one for subplots. For the case of subplots i wanted to have scroll bar so as i can slide it down. I dont know how to call this function, if i replace the call of addaxis to my function then how would the axis be readjusted without any call to addaxis function. function readfile while(1) q = cell(16,2); q{1,1}='1B000003AC63A328.txt'; % sensor 1 q{1,2} = 'sensor 1'; q{2,1}='D6000003ACA0AB28.txt';% sensor 2 q{2,2} = 'sensor 2'; q{3,1}='B0000003AC9B8428.txt'; % sensor 3 q{3,2} = 'sensor 3'; q{4,1}='5D000003AC5FEA28.txt';% sensor 4 q{4,2} = 'sensor 4'; q{5,1}='E1000003AC5DA728.txt';% sensor 5 q{5,2} = 'sensor 5'; q{6,1}='BE000003ACA4F828.txt';% sensor 6 q{6,2} = 'sensor 6'; q{7,1}='5F000003AC8C6128.txt';% sensor 7 q{7,2} = 'sensor 7'; q{8,1}='78000003AC77A328.txt'; q{8,2} = 'sensor 8'; % sensor 8 q{9,1}='B2000003AC542A28.txt';% sensor 9 q{9,2} = 'sensor 9'; q{10,1}='EB000003B717F328.txt';% sensor 10 q{10,2} = 'sensor 10'; q{11,1}='86000003AC97AC28.txt';% sensor 11 q{11,2} = 'sensor 11'; q{12,1}='78000003AC748828.txt';% sensor 12 q{12,2} = 'sensor 12'; q{13,1}='A5000003AC905C28.txt';% sensor 20 q{13,2} = 'sensor 20'; q{14,1}='B4000003ACA4A728.txt';% sensor 21 q{14,2} = 'sensor 21'; q{15,1}='14000003AC69A528.txt';% sensor 22 q{15,2} = 'sensor 22'; q{16,1}='99000003AC68F728.txt';% sensor 23 q{16,2} = 'sensor 23'; for j=1:16 fname=q{j}; fid=fopen(fname,'r'); header=fgetl(fid); data=textscan(fid,'%s','delimiter',';'); fclose(fid); data=data{:}; day=data(1:3:end); hour=data(2:3:end); temp=str2double(data(3:3:end)); time=cellfun(@(x) sprintf('%s %s',day{strcmpi(hour,x)},x),hour,'uniformoutput',0); % timev=datevec(time,'mm.dd.yyyy HH:MM:SS'); timen=datenum(time,'mm.dd.yyyy HH:MM:SS'); seconds=timen*86400/60; figure(1) subplot(5,4,j), h=plot(seconds-seconds(1),temp,'YDataSource','temp'); legend(h,q{j,2}); grid on xlabel('Time(mins)'); ylabel('Temp °C'); %subplot(1,1,i), figure(2) if(j==1) r=plot(seconds-seconds(1),temp); hold on set(r,'Color','blue','LineWidth',2) end if(j==2) r=plot(seconds-seconds(1),temp); set(r,'Color','green','LineWidth',2) end if(j==3) r=plot(seconds-seconds(1),temp); set(r,'Color','red','LineWidth',2) end if(j==4) r=plot(seconds-seconds(1),temp); set(r,'Color','cyan','LineWidth',2) end if(j==5) r=plot(seconds-seconds(1),temp); set(r,'Color','magenta','LineWidth',2) end if(j==6) r=plot(seconds-seconds(1),temp); set(r,'Color','yellow','LineWidth',2) end if(j==7) r=plot(seconds-seconds(1),temp); set(r,'Color','black','LineWidth',2) end if(j==8) r=plot(seconds-seconds(1),temp,'--'); set(r,'Color','blue','LineWidth',2) end if(j==9) r=plot(seconds-seconds(1),temp,'--'); set(r,'color','green','LineWidth',2) end if(j==10) r=plot(seconds-seconds(1),temp,'--'); set(r,'Color','red','LineWidth',2) end if(j==11) r=plot(seconds-seconds(1),temp,'--'); set(r,'Color','cyan','LineWidth',2) end if(j==12) r=plot(seconds-seconds(1),temp,'--'); hold on set(r,'Color','magenta','LineWidth',2) end if(j==13) r=plot(seconds-seconds(1),temp,'--'); set(r,'Color','yellow','LineWidth',2) end if(j==14) r=plot(seconds-seconds(1),temp,'--'); set(r,'Color','black','LineWidth',2) end if(j==15) r=plot(seconds-seconds(1),temp,'-.'); set(r,'Color','blue','LineWidth',2) end if(j==16) r=plot(seconds-seconds(1),temp,'-.'); set(r,'Color','green','LineWidth',2) end legend('Sensor 1','Sensor 2','Sensor 3','Sensor 4','Sensor 5','Sensor 6',... 'Sensor 7','Sensor 8','Sensor 9','Sensor 10','Sensor 11','Sensor 12','Sensor 20','Sensor 21','Sensor 22','Sensor 23','Location','BestOutside') end pause(2*60) end end A: I'm not sure what demo you are referring to, but let me explain how I would implement such a functionality. The idea is to create a large panel inside a figure, which will contain all the subplots. The panel would be larger than the figure in size. You will have to manually position the axes inside this panel. Also using a slider, you will have to maintain the position of the panel itself to control which part of it is visible. Consider the following example. We will create a figure such that we scroll vertically to see all the subplots. We start by creating a figure, and placing a panel and a slider components to fill the entire figure: %# create figure, panel, and slider w = 600; h = 500; %# width/height of figure handles.hFig = figure('Menubar','figure', 'Resize','off', ... 'Units','pixels', 'Position',[200 200 w h]); handles.hPan = uipanel('Parent',handles.hFig, ... 'Units','pixels', 'Position',[0 0 w-20 h]); handles.hSld = uicontrol('Parent',handles.hFig, ... 'Style','slider', 'Enable','off', ... 'Units','pixels', 'Position',[w-20 0 20 h], ... 'Min',0-eps, 'Max',0, 'Value',0, ... 'Callback',{@onSlide,handles.hPan}); For now the slider is disabled. Note that in order to keep things simple, I turned off figure resizing. That way we can position components in fixed pixel units. Next, we will create new axes one at a time, making each fill one view page. I placed that code inside a separate function addAxis for easy use. First let me show how we call this function: %# add and plot to axes one-by-one hAx = zeros(7,1); clr = lines(7); for i=1:7 hAx(i) = addAxis(handles); plot(hAx(i), cumsum(rand(100,1)-0.5), 'LineWidth',2, 'Color',clr(i,:)) title(hAx(i), sprintf('plot %d',i)) pause(1) %# slow down so that we can see the updates end The addAxis simply grows the container panel in size, creates an axis, position it on the top, adjusts the slider limits, then returns a handle to the newly created axis. function hAx = addAxis(handles) %# look for previous axes ax = findobj(handles.hPan, 'type','axes'); if isempty(ax) %# create first axis hAx = axes('Parent',handles.hPan, ... 'Units','normalized', 'Position',[0.13 0.11 0.775 0.815]); set(hAx, 'Units','pixels'); else %# get height of figure p = get(handles.hFig, 'Position'); h = p(4); %# increase panel height, and shift it to show new space p = get(handles.hPan, 'Position'); set(handles.hPan, 'Position',[p(1) p(2)-h p(3) p(4)+h]) %# compute position of new axis: append on top (y-shifted) p = get(ax, 'Position'); if iscell(p), p = cell2mat(p); end p = [p(1,1) max(p(:,2))+h p(1,3) p(1,4)]; %# create the new axis hAx = axes('Parent',handles.hPan, ... 'Units','pixels', 'Position',p); %# adjust slider, and call its callback function mx = get(handles.hSld, 'Max'); set(handles.hSld, 'Max',mx+h, 'Min',0, 'Enable','on') %#set(handles.hSld, 'Value',mx+h) %# scroll to new space hgfeval(get(handles.hSld,'Callback'), handles.hSld, []); end %# force GUI update drawnow end The slider callback function simply shifts the panel up and down according to the current value of the slider: function onSlide(hSld,ev,hPan) %# slider value offset = get(hSld,'Value'); %# update panel position p = get(hPan, 'Position'); %# panel current position set(hPan, 'Position',[p(1) -offset p(3) p(4)]) end The result of this example:
{ "language": "en", "url": "https://stackoverflow.com/questions/7545469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Perl form-mail script that is not working I have been given the task through school to institute a comments form on my website. I got all of what I thought would be the hard things done, but have now hit a major stumbling block. I was given a perl script called form-mail2 to put in the cgi-bin of my web server and did that, but when I click submit on my form, I get this: The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, webmaster@randyloope.com and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. This has to be related to the script, so I would like to reach out to you to help me. I was given the script in total so I'm guessing it isn't configured right, but I haven't the foggiest of how to configure it correctly. Here is the script: #!/usr/local/bin/perl # ------------------------------------------------------------ # Form-mail.pl, by Reuven M. Lerner (reuven@the-tech.mit.edu). # # Last updated: March 14, 1994 # # Form-mail provides a mechanism by which users of a World- # Wide Web browser may submit comments to the webmasters # (or anyone else) at a site. It should be compatible with # any CGI-compatible HTTP server. # # Please read the README file that came with this distribution # for further details. # ------------------------------------------------------------ # ------------------------------------------------------------ # This package is Copyright 1994 by The Tech. # Form-mail is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2, or (at your option) any # later version. # Form-mail is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # You should have received a copy of the GNU General Public License # along with Form-mail; see the file COPYING. If not, write to the Free # Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # ------------------------------------------------------------ # Define fairly-constants # This should match the mail program on your system. $mailprog = '/usr/lib/sendmail'; # This should be set to the username or alias that runs your # WWW server. $recipient = 'salvador.voli@gmail.com' if ($recipient eq "\@csprofessor.com") { $recipient = $ENV{'SERVER_ADMIN'}; } # Print out a content-type for HTTP/1.0 compatibility print "Content-type: text/html\n\n"; # Get the input read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); # Split the name-value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); # Un-Webify plus signs and %-encoding $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; # Stop people from using subshells to execute commands # Not a big deal when using sendmail, but very important # when using UCB mail (aka mailx). # $value =~ s/~!/ ~!/g; # Uncomment for debugging purposes # print "Setting $name to $value<P>"; $FORM{$name} = $value; } # If the comments are blank, then give a "blank form" response unless ($FORM{'realname'}) { &blank_response("name"); } unless ($FORM{'email'} ) { &blank_response("email"); } unless ($FORM{'message'} ) { &blank_response("message"); } unless ($FORM{'rating'} ) { &blank_response("rating"); } # Print a title and initial heading print "<html>\n"; print "<Head><Title>Thank you</Title></Head>"; print "<Body><H1>Thank you</H1>"; print "<p>Thank you for sending your comments!<br>"; print "</body></html>"; # Now send mail to $recipient open (MAIL, "|$mailprog $recipient") || die "Can't open $mailprog!\n"; print MAIL "To: sgifford\@csprofessor.com\n"; #print MAIL "To: $recipient\n"; print MAIL "From: $FORM{'email'} ($FORM{'realname'})\n"; print MAIL "Reply-to: $FORM{'email'} ($FORM{'realname'})\n"; print MAIL "Subject: Web Site Comments\n\n"; print MAIL "------------------------------------------------------------\n"; print MAIL "$FORM{'email'} ($FORM{'realname'}) Stopped by\n"; print MAIL "Phone: $FORM{'phone'}\n"; print MAIL "Birthday: $FORM{'bday'}\n"; print MAIL "------------------------------------------------------------\n"; print MAIL "And this is what $FORM{'realname'} had to say:\n\n"; print MAIL "$FORM{'message'}"; print MAIL "\n------------------------------------------------------------\n"; print MAIL "Web Site Rating: $FORM{'rating'}"; print MAIL "\n------------------------------------------------------------\n"; print MAIL "Server protocol: $ENV{'SERVER_PROTOCOL'}\n"; print MAIL "Remote host: $ENV{'REMOTE_HOST'}\n"; print MAIL "Remote IP address: $ENV{'REMOTE_ADDR'}\n"; print MAIL "------------------------------------------------------------\n"; close (MAIL); # Make the person feel good for writing to us # ------------------------------------------------------------ # subroutine blank_response sub blank_response { print "<html>\n"; print "<Head><Title>Incomplete Comment Form</Title></Head>"; print "<Body><H1>Incomplete Comment Form</H1>"; print "<p>"; print "The $_[0] field appears to be blank! "; print "Please finish filling out the form and re-submit your comments. "; print "</body></html>"; exit; } And here is the form part of my code: <form name="usercomments" action="/cgi-bin/form-mail2.pl" method="post" onsubmit="return finalCheck()"> Name: <input type="text" name="realname" onchange= "nameCheck()" value="" /><br /> email: <input type="text" name="email" onchange = "emailCheck()" value="" /><br /> phone: <input type="text" name="phone" onchange = "phoneCheck()" value="" /><br /> birthday: <input type="text" name="bday" onchange = "birthdayCheck()" value="" /><br /> How would you describe your experience today? <br/ > <input type="radio" name="rating" value="Awesome" checked="checked" /> Awesome<br /> <input type="radio" name="rating" value="Mediocre" /> Mediocre<br /> <input type="radio" name="rating" value="Terrible" /> Terrible<br /> Comments: <br /> <textarea name="message" rows="5" cols = "100" > </textarea><br /> <input type="submit" value="Submit" /> </form> Any suggestions you could give would be most appreciated. A: Perhaps the "last updated 1994" should have been a bit of a red flag? If you're going to do form-mail in Perl you should start with the NMS FormMail script which is well written and commented and almost certainly way more secure than the script you have. But yes, look at your server error logs. A: I wrote that form-mail program, back in 1993. (I updated it somewhat over the subsequent year, as the copyright indicates.) You should not use it on any modern Web server. It was more than adequate at a time when the Web was young, and we didn't have to worry (too much) about security. And before the CGI module was written. And so forth. No one should use it any more. There are dozens, and probably hundreds, of ways to send e-mail from a Web server without the security concerns that form-mail has. A: Since you saw this part of the message: More information about this error may be available in the server error log. You should be here asking "How do I see the contents of my server error log?" :-) The short answer is "it depends on how your particular web server is configured". ie. you should ask your webmaster/ISP that question. For more info, there is a magazine article (written by the same author as your code): Learning to use the httpd error log to debug CGI programs http://www.linuxjournal.com/article/2055 You can easily arrange to get those messages displayed in the browser too, as described in the answer to your frequently asked question: http://perldoc.perl.org/perlfaq9.html#My-CGI-script-runs-from-the-command-line-but-not-the-browser.-%28500-Server-Error%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7545471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: background color problem in an access form I have a form containing a textbox "Text20". I have put some code in the OnCurrent event of the form: Option Compare Database Private Sub Form_Current() Text20.BackColor = vbRed End Sub It does nothing when I display the form whereas it should color my textbox. Do you see why ? Thank you A: There really is no reason to do this in the code behind. Just right click the control, select conditional formatting and apply the formatting and give it a condition and a format. No code required. In fact, the code you included in your example would re-set that every time the form changes records, which is overkill anyway. Better yet. Why not just set the color in the property sheet for the control?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: add characters to end of line How do I add </in> to the end of each line? A String contain: <ch>13</ch><in>Item 13(mono) <ch>14</ch><in>Item 14(mono) <ch>15</ch><in>Item 15(mono) A: To replace each line break with </in> and a line break, you could try something like this: myString = myString.replace(/\n/g, "</in>\n"); But if the strings contains the extra white space, extra empty lines, in your example, you would probably end up with an extra </in> there too. So to get valid XML, you would probably have to do more than the above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Zend Framework default htaccess to Lighttpd I've been looking through the subject a couple of times, but nothing I found is quite what I need, and/or outdated as hell. I built a website using Zend Framework (and its default htaccess file), and tested it locally on MAMP, works perfectly. The live web server, unfortunately, runs on Lighttpd, which I gather does not support htaccess. The big problem with this is that I have absolutely no experience at all with web servers, regular expressions, mod_rewrite and so on, let alone using anything else than Apache. The default Zend Framework htaccess contains these lines: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] And I have absolutely no idea how to convert this to Lighttpd URL rewrite rules, and how/where to put them :/ Any help at all would be greatly appreciated! A: Going by this documentation: http://redmine.lighttpd.net/wiki/1/Docs:ModRewrite it should be done like this: url.rewrite-once = ( "^(/(?!(favicon.ico$|js/|images/)).*)" => "index.php" ) This basically tells your webserver to redirect everything that is NOT a file or NOT within the "js/" and "images/" folder to be redirected to the index.php As to where you have to put this snipped of code, i'm not so familiar with lighttp myself. But i hope the snipped itself helps you enough. For a fellow Sam! ;) A: This works fine for me (specialy for ZF2): url.rewrite-if-not-file = ("^/[^\?]*(\?.*)?$" => "index.php/$1")
{ "language": "en", "url": "https://stackoverflow.com/questions/7545489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I have the only column of my NSTableView take all the width of the TableView? I am currently trying to learn a bit of Cocoa (using the book Cocoa Programming for Mac OS X). In one of the exercises, we set up a NSTableView with only one column, to act as a list of things. What annoys me is that in Interface Builder, I could not find a way to have the (only) column always take the full width of the NSTableView. As a consequence, it always somehow looks like there are 2 columns when there is actually only one. Any idea ? A: This is just an IB problem that happens all the time (I'm not sure why). To solve this, simply just resize the table view to the size smaller than the 2nd column, then drag it back to the size you want and the 2nd column will disappear. A: Here's how I did it in Xcode 4.6... In IB, select the table view and go to the Attributes Inspector. Choose 'Uniform' for 'Column Sizing'. Then, select the table column and choose 'Autoresizes with Table' for 'Resizing'. These options correspond to: [tableView setColumnAutoresizingStyle:NSTableViewUniformColumnAutoresizingStyle]; [tableColumn setResizingMask:NSTableColumnAutoresizingMask]; A: I had to use both steps - sam's answer + the comment by David Douglas. [tableView setColumnAutoresizingStyle:NSTableViewUniformColumnAutoresizingStyle]; [tableColumn setResizingMask:NSTableColumnAutoresizingMask]; //AND [tableView sizeLastColumnToFit];
{ "language": "en", "url": "https://stackoverflow.com/questions/7545490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: mutex problem in windows I have problem with mutexes I have this code and I dont any idea why it doesn't work correctly... #include <windows.h> #include <process.h> #include <stdio.h> HANDLE mutex; unsigned _stdcall t(void*){ printf(":D:D:D\n"); return NULL; } int main(){ mutex=CreateMutex(NULL,FALSE,NULL); WaitForSingleObject(mutex,INFINITE); _beginthreadex(NULL,NULL,&t,NULL,0,NULL); WaitForSingleObject(mutex,INFINITE); printf("HD\n"); } the result is : HD :D:D:D I expect not to see HD in console..... but this code work correctly HANDLE mutex; unsigned _stdcall t(void*){ WaitForSingleObject(mutex,INFINITE); printf(":D:D:D\n"); ReleaseMutex(mutex); return NULL; } int main(){ mutex=CreateMutex(NULL,FALSE,NULL); WaitForSingleObject(mutex,INFINITE); _beginthreadex(NULL,NULL,&t,NULL,0,NULL); printf("HD\n"); while(1){ } } the result is: HD Thank you everyone.... A: As per MSDN: The thread that owns a mutex can specify the same mutex in repeated wait function calls without blocking its execution. Thus in your first sample, the second call to WaitForSingleObject() doesn't block the main thread as it is the thread that owns the mutex. A: It looks like you want the main thread to take the mutex on behalf of the secondary thread. Mutexes are tracked by thread, so you cannot take a mutex on behalf of somebody else. You might want to switch to a semaphore, which does not have owner tracking. A: You used the mutex improperly: when you wait for a mutex you block until somebody else will release it. The thread procedure must do its own lock/unlock (WaitForSingleObject and ReleaseMutex, in windows) as well as the main thread. The purpose is avoid that one thread interleave the output with another. If you want to "join" a thread (do something after its termination) you can wait for it as well. HANDLE mutex; unsigned _stdcall t(void*) { WaitForSingleObject(mutex,INFINITE); printf(":D:D:D\n"); ReleaseMutex(mutex); return NULL; } int main() { mutex=CreateMutex(NULL,FALSE,NULL); _beginthreadex(NULL,NULL,&t,NULL,0,NULL); Sleep(0); WaitForSingleObject(mutex,INFINITE); printf("HD\n"); ReleaseMutex(mutex); } Also: don't use infinite loops to stuck a thread (while(1) ...), use Sleep instead. Note also that -in general- you cannot predict what thread will printf first. That's what concurrency is for: the threads compete each other running in parallel. The mutex avoid them to output together, but what sequence will result depends also on what else the system is doing while running your program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to Create sample movie ( mini movie) with ffmpeg? Is it possible to create a mini movie ( if i have a movie which is 1 hour - i want 3 seconds of it) with ffmpeg ? How do i do it ? A: This command will copy the first 3 seconds of input.avi to output.avi. ffmpeg -ss 0 -t 3 -i input.avi -codec copy output.avi This will stream copy (re-mux), so no encoding is occurring. If you want to re-encode then remove -codec copy: ffmpeg -ss 0 -t 3 -i input.avi output.flv
{ "language": "en", "url": "https://stackoverflow.com/questions/7545506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Call variable inside a function AS3.0 I'm trying to pass a variable through a function, but I'm getting it's value 0 Here's my code: thumbLoader.addEventListener(MouseEvent.CLICK, goToCategory); function goToCategory(e:MouseEvent) { trace(c); gotoAndStop(2); doSMTH(0); } this trace gives me value of 0. Normally I would do goToCategory(c) and inside that category I would get it's value, but in this case I'm calling this function with an event, how can that be done? var c is declared globally, so I'm using it above this code in different place... is there smth like global $c like in PHP.. or there's some other way to do it? Thanks in advance!!! A: You could try to not use globals, but if you really don't know how, then one solution is to use a static class, and add your globals to it: package { public class Globals { static public var c:String = ""; } } Then access the global with: trace(Global::c); Just writing this code makes me shiver but that's one way to have globals. A: I assume variable c is available where you are adding mouse click listener. In that case, this should do what you want. thumbLoader.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) { goToCategory(c); } ); function goToCategory(c:*) { trace(c); gotoAndStop(2); doSMTH(0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: os.walk() strips polish characters So what I'm trying to do is fix some id3tags of mp3 files. It all works, except for files with any kind of accent, because os.walk seems to strip them. For example, I have the file 01.Co Słychać.mp3, which in this code: for root, dirs, files in os.walk(folder): print files Shows up as ['01.Co Slychac.mp3'], later resulting in a 'No such file or directory' error. How can this be fixed? A: Did you define folder as a Unicode string? This has implications on how os.walk() matches its subdirectories, or better, the type of string that it returns. >>> for a,b,c in os.walk("."): ... print b ... break ... ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'tcl', 'Tools'] >>> for a,b,c in os.walk(u"."): ... print b ... break ... [u'DLLs', u'Doc', u'include', u'Lib', u'libs', u'tcl', u'Tools']
{ "language": "en", "url": "https://stackoverflow.com/questions/7545511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Move data from one table to another This question seems to be answered multiple times. However none match the criteria I need. Is it possible to select (and insert them in another table) and delete rows from the original table in Mysql without running the selected criteria twice? For example I could do this: INSERT INTO main (SELECT * FROM temp WHERE age > 30) DELETE FROM cache WHERE age > 30 However with a very complex and long running query the 'match part' of the query would be executed twice, whilst I think that there should be a solution to delete the selected items, since you have fetched them already anyways. My question, is this possible, and if so. How? A: No you can't do that. You should use a transaction if you are worried about the integrity of your tables in between the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding nested model with MVC3 on HttpPost I am new to MVC3. I have a submit button on a form and I want to bind a model which has 2-3 nested object models with many properties inside. Is there a way to bind these nested objects without using EditorFor; so that when I submit the form I will take on ActionResult(Object model) on model that is being returned, the nested object models with their values without having to implement hidden values or forms behind on html? A: The DefaultModelBinder works by convention, so for it to work, the form fields must adhere to the MVC naming convention. If you do not want to use EditorForModel to create your form, then you will have to implement your own naming convention for every field, and set ViewData.TemplateInfo.HtmlFieldPrefix for each element. Then, you will have to create a custom ModelBinder to take the form returned, and bind to your models based on your naming convention. Be aware that this creates some other issues in MVC3, most important of which is that the rendering of unobtrusive validation for DropDownLists and some other items may fail. For the general case, it is best to use EditorForModel in your view, and to work using MVC's existing conventions. You can create a view which is specific for each nested model. Brad Wilson gives a good overview of the process in this article. A: basically you need enough values to identify your model again. So you can go with a Id in a hidden field and all the properties you want to change. To recreate your model either just pass the Id and changed values via basic parameters to your controller-action or write a model-binder - IMHO thats the best way to deal with those situations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: flash dynamic text field I want to make auto width text area. Using xml to pull the data, I would like to expand as data comes in. menu_item_group["menu_item" + i].item_label = nodes[i].attributes.item_label; For example: enlarged according to the context menus in this example, the background http://webscripts.softpedia.com/scriptScreenshots/AS3-XML-MENU---VERTICAL---Screenshots-53313.html How can I do this? A: I cooked up a light example for you. The most important part to note is the myField.autoSize as that will do what you are looking for. I use LEFT by default, but there is also CENTER and RIGHT. Anyway, in this working example you'll see that the border always fits to the length of the text and that the length is new every time you run the program. Note that this example only works when the TextField is set to Single Line. Multi Line works differently. Good Luck! import flash.text.TextField; import flash.text.TextFieldAutoSize; var myField:TextField = new TextField(); myField.border = true; var jibberish:String = "Z"; for(var i=0; i < Math.floor(Math.random() * 100); ++i) jibberish += "Z"; myField.text = jibberish; myField.autoSize = TextFieldAutoSize.LEFT; this.addChild(myField);
{ "language": "en", "url": "https://stackoverflow.com/questions/7545517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: log file viewer for java applications All, I was exploring if there can be a tool that helps me to this: * *View a log file in reverse chronological order i.e. I want to see the latest log statements being written to a log file at the top of the screen and not scroll all the way down every time log file is updated. *may be pause while viewing so that while I am reading or analyzing my log files, it does not refresh the screen. Is it possible? I am using log4j for logging in my j2ee application. Thanks. A: You can use OtrosLogViewer. You can pause scrolling to bottom and turn off adding new log events. You can watch screen capture on youtube. Disclaimer: I am the author of OtrosLogViewer A: You can use Apache Chainsaw. Although it doesn't appear to be actively developed, you can: * *toggle the option of automatically scrolling to the bottom. You can also order the log records in the reverse chronological order, to display the most recent records first, so the previous option is no longer required. *pause log record collection. This will discard any log records and will not update the display until you resume collection. A: Use LogMX from www.logmx.com. I've worked with Chainsaw and LogFactor5, but in the end, LogMX is worth the money. Use Chainsaw if you want something free. A: Check mtail (or monkeytail). It's not exactly what you are searching for but maybe worth a look. Watch all of your logs using monkeytail Some closed question in SO: * *The best Tail GUI *Best tail (log file visualization) freeware tool?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Which of these two dimensional array are advantageous to use and why? In a facebook group, I saw a question like : If a row dominated two dimensional array in the following which one is advantage and why? a) for(i=0;i<1000;i++) for(j=0;j<1000;j++) temp=temp+a[i][j]; b) for(j=0;j<1000;j++) for(i=0;i<1000;i++) temp=temp+a[i][j] From my point I can see there is no difference in the above two statements. And I guess these both are same. Correct me if am wrong? A: There is no difference in theory. The practical advantage is in cache locality. If you access locations which are far apart, you increase the number of cache misses, which in turn makes the code run slower. Depending on your processor cache size, you would perhaps need to replace 1000 with some reasonably bigger number in order to perceive the effect. A: Variant (a) is better, since it's much more cache-friendly, than (b): you access consecutive elements, so there are less cache misses. However, some compilers can rearrange your loops, so when compiled both variants might produce same machine codes. Besides performance, there is no difference between this two variants, i.e. thay produce the same output. A: However, there could very well be extenuating circumstances. For instance, if the numbers are both positive and negative there could be patterns to them such that one order would lead to an overflow (or loss of precision if floating point) where the other would be much better behaved. A: When the CPU wants to read data/code from the memory, chunks of data or moved from the memory to cache. Cache is much faster than RAM and much more expensive, so you have little of it. The idea behind this is that usually when you read one part of memory, you probably read other parts that are close to it. In method a, you read the array row by row, and therefore you keep the locality. That is, on the first read from a row, the row is loaded in cache, and the rest of the row is read from cache (cache hit), so you have a high cache hit rate which is good. In method b, you are deliberately accessing the array in a non contiguous way, so you get a lot of cache misses, and you need to keep reading from memory all the time. A: According to me The Correct One is 'A' :Because when we use array of 2-D it is easy for assessment Of element Row by Row to cache ,than Column by Column, Since Cache is used for fast Assessment ,if more hit than it behaves fast so first one is Correct, Thanx Have a nice day.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alternatives to multicast I'm currently developing a server (using Java) that has to send quite often (every 10-30 seconds) a few bytes to multiple clients (10 - 100). At first, I thought of using UDP multicast datagrams (java.net.MulticastSocket), but I thought of this not being a good solution because of the bad support for multicast on most routers. So I'm wondering if it would be a good idea if I sent all data directly to the hosts via unicast or do you know of anything more elegant/with less traffic? A: There are many advantages in using JMS, but most of these use TCP and so could you. A few bytes every 10-30 seconds to a few hundred clients is small even on low bandwidth networks. Say you send a 100 bytes message to 100 clients every 10 seconds, That 1000 bytes per second or 8Kbits/second. Even 3G networks will support this bandwidth easily. i.e. you could do this with a smart phone. ;) The simplest approach may be to have a tcp connection from each client which the server sends update messages as required. A: Have you considered using a message queue such as Active MQ? These have the nice characteristic that you write the message once to the queue and you can have as many readers as you like reading the queue. A: You can also use a gossip-based application-level multicast protocol. For instance, NeEM will scale easily to 100 destinations while providing an interface similar to MulticastSocket and using just TCP/IP, thus being compatible with less than optimal network setups.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validating XMLs with "free" elements using XML Schemas Is there a way to define an XML schema that allows elements not defined in the schema? I have an XML file that needs validation only on part of the file. like so: <?xml version="1.0"?> <xml> <ValidatedElement type="PositiveInteger">123</ValidatedElement> <OtherStuff> <MemoryUsed type="PositiveInteger">356</MemoryUsed> <MemoryLeft type="PositiveInteger">44</MemoryLeft> </OtherStuff> </xml> I'd like to schema-validate only certain elements (regardless of position in the XML. If hierarchy could also be ignored - even better) A: Using the <any> directive, you can define spots where any content is allowed. If you want to validate elements that can exist in arbitrary positions in a tree of otherwise unvalidated content, you'ld have to look them up and arrange for them to be individually validated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transparent background for Facebook "like" button I need the background for the Facebook "like" button to be transparent. I've achieved this one time but I don't remember how I did it. allowTransparency="true" in the iframe version of the button doesn't work either. Any ideas? A: allowTransparency="true" with iframe version should work, I have used it recently without any problem like this: <iframe src="//www.facebook.com/plugins/like.php?app_id=242000359180192&amp;href=www.facebook.com%2Fbevagus&amp;send=false&amp;layout=button_count&amp;width=180&amp;show_faces=true&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=21&amp;locale=cs_CZ" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:180px; height:21px;" allowTransparency="true"></iframe>
{ "language": "en", "url": "https://stackoverflow.com/questions/7545537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cocoa Touch: parsing XML, should I use NSXMLParser or a Dom parser? I need to parse a XML file storing events. I just need to process events with ending date later than actual date, so no many of them will used in the app. The application will need to sort then before displaying, and then the user will resort and filter the results in a UITableView. By now I just parse the data with NSXMLParser and load it into a NSMutableArray of Events. Then I can reorder the array or select a subset of it to acomadate to user needs. What are the benefits of using a Dom parser and building an in-memory representation of the document? how is this representation implemented? is the sorting and filtering faster? does it save memory? can it be configured so only events with some condition are parsed? can it be configured to include needed elements from each event and not all of them?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Find all connected components given the connections in a graph (Java) I'm building a program in Java that simulates a network of moving nodes. When nodes collide there is a certain probability that they will establish a connection. I'm trying to store all the nodes in the graph in a way that makes the connected components obvious, so I'm storing it as a Set of Lists where each list is a component and the set contains all components. (Each component must have size greater than 1.) The complete code is on github: https://github.com/IceCreamYou/ViralSpread But here's the important part: // Store the components in the "temp" variable while we calculate them. // Each list is a component; the set contains all components. HashSet<LinkedList<Person>> temp = new HashSet<LinkedList<Person>>(); // hardConnections is a set of all connections between the nodes. // Each connection appears only once (e.g. if there is a connection from A to B // there will not be a connection from B to A -- however each connection is // considered bidirectional). for (Person[] connection : hardConnections) { // Each element of hardConnections is an array // containing two connected nodes. // "Person" is the node class. Person a = connection[0], b = connection[1]; boolean bFound = false, aFound = false; // If we've already added one of the nodes to a component, // add the other one to it. for (LinkedList<Person> component : temp) { boolean bInComponent = false, aInComponent = false; for (Person p : component) { if (p.samePosition(b)) { bInComponent = true; } if (p.samePosition(a)) { aInComponent = true; } } if (bInComponent && !aInComponent) { component.add(a); bFound = true; break; } else if (!bInComponent && aInComponent) { component.add(b); aFound = true; break; } else if (bInComponent && aInComponent) { aFound = true; bFound = true; break; } } // If neither node is in a component, create a new component containing both nodes. if (!bFound && !aFound) { LinkedList<Person> newComponent = new LinkedList<Person>(); newComponent.add(b); newComponent.add(a); temp.add(newComponent); } } components = temp; p.samePosition() checks if the nodes have the same X and Y position. I'm using that method instead of equals() just in case the problem is related to equality checks failing somehow, even though I haven't overridden anything in the Person class (including equals(), hashCode(), etc.). This seems to work most of the time. Unfortunately sometimes after a new connection is added to a component from an existing component, this code calculates the new single component as being two components of incorrect sizes. I'm aware that the problem could also be that I'm calculating the connections incorrectly. However, the connections display correctly on the screen, and there are the right number of them (in the set -- not just from counting on the screen) so the error is probably not there. Just in case though, here's the code that calculates the connections. It's a little less generic than the code above so probably harder to read. // "infected" and "infector" are the nodes. // sameColor is true if the nodes have the same type. // Nodes with the same type should retain their connections // (which are also to nodes of the same type) while if the nodes have different types // then the "infected" node will lose its connections because // it will no longer be the same type as those connections. // Note that nodes of different types should never have connections to each other. boolean sameColor = (infected.getVirus().equalsVirus(infector.getVirus())); boolean sameColorConnectionExists = false; // As above, hardConnections is a set of connections between nodes (the Person class) Iterator<Person[]> it = hardConnections.iterator(); while (it.hasNext()) { Person[] connection = it.next(); if (sameColor) { if ((infected.equals(connection[0]) && infector.equals(connection[1])) || (infected.equals(connection[1]) && infector.equals(connection[0]))) { sameColorConnectionExists = true; } } // Remove connections to the connected person. else if (infected.equals(connection[0]) || infected.equals(connection[1])) { it.remove(); } } // Create a new connection if the nodes were of different types or // if they are the same type but no connection exists between them. if (!sameColor || !sameColorConnectionExists) { hardConnections.add(new Person[] {infected, infector}); } // After this function returns, the infected node is changed to the type of the infector. Basically what's happening there is we walk through the set of connections and remove any connections to the infected node that aren't from nodes of the same type. Then if a connection between the infected and infecting nodes doesn't exist, we add one. I can't figure out where the bug is here... any help (or even other tips / comments on the project itself) would be appreciated. If you're looking at the code in github, the code in question is in Statistics.java functions updateConnections() and updateComponents(). updateConnections() is called from Person.java in transferVirus(). Thanks. UPDATE I've been outputting debugging information in an attempt to figure out what's going on. I've isolated one collision that causes incorrect fragmentation. In the data below, the first part shows the edges of the graph, and the second part shows the connected components and how many nodes are in them. As you can see, after the second collision, there is an extra "dark gray" component that shouldn't be there. There is only one "dark gray" component and it has 4 nodes in it. (Screenshot: http://screencast.com/t/f9PIzjuk ) ---- blue:(489, 82) blue:(471, 449) blue:(416, 412) blue:(471, 449) pink:(207, 172) pink:(204, 132) dark gray:(51, 285) dark gray:(635, 278) dark gray:(635, 278) dark gray:(746, 369) dark gray:(51, 285) dark gray:(737, 313) dark gray:(737, 313) dark gray:(635, 278) cyan:(2, 523) cyan:(473, 273) 3 blue 2 pink 4 dark gray 2 cyan ---- blue:(514, 79) blue:(535, 435) dark gray:(725, 326) dark gray:(717, 365) blue:(404, 404) blue:(535, 435) pink:(197, 186) pink:(236, 127) dark gray:(35, 283) dark gray:(619, 271) dark gray:(619, 271) dark gray:(717, 365) dark gray:(35, 283) dark gray:(725, 326) dark gray:(725, 326) dark gray:(619, 271) cyan:(1, 505) cyan:(490, 288) 3 blue 2 pink 4 dark gray 2 dark gray 2 cyan ---- After thinking more about what information I needed in order to debug this without producing an overwhelming amount of information, I produced this result of a snapshot during the simulation: red:(227, 344) red:(257, 318) red:(643, 244) red:(437, 140) red:(437, 140) red:(257, 318) orange:(573, 485) orange:(255, 143) orange:(255, 143) orange:(20, 86) red:(227, 344) red:(437, 140) orange:(727, 494) orange:(573, 485) 3 red red:(257, 318) red:(227, 344) red:(437, 140) 4 orange orange:(255, 143) orange:(573, 485) orange:(20, 86) orange:(727, 494) 2 red red:(437, 140) red:(643, 244) If you follow the logic here: * *Look at the first connection. There are no components yet, so create a new one with red:(227, 344), red:(257, 318). *Look at the second connection. There is only one component and none of the nodes in the component match either of the nodes in the connection, so create a second component with red:(227, 344), red:(257, 318). This is wrong because there are other nodes later in the list that connect the nodes in the current connection to the original component. *Look at the third connection. The second node matches a node in the first component, so add the first node to the first component. *...and so on. So now I know that my algorithm for finding connected components is actually wrong. I guess I need to do some research on that. My first thought is to take the following approach: * *Create a copy of the list of connections. *When we look at the first pair, we don't have any components yet, so add the nodes in the first connection to a new (first) component and remove that connection from the copy. *Look at each successive connection. If one of the nodes in the connection is in the first component: * *Add its nodes to the component *Remove that connection from the copy *Go back to the last connection with nodes that we added to the component, and check each connection between that connection and the current connection to see if they connect to the component now. If they do, add them to the component and remove them from the copy. Do this recursively. *When we get to the end, repeat the process starting with the (now reduced) copy instead of the list of all connections. Any thoughts on that approach would be appreciated. A: Per comments on the OP above -- For anyone interested, I completely redesigned the algorithm (which essentially maps a set of unique two-way edges to a set of connected components [size > 2]). You can find it in the github repo at https://github.com/IceCreamYou/ViralSpread/blob/master/Statistics.java
{ "language": "en", "url": "https://stackoverflow.com/questions/7545542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to make NSURL form string I'm trying to read a a file in my project. I first create a string with the path and then turn it into a NSURL, and that's where I get into trouble: NSString *sndPath = [[NSBundle mainBundle] pathForResource:@"vader" ofType:@"caf"]; NSURL *url = [NSURL URLWithString:sndPath]; //url is nil! The contents of sndPath is: /Users/fernando/Library/Application Support/iPhone Simulator/4.3.2/Applications/4B677E62-A6BB-4436-A3DA-EB83A57917FF/Ex1.app/vader.caf The file does exist, BTW. A: When creating a URL that represents a file system path, you should use +[NSURL fileURLWithPath:] or +[NSURL fileURLWithPath:isDirectory:]
{ "language": "en", "url": "https://stackoverflow.com/questions/7545544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleted the apk key by mistake I have put up an app in the market..but I have to update the app..but my mistake i deleted the old apk and have made changes to the code and when I try uploading the app it says I must have the same key..what should I do now? A: There is absolutely no way to update your application. Sorry. You should publish you new update as a new Application with a new key and a new package. Also update the description of your old app and tell your user about the new app. If you have a webview loaded from external web server, try to inform on that page, too. Basically, that is all you can do. Lessons learned: Backup your key the next time! A: You will have to upload a new application to the market. There is nothing else you can do. Like they said at the last Google IO - Even if you know Andy Rubin personally, even he can't do anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Has the ::-webkit-selection selector ever been supported? There are a few references on the internet to ::-webkit-selection, a WebKit-specific version of the ::selection selector. See e.g. http://www.quirksmode.org/css/selection.html (Edit: PPK has since removed ::-webkit-selection from that page.) However, I haven’t been able to get the example in the page above, or my own examples, to work in any WebKit-based browser. I’ve tried: * *Safari * *1.0 *1.2 *2.0 *3.0 *4.0 *5.0 *5.1 *Chrome * *2 *6 *14 The unprefixed ::selection selector works in all of these browsers anyway, so it’s not really a problem. But I was wondering where the references to the WebKit-specific version of this selector had come from. Has anyone ever used it? A: I’ve tested all the way back to Safari 1.0 (using Multi-Safari), and no version supports ::-webkit-selection (and they all do support ::selection). Unless this is an issue with Multi-Safari, ::-webkit-selection has never been supported in Safari post-1.0. I guess it might have been in the public beta though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Location of variables in the memory, C I'm looking at exams in C from past years, and I'm came across a question I didn't fully understand. They've supplied a simple piece of code, and asked about the location of different variables in the memory. The options were heap stack and unknows. I know that automatic variables a initialized in the stack, and that dynamically allocated variables are in the heap. So, first question - what is unknown? For the second question here's the code and the table with the right answer: #include <string.h> #include <stdlib.h> typedef struct { char *_str; int _l; } MyString; MyString* NewMyString (char *str) { MyString *t = (MyString *) malloc (sizeof (MyString)); //LINE 12 t->_l = strlen (str); t->_str = (char*) malloc (t->_l + 1); strcpy (t->_str, str); return t; } int main() { MyString ** arr = (MyString**) malloc (sizeof (MyString*)*10); //LINE 21 int i; for (i=0;i<10;i++) { arr[i] = NewMyString ("item"); //LINE 25 } // do something // free allocated memory return 0; } And here's the table with the results I didn't understand Variable Line number Memory location arr 21 stack *arr 21 heap **arr 21 unknows arr[5] 25 heap arr[3]->_str[2] 25 heap *(t->_str) 12 unknows I think I understand arr and *arr, but why is **arr unknown? The rest I couldn't answer at all, so any help would be great. I know its long so thanks in advance... A: This is a crappy exam question. The C standard does not specify how the storage is allocated -- it only specifies the semantics. Heap, stack, etc. are specifics of a particular implementation. Read about storage class and storage duration in C. The variable arr is allocated on the stack ("automatic variable"), but the values of the expressions *arr and **arr are obtained by following pointers, and in general, it is impossible to say where the memory is allocated just given the pointer to it. The similar reasoning is for the other unknown case. A: About unknown: the idea behind the question is that at line 21 *arr is allocated but not initialized. Therefore it points to some arbitrary location. Therefore the placement of **arr is treated as unknown. Of course, the zvrba's note about the semantics is still valid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Make a button ADD a number to a label I'm fairly new to coding with Objective-C/Xcode, so I'm just trying my luck with the easy stuff, making sure I get it before moving on to something harder. What I am trying at the moment is to make a calculator. I've done one of those simple ones where there are two text boxes and an equals button, so I'm trying a number pad calculator now. What I'm stuck on is how to ADD a number to a label (NEXT TO ALL THE OTHER NUMBERS, NOT ADDED) when the corresponding button is pressed. I can manage to add one number, but not both. At the moment, I am only experienced with vb.net, so I'm used to label.text = label.text & 1 I'm not sure how to do this is in Xcode. Any help, code hints, links (or code chunks :P) would be appreciated. A: Don't add the number to the label. Instead, have another variable which is your running total which is a number and then update the label with the text version of the number. A good habit to get into is separating your presentation (view) from your data (model). In this trivial example, create a variable to hold your data and make the UI reflect that. Don't use the label as your model. As a simple code example, let's say I had an increment button and I wanted it to increment the value of the label. The action for the button is the IBAction increment function. Header: @interface CrapletViewController : UIViewController { NSInteger _total; } @property (nonatomic, retain) IBOutlet UIButton *myButton; @property (nonatomic, retain) IBOutlet UILabel *label; - (IBAction)increment:(id)sender; Implemenation: - (IBAction)increment:(id)sender { _total++; NSLog(@"total"); [label setText:[NSString stringWithFormat:@"total: %d", _total]]; } A: label.text = [[NSNumber numberWithInt:([label.text intValue] + 1)] stringValue];
{ "language": "en", "url": "https://stackoverflow.com/questions/7545559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use Java 7 with Eclipse Indigo 3.7.1 From what I understand Eclipse Indigo 3.7.1 should now have support for Java 7. I downloaded Eclipse 3.7.1. and JDK 1.7.0 and added JRE7 in the settings in Eclipse. Then I created a new project using JRE7 and wrote a short Java 7 program: public class Test7 { public static void main(String[] args) { String k = "Hello"; switch(k) { case "World": System.out.println("World Hello"); break; case "Hello": System.out.println("Hello World"); break; } } } But I get an error when I try to use a String in a Switch statement. The error in Content assist looks like this: Have I done anything wrong or doesn't Eclipse 3.7.1 have support for Java 7 yet? Is there any settings in Eclipse I need to change? A: You also have to change the compiler compliance settings under "Preferences | Java | Compiler | JDK Compliance." Setting the JDK for the project only sets the libraries to compile against and the JDK used to run the project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Access denied for user 'root'. PHP/MYSQL/XAMPP I have been using XAMPP for a while now, but this morning seems like something kinda went wrong. I am using XP with XAMPP 5.3.5. I develop at home, and I use my other computer as a server. running PHP/APACHE/MYSQL on XAMPP. I am using phpMyAdmin to manage my db. I noticed that my webpage was not responding too quickly, would lag and return an error about not being able to connect to the DB. (I lost that error message, I tried too many times). * *I ended up changing the root security password inside phpMyAdmin *changed the config.inc.php for that very same password Still I get this message: Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'@'localhost' (using password: NO) in C:\xampp\htdocs\MyProject\includes\connection.php on line 5 Database connection failed: Access denied for user 'root'@'localhost' (using password: NO). Why does it say "using password: NO" ? I did create a password for root, and also for the directory, and also updated config.inc.php How do I recover from this, seems like a work day has passed by. Thanks !!! A: Rule #1: DO NOT USE root for application programming. Try logging onto the database using the mysql client and your root password. If that doesn't work, you may have to reset your root password. The MySql docs have instructions for that. A: Have you tried with root as both the username and password? A: you might try searching your browser cookies for "localhost". you could then delete any pma related items as they may contain outdated credentials A: Simply to add the password or remove the existing one 1. Go to your root of phpmyadmin. Select the user tab. 2. Select the user that you assign. 3. Click on Edit Privileges. 4. Find on login information fieldset 5. Adjust the password you wanna set That's it may helpful A: I know this sounds sounds bizarre, but on my new installation on Win7, using the Xampp stack, I typed '127.0.0.1' in 'username' field, and left 'password' blank. It took me straight to the control panel! A: XAMPP has a weird default configuration and accepts any user from any host. So the first time you open phpMyAdmin just use localhost for the server and don't type any user/pass. Once you're in delete both "Any" user accounts and create your own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Textarea add rare symbols I have problems with my textarea. When someone copy text from an html or .txt and paste it in my textarea, the post have rare symbols like: =20, =space, =3D... Anyone have some idea about my problem?? And how could I fix it? My textarea is: <textarea id="id_message" cols="40" name="message" rows="10"></textarea> I use Markdown, but I have tried this without javascript and the problem is the same. I use Django in Google app engine. Thank you in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the argument for promise::set_exception(x)? I found in several places on how a promise should be used references to copy_exception, but I can not find it in the current FDIS. Is there an alternative way on how to use set_exception() since those blogs? For example here void asyncFun(promise<int> intPromise) { int result; try { // calculate the result intPromise.set_value(result); } catch (MyException e) { intPromise.set_exception(std::copy_exception(e)); // <- copy } } I find std::current_exception() here. catch(...) { p.set_exception(std::current_exception()); } Therefore my questions: * *Should I always use current_exception(), even when I do not catch "..."? *Or is there new a different name for copy_exception? A: There is a different name for copy_exception. copy_exception was renamed late in the standardization process over confusion of what it actually did: template<class E> exception_ptr make_exception_ptr(E e) noexcept; Effects: Creates an exception_ptr object that refers to a copy of e, ... Use of either make_exception_ptr or current_exception is fine, depending on what exception you're trying to set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Setting a form field's default value from a request variable In Django, is it possible to set the default value of a form field to be tied to a request variable. e.g. request.META['REMOTE_ADDR']. This is just an example, it'd like to be use any of the headers available in the request variable without passing it explicitly to the form. Thanks. A: No, it is not possible, since the request object is not globally available, and thus it is not available in the form unless explicitly passed in. The initial argument exists for exactly the problem you are trying to solve. You should probably use form = YourForm(..., initial={'your_field': request.META['REMOTE_ADDR']) in your view. Edit: If you like to pass in the request explicitly, you can use something like this, and then just pass request=request when you instantiates the form: class YourForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(YourForm, self).__init__(*args, **kwargs) # ... use self.request in clean etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7545570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to launch a new process with different program in Unix? I heard that the Unix fork will copy current process. Does it mean exactly same program and state will be spawned in a new child process? I can't understand why it work in that way. Because it looks inefficient. * *What's the being copied? *And why does it work in that way? *Is there no other way to spawn new child process? (or separated process) A: It does work that way -- sort of. It's mostly implemented using "copy on write", meaning that most memory pages are shared between the two processes until the child tries to write to a page, at which point it really is copied. Therefore if a child is forked and then immediately loads and executes a new binary image, the inefficiency you're worried about never happens: the copies of the memory pages from the parent are never actually created. Are there other ways to make child processes? Sure, other operating systems do things differently. The UNIX way is actually a very efficient way to do things to that the child process can inherit open file descriptors, environment variables, and other system information from its parent: it actually leads to less work, rather than more! A: fork is very efficient on modern operating systems. It copies only the required pages via Copy on Write techniques or similar. Different operating systems have different ways of spawning other processes. Linux has a clone system call (and fork is based on that) that allows a lot of control on exactly what the new process inherits from its parent. Why it works that way, I don't know. It's efficient, widespread, and reasonably easy to use and understand (once you're read through the man pages and looked at examples). A: when calling a fork() think of cloning (you have an image of one but wait they are the same - which is the first one, which is the second/clone one?), there becomes a child thread under the main thread (parent/child). The forking is a system call, but the overhead is mimimal unless you follow-up with a call to exec. So, the forking/execing does cost you alot in unix. fork: A child process takes on the attributes of the parent - so there are sort of two separate runable code sections in the same memory space (one the parent, and one the child). To separate the two follow-up with a call to 'exec', now the child code section becomes a separated runable process and has a parent-id from its parent process. If you were to use just fork() then you have to manage the separate code sections of who is the parent, who is the child. The exec call is the cost of overhead for the kernel, not the fork. A: Does it mean exactly same program and state will be spawned in a new child process? Not exactly the same state. There is a small difference: the fork return value will differ depending on the process is the parent or the child. Of course the pids will also differ. Also, launching a new process doesn't need to be done with fork. posix_spawn has been standardized as an alternative when fork proves too difficult to implement. http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_spawn.html A: Oh, if you can explain how the init process or swapper 'init' is created in unix, then you understand the concepts of unix process creation: fork/exec. A beautiful thing!
{ "language": "en", "url": "https://stackoverflow.com/questions/7545571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Giving users unique ids in the form of an auto_increment Let me explain, take an inventory system. You have items and you have rooms. If I have a table for items, that means everyone's data gets inserted into the same table. Hence, the primary key (item_id) is auto_incremented by 1. So "John" signs up two weeks later and his first item's id might be 210. How can I go about giving each user their own "id?" Without resorting to creating their own table, which could get messy if I have 1,000 users. | item_id | item_name | user_id | | 1 | sofa | 1 | | 2 | ps3 | 1 | | 3 | ipad | 1 | | 4 | laptop | 2 | Example URL: http://domain.com/item/view/1 John would get a URL of http://domain.com/item/view/210 for his first item. In case this helps someone else, here's what i ended up doing. Create a mapping table. In my case, "users_items" with item_id and user_id and remove the primary key. SELECT case when item_id IS NULL then isnull(max(item_id)+1) else max(item_id) +1 end as item_id FROM users_items WHERE user_id = $user+id; A: Maybe create an additional column item_code which you can populate with something like SELECT ISNULL(MAX(item_code) + 1) FROM item WHERE user_id = 2 Considering item_id is a surrogate key it shouldn't matter what value it is, the user has no concern about that, but item code can be the code for the user to display. A: If its only about places where item id is visible to user, why not storing first item_id for each user in some column and then just adding desired ID(from URL, for example) to this number? For example in users table user with id=2 will have 4 as value of this column, and when he opens url /item/view/%X system will add (%x-1) to 4 and get real item_id.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vb.net looping through several passed parameters with same name i am passing paramters from one page to another all witht he same name...how do i look through them? dim sHtmlBody sHtmlBody = "" for i=0 to Request.QueryString("name").Count sHtmlBody = "<html><body onload=""window.print();"">" sHtmlBody = sHtmlBody & "<body>hello</body>" sHtmlBody = sHtmlBody & "</head>" next context.Response.Write(sHtmlBody) this is what i am doing and it works. But how do i access the individual name Dim Name = Request.QueryString("Name")(i) does not work A: You could try the following. dim sHtmlBody sHtmlBody = "" Dim nameValues As String = Request.Form.GetValues("name") For Each name As var In nameValues sHtmlBody = "<html><body onload=""window.print();"">" sHtmlBody = sHtmlBody & "<body>hello</body>" sHtmlBody = sHtmlBody & "</head>" Next Which means you can do the following. Dim name = Request.Form.GetValues("name")(1) A: Assuming the request looks like this: SomePage.aspx?name=name1&name=name2&name=name3 you could split the Name request parameter by comma: Dim names = Request.QueryString("Name").Split(",") For Each name As String In names ' do something with each name Next
{ "language": "en", "url": "https://stackoverflow.com/questions/7545579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Session clearing issue with PHP I'm using a Facebook Connect application. Imagine it's a kind of application, where users come to my site, clicks connect button, logs in to Facebook and comes back to my site and wait for another user to connect. I'm using the offline_access parameter when connecting. Once the user is back to my site, I need to clear all the session cookies. If the session wasn't cleared successfully, and the next user comes and connects, the user will not get the Login Page, instead it immediately redirects to my response URL, after taking my last session state. I tried these methods together to clear the session: if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]); } if (isset($_SERVER['HTTP_COOKIE'])) { $cookies = explode(';', $_SERVER['HTTP_COOKIE']); foreach($cookies as $cookie) { $parts = explode('=', $cookie); $name = trim($parts[0]); setcookie($name, '', time()-42000); setcookie($name, '', time()-42000, '/'); } } With the above methods, something is working, but not all sessions are cleared, especially the Facebook domain specific cookies. So, to delete Facebook cookies, I tried the following static methods as well to test how it works. But, even this fails. setcookie('L', '', time()-42000,"/",".facebook.com"); setcookie('act', '', time()-42000,"/",".facebook.com"); setcookie('c_user', '', time()-42000,"/",".facebook.com"); setcookie('datr', '', time()-42000,"/",".facebook.com"); setcookie('locale', '', time()-42000,"/",".facebook.com"); setcookie('lu', '', time()-42000,"/",".facebook.com"); setcookie('pk', '', time()-42000,"/",".facebook.com"); setcookie('p', '', time()-42000,"/",".facebook.com"); setcookie('presence', '', time()-42000,"/",".facebook.com"); setcookie('s', '', time()-42000,"/",".facebook.com"); setcookie('sct', '', time()-42000,"/",".facebook.com"); setcookie('x-src', '', time()-42000,"/",".facebook.com"); setcookie('xs', '', time()-42000,"/",".facebook.com"); And finally, I tried the normal methods, unset($_SESSION['fb_243155855719532_access_token']); unset($_SESSION['fb_243155855719532_code']); unset($_SESSION['fb_243155855719532_user_id']); unset($_SESSION['fb_243155855719532_state']); // Finally, destroy the session. session_unset(); session_destroy();exit; Destroying session works, but still Facebook sessions are not getting cleared. If I try to clear session cookies, with the Firefox Web Dev add-on, it works very smartly. A: If the user has 'offline_access' it's currently IMPOSSIBLE to clear the session. Calling the PHP SDK method getLoginUrl() looks as though it should work, it logs the user out of Facebook, but when returning to your own site, the session is still valid. This is NOT how it should work at the bug has only been introduced with the latest PHP SDK v3. I have registered a bug, please vote/add your repro to help get it fixed: http://developers.facebook.com/bugs/250825644953332 A: Due to cross-domain restrictions you can't edit cookies from a different domain (ie Facebook cookies). You could call the javascript sdk FB.logout() function to properly log out. The PHP SDK has a getLogoutUrl method that you could call: $facebook->getLogoutUrl( array( 'next' => 'http://example.com/logout.php') );
{ "language": "en", "url": "https://stackoverflow.com/questions/7545584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regressive python counter i was doing a small weekend project, kind of a music player, in python (console). I'm done in all the part of selecting music, parsing ID3 tags, playing and blablabla. I just think i need something like a counter to show the music's total time and played time. Basically what i need is to print a string, erase only that string and print it again. I don't care if i need any external libraries for this, but i need it to be windows if exists. So, is there any way to do this on python? Thanks in advance. A: You should look at the curses module which provides more control over the console. It is built into python. EDIT Apparently the standard library curses isn't available on Window, but you can look at using this: http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses But a simpler strategy is to use "\b" it is a backspace character. sys.stdout.write("a\b") Has no output because the a is erase. You might be able to use that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I see what the current android layout looks like for debugging purposes? In my android application, I frequently add and remove parts of my layout. Is there a way I can log or capture the layout at specific points? I want to see the way my buttons and layouts are nested to ensure it is as I want it to be at that moment. A: You can take screenshots using DDMS, or in Eclipse, view the layout as you create it.. A: Use the hierarchyviewer tool that comes with the SDK, in the platform-tools directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MotionEvent Issues I was wondering how to get accurate, get(x) and get(y) values for a MotionEvent? What is happening is that when I touch a specific area on the screen, I tell an action to happen. The problem is that once I touch the screen and take my finger off, it still thinks my finger is at the same location (since that was the last location I touched). So when I have more than one Down event (for multitouch) it throws everything off. Is there a way to reset the X and Y values so when I let off the screen, they go back to 0 or null (or whatever)? Here is a video I just uploaded to explain it better, cause it is kind of confusing http://www.youtube.com/watch?v=OHGj2z5SwQs And here is the exact code I'm using int x = (int) e.getX(); int y = (int) e.getY(); int x2 = (int) e.getX(1); int y2 = (int) e.getY(1); boolean a1 = y > 0 && y < 200....etc boolean a5 = etc... switch (e.getActionMasked()) { case MotionEvent.ACTION_DOWN: x = 0; y = 0; x2 = 0; y2 = 0; ////I'm setting the x and y values to 0 as suggested text.setText("x:" + String.valueOf(x) + "y:" + String.valueOf(y)); //// This is so I can see the values on the screen if (a1 && a5){ viewA1.setBackgroundColor(Color.GREEN); viewA5.setBackgroundColor(Color.GREEN); } if (a1) { viewA1.setBackgroundColor(Color.GREEN); } else if (a5) { viewA5.setBackgroundColor(Color.GREEN); } break; case MotionEvent.ACTION_POINTER_1_DOWN: // /A Strummer x = 0; y = 0; x2 = 0; y2 = 0; text1.setText("x:" + String.valueOf(x2) + "y:" + String.valueOf(y2)); if (a1 && a5){ viewA1.setBackgroundColor(Color.GREEN); viewA5.setBackgroundColor(Color.GREEN); } if (a1) { viewA1.setBackgroundColor(Color.GREEN); } else if (a5) { viewA1.setBackgroundColor(Color.GREEN); } /////I have pretty much the same method for ACTION_UP & ACTION_POINTER_UP; I set x & y to 0. Please let me know if you can think of anything. I tried the methods you guys explained and it would seem like it would help, but it hasn't. A: I don't have a tip but a working solution and some tips for multitouch starters. I never did that before so after seeing your question I was eager to now how multitouch works. And actually it's pretty tricky to get it done right. This is a great example for startes (view with four corners which are colored when one of the pointers is touching it - works with one up to five pointers / fingers). So I will explain it based on the working solution posted further below. Basically it works like this: getPointerCount() is giving you the amount of currently touching pointers. getX(i) and getY(i) are giving you the corresponding coordinates. But this part is tricky: pointer 0, 1, 2 are touching, you lift 1 (second finger), and now you have 0, 1. This is the point where getPointerId(1) will return 2 because this is still your pointer 2 which is touching but it's now on position 1 instead 2. You have a single chance to react on that change, that's when ACTION_POINTER_UP is fired. On this action and on ACTION_POINTER_DOWN getActionIndex() will return the action pointer position of the pointer which was added or removed from pointer event list. Otherwise it's returning always 0 and that's something nobody tells you. The conclusion is that you can't actually track which pointer is moving (that's why getActionIndex() is return 0 on move). That seems ridiculously logical because it would be stupid to fire 5 separate events for each finger. But while starting with multitouch that's a really non trivial fact ;-) Here's the example. coordsX and coordsY will track the pointer coordinates and if position 2 contains valid coordinates, it means that this is your third finger which is still touching the screen whether you lifted the other fingers or not. This might not be relevant in this case but it's a fact which could still be useful in other multitouch implementations. public class MultitouchView extends LinearLayout { // we have a maximum of 5 pointer // we will set Integer.MIN_VALUE if the pointer is not present private int [] coordsX = new int [5]; private int [] coordsY = new int [5]; // add 4 views with a certain gravity so they are placed in corners public MultitouchView(Context context, AttributeSet attrs) { super(context, attrs); // initialize as not present Arrays.fill(coordsX, Integer.MIN_VALUE); Arrays.fill(coordsY, Integer.MIN_VALUE); /* the layout is inflated from a XML file and is basically this one: * all subviews are matching / filling parent and have a weight of 1 * <LinearLayout vertical> * <LinearLayout horizontal> * <View /><View /> * </LinearLayout> * <LinearLayout horizontal> * <View /><View /> * </LinearLayout> * </LinearLayout> */ } @Override public boolean onTouchEvent(MotionEvent e) { if (e.getAction() == MotionEvent.ACTION_CANCEL) { // every touch is going to be canceled, clear everything Arrays.fill(coordsX, Integer.MIN_VALUE); Arrays.fill(coordsY, Integer.MIN_VALUE); } else { // track all touches for (int i = 0; i < e.getPointerCount(); i++) { int id = e.getPointerId(i); if (e.getActionIndex() == i && (e.getActionMasked() == MotionEvent.ACTION_POINTER_UP || e.getActionMasked() == MotionEvent.ACTION_UP)) { // pointer with this id is about to leave, clear it coordsX[id] = coordsY[id] = Integer.MIN_VALUE; } else { // update all other pointer positions coordsX[id] = (int) e.getX(i); coordsY[id] = (int) e.getY(i); } } } int hw = getWidth() / 2; int hh = getHeight() / 2; // first no corner is touched boolean topLeft = false, topRight = false, bottomRight = false, bottomLeft = false; // check if any of the given pointer is touching a certain corner for (int i = 0; i < coordsX.length; i++) { // pointer is not active (anymore) if (coordsX[i] == Integer.MIN_VALUE || coordsY[i] == Integer.MIN_VALUE) { continue; } topLeft = topLeft || coordsX[i] < hw && coordsY[i] < hh; topRight = topRight || coordsX[i] > hw && coordsY[i] < hh; bottomRight = bottomRight || coordsX[i] > hw && coordsY[i] > hh; bottomLeft = bottomLeft || coordsX[i] < hw && coordsY[i] > hh; } // set the result we have now to the views represnting the corners ((ViewGroup) getChildAt(0)).getChildAt(0).setBackgroundColor(topLeft ? 0xffffff00 : 0x0); ((ViewGroup) getChildAt(0)).getChildAt(1).setBackgroundColor(topRight ? 0xffff0000 : 0x0); ((ViewGroup) getChildAt(1)).getChildAt(0).setBackgroundColor(bottomLeft ? 0xff00ff00 : 0x0); ((ViewGroup) getChildAt(1)).getChildAt(1).setBackgroundColor(bottomRight ? 0xff0000ff : 0x0); return true; } } A: You should use ‘motionEvent.getPoinerCount()‘ to check the number of touch points.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do you know of any project that has redefined the native types of PHP as objects? Is it feasible? Do you know of any project that has redefined the native types of PHP (string, array, ints, floats, bools, etc.) as objects? I'm not sure how feasible it would be but i was just thinking that it would be nice to have the native types as objects. example: $Name = new String('Mary had a little lamb.'); print($Name->Length); //prints 23 print($Name->Replace('/lamb/', 'duck')); // prints Mary had a little duck. Would this add to much overhead? Have any thoughts on this? A: There are many, many, many (even native) projects that are aiming at that - thing is: Nobody uses them. There are basically two problems: * *PHP has only limited operator overloading. You can't overload the + operator. So to sum two number you would need to write $number->add($number2), which isn't quite intuitive. *PHP has loads of predefined functions. One could argue that PHP has the most powerful standard library of all programming languages. But: All those functions return the native types, not the boxed ones. So you would need to write something like $number = new Number(function_returning_number());. This also applies to 3rd party libraries. For the first issue there is a PECL extension. It is not bundled with PHP though and is not enabled on normal PHP installations. So you can't use it for portable applications. To solve the second issue, there is an Autoboxing RFC. Maybe it will be implemented, maybe not. A: Perhaps someone can clarify this, as I'm not completely informed on the subject - but PHP runs on the Zend engine right (C++) and thus if you're proficient enough could probably implement your above idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Risk of users editing any field in Lotus Notes document In designing forms in Lotus Notes I've always been under the assumption that if the user does not have designer (or manager) access they can only interact with the documents via the forms I provide. This means for example I can have a non-editable field for the status and know that only through interacting with the form (ie. following the workflow) can the status change and also know the steps that must be followed and all actions recorded in the audit trail (list of modifications/actions) However this toolbar script has turned my thinking upsidedown. * *What are the consequences of a non-designer/non-manager being able to change any field in a document (hidden or not)? *If this is an issue how would I go about preserving the status field or similar to ensure it doesn't get short circuited to "approved"? Similarly how do I stop the user from just editing the action history manually? A: Access-controlled forms and documents This works very well: To prevent editing of existing documents You can prevent users with Author access in the database ACL from editing a field in existing documents. This restriction doesn't apply to new documents. Open the form. Create a field, or click an existing field. In the Field Properties box, click the Advanced tab. Select "Security options: Must have at least Editor access to use" and click the check mark. A: Any ordinary user can, with the help of tools such as the one that you linked, read and change fields that are hidden or uneditable in your form design. That's because those features are not intended as security features. You can, however, hide the design of your database, and that makes it far more difficult for someone to use a little bits of Notes programming to access your application's fields. The downside is that hidden design makes maintaining your application a lot harder. Or you can use the real security features of Notes and Domino - ACL, ReaderNames and Authornames. These allow you to segregate your data fields into separate documents or even separate databases, where only specific people have rights to set, modofy or delete documents. You can have a non-editable master document pull in the values from these separately controlled documents, and separate edit buttons that launch dialogues to edit the secured portions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making JQuery extension $.fn.extension I'm writing a plugin that will display a little helper when called for. It's supposed to be initiated like this: $(el).santasLittleHelper([options]) The plugin then have some "events" just like the jquery UI has and they should be triggered like this: $(el).santasLittleHelper('evetnName', [options]) I have a prototype working but I have a few concerns about future problems with my structure. Flooding the memory or having other issues with variable and function scopes when I keep on working on it. Here is an outline: (function($) { $.fn.santasLittleHelper = function(p1, p2) { return this.each(function() { var o = { showSpeed: 50, hideSpeed: 50, duration: 5000, delay: 0 } var el = $(this); function init() { console.log('init 1'); } var events = { show: function(opt) {}, hide: function(opt) {}, pulse: function(opt) {} } if(p1 == undefined) {//This is obviously the init call init(); } if(typeof(p1) == 'object') { //Correctly added parameters would then mean that p1 is options //and is the only parameter added so we store the options and init $.extend(o, p1); init(); } if(typeof(p1) == 'string') { //This is a call to an "event". //call the "event" function and supply possible options as arg events[p1](p2); } }); } })(jQuery); Options can be supplied for each event call but should in that case only be available in that events function scope. This is because I might want the helper to do something out of the mental box I created him in by supplying options in the init call. Will this approach fill up the memory a little by each call to $(el).santasLittleHelper('event') because of the declared variables in the beginning of the code? I think it looks clean and understandable, but can improvements be done? A: According to practices described here, it seems to me that you're doing it right, but I would try if possible to make o and events independent of each (declare it before and pass as optional parameter if override is needed else use unique declared outside of each?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add a contact with first name and last name via intent I am trying to launch the android native "add or edit contact" activity with some data already in the form. This is the code I am using currently: Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT); intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); intent.putExtra(Insert.NAME, "A name"); intent.putExtra(Insert.PHONE, "123456789"); startActivity(intent); My problem is that I would like to specify a first name and a last name. I also noticed that there is a StructuredName class which contains constant identifiers for all fields I require. Unfortunately, I was unable to add the StructuredName fields to the intent... Does anybody know how this is done properly? Note: I am not trying to add the contact directly, but I want to open a populated "add contact" dialog! Thanks Duh A: Most/all values from ContactsContract.Intents.Insert are processed in the model/EntityModifier.java class in the default contacts application - and that just stuffs the value from Insert.NAME into StructuredName.GIVEN_NAME. You could try importing it as a vCard 2.1 (text/x-vcard), that supports all the name components but require that you either dump your vCard file on the sdcard or supply something that ContentResolver#openInputStream(Uri) can read (typically a file on the sdcard or an URI pointing to your own ContentProvider). A simple example that uses a ContentProvider to create the vCards dynamically: In your Activity: Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("content://some.authority/N:Jones;Bob\nTEL:123456790\n"), "text/x-vcard"); startActivity(i); In your ContentProvider (registered for the authority used in the ACTION_VIEW Intent): public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { try { FileOutputStream fos = getContext().openFileOutput("filename.txt", Context.MODE_PRIVATE); String vcard = "BEGIN:VCARD\nVERSION:2.1\n" + uri.getPath().substring(1) + "END:VCARD\n"; fos.write(vcard.getBytes("UTF-8")); fos.close(); return ParcelFileDescriptor.open(new File(getContext().getFilesDir(), "filename.txt"), ParcelFileDescriptor.MODE_READ_ONLY); } catch (IOException e) { throw new FileNotFoundException(); } } This should, when triggered, insert a contact named whatever you put in the path of your Uri into the phone book. If the user has several contacts accounts he/she will be asked to select one. Note: Proper encoding of the vCard is of course completely ignored. I image most versions of the contacts app should support vCard 3.0 also which doesn't have quite as brain-dead encoding as vCard 2.1. On the up-side, this method will also allow you to add work/mobile and other numbers (and more).
{ "language": "en", "url": "https://stackoverflow.com/questions/7545609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: how to post a message on a friends facebook wall facebook c# sdk using facebook c# sdk, I'm able to post to my wall but when I try to do it on my friend's wall, it just does not show, any ideas why this could be happening? client.Post("me/feed", parameters); ----works client.Post("friends id/feed", parameters);--does not work or client.Post("/friends id/feed", parameters); --does not work A: Make sure the app is not in sandbox mode, or if it is, add that friend as a developer of your application. Also, post the error message you are getting. A: Sorry to tell you, but you can't actually do this. Facebook has change the privacy settings, so that you can't access your friends wall using an app Please find the relevant info here https://developers.facebook.com/roadmap/completed-changes/ (look for the change of February 6th)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass a variable argument list I would like to create a subclass of UIActionSheet that uses blocks instead of delegation. So I created the following class: #import <UIKit/UIKit.h> // Public Interface typedef void (^FJActionSheetCompletion)(int buttonIndex); @interface FJActionSheet : UIActionSheet - (id)initWithTitle:(NSString *)title completionBlock:(FJActionSheetCompletion)completionBlock cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; @end // Private Interface @interface FJActionSheet() <UIActionSheetDelegate> { FJActionSheetCompletion _completionBlock; } @end // Implementation @implementation FJActionSheet - (id)initWithTitle:(NSString *)title completionBlock:(FJActionSheetCompletion)completionBlock cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... { self = [super initWithTitle:title delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:otherButtonTitles]; if (self) { _completionBlock = [completionBlock copy]; } return self; } - (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex { _completionBlock(buttonIndex); } @end This works except for one problem: I can not pass multiple strings for otherButtonTitles. If I do it as above, I (obviously) get a "Missing sentinel in method dispatch". My question is: How can I pass the otherButtonTitles argument to the initializer of UIActionSheet? A: see this great blog post about variadic methods. Mainly how to access the variable arguments by using va_list args; va_start(args, firstArg); va_arg(args, NSString*)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transform a data.frame, while filling missing values I have the data frame data<-data.frame(id=c("A","A","B","B"), day=c(5,6,1,2), duration=c(12,1440,5,6), obs.period=c(60, 60,100,100)) showing Subject ID, day of event, duration of event, and observation period of Subject I want to transform the data set to that it will show the whole observation period for each subject (all days of observation), while adding zero as duration values for the days where no event was observed For the above dataset this would be something like this: id day duration obs.period A 1 0 60 A 2 0 60 A 3 0 60 A 4 0 60 A 5 12 60 A 6 1440 60 A 7 0 60 A 8 0 60 . . . A 60 0 60 B 1 5 100 B 2 6 100 B 3 0 100 B 4 0 100 . . . . B 100 0 100 Any ideas? A: Here's one approach using the plyr package. First, create a function to expand the data into the appropriate number of rows. Then, index into that new data.frame with the duration info from the original data. Finally, call this function with ddply() and group on the id variable. require(plyr) FUN <- function(x){ dat <- data.frame( id = x[1,1] , day = seq_len(x[1,4]) , duration = 0 , obs.period = x[1,4] ) dat[dat$id == x$id & dat$day == x$day, "duration"] <- x$duration return(dat) } ddply(data, "id", FUN) id day duration obs.period 1 A 1 0 60 2 A 2 0 60 3 A 3 0 60 4 A 4 0 60 5 A 5 12 60 6 A 6 1440 60 ... 61 B 1 5 100 62 B 2 6 100 63 B 3 0 100 ... 160 B 100 0 100 A: Create an empty data frame with the proper index columns, but no value columns, then merge it with your data and replace the NA's in the value columns with zeros. data<-data.frame(id=c("A","A","B","B"), day=c(5,6,1,2), duration=c(12,1440,5,6), obs.period=c(60, 60,100,100)) zilch=data.frame(id=rep(c("A","B"),each=60),day=1:60) all=merge(zilch,data, all=T) all[is.na(all$duration),"duration"]<-0 all[is.na(all$obs.period),"obs.period"]<-0 A: I would first create a data frame to contain the results. ob.period <- with(data, tapply(obs.period, id, max)) n <- sum(ob.period) result <- data.frame(id=rep(names(ob.period), ob.period), day=unlist(lapply(ob.period, function(a) 1:a)), duration=rep(0, n), obs.period=rep(ob.period,ob.period)) Then I would paste id and day together, use match to find the relevant rows in the larger data frame, and plug in the duration values. idday.sm <- paste(data$id, data$day, sep=":") idday.lg <- paste(result$id, result$day, sep=":") result$duration[match(idday.sm, idday.lg)] <- data$duration A: Here is an approach with plyr fill1 <- function(df) { full_period <- 1:100 to_fill <- setdiff(full_period, df$day) fill_id <- df[1,"id"] fill_dur <- 0 fill_obs.p <- df[1,"obs.period"] rows_to_add <- data.frame(id=fill_id, day=to_fill, duration=fill_dur, obs.period=fill_obs.p) rbind(df,rows_to_add) } ddply(data, "id", fill1) The result is not sorted by id, duration, however.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i add text to span using jquery I am trying to add the selected value of combo box to its preceding span. but it failed too sad. I am trying with following code: <span></span><select multiple ="multiple" ondblclick="$(this).css('display','none').prev().css('display','inline').addClass('sss').html($(this).val());">....</select> What's the error here? how can i do it easily? I want it to trigger in double click event. as after double clicking on option of combo box it should disappear and selected text should appear in span and of course i forgot to tell that my select box is not selectbox. its a lisstbox. i.e multiple="multiple" A: Try something like: $('select').change( function() { $(this).prev('span').addClass('sss').text($(this).val()); }); JS Fiddle demo. References: * *change(). *prev(). *addClass(). *text(). *val(). A: You need to put an option in your select tag. <span></span> <select> <option>Something</option> </select> js $('select').click(function(){ $(this).css('display','none') .prev() .css('display','inline') .addClass('sss') .html($(this).val()); }); Example: http://jsfiddle.net/jasongennaro/AKa9b/ EDIT Based on the comment not working in context of multiple option, I revised as follows: $('select').change(function(){ $('select option:selected').each(function(){ $(this).parent().css('display','none') .prev() .css('display','inline') .addClass('sss') .html($(this).val()); }); }); Second example: http://jsfiddle.net/jasongennaro/AKa9b/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7545621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: encodeURIComponent in c sharp I've tried to use HttpUtility.UrlEncode in order to simulate the javscript's encodeURIComponent, but had some issues (instead of getting "%20" i got "+") then I've replaced the string, but i see that the problem is not only in these two signs, in some places the encoded string (by UrlEncode) is totally different from the encoded string by using encodeURIComponent. Any ideas how it can be solved ? thanks. A: You are looking for HttpUtility.UrlPathEncode. See this SO question: Server.UrlEncode vs. HttpUtility.UrlEncode
{ "language": "en", "url": "https://stackoverflow.com/questions/7545622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery plugin for user mappings? I am building a web application using asp.net, which has three types of user's admin, dealers, and employees (under dealers). The employees can be associated with more than one dealers and which can be done only by the "admin". So what i need is to make a neat employee and dealers mapping page visible to the admin. but am not getting any ideas, in order how to achieve that. The mappings can be in a graphical format (using any jquery plugin) or can be in a simple interactive tabular format. Searched for jquery plugin, but had no luck. Please help me out, need suggestions or demo page views of similar structure or any jquery plugins to be helpful. A: What about using Drag & Drop plugin of jQuery? It's simple and will provide a nice and easy way for the admin to associate employees with dealers by simply dragging and dropping them. Some nice example of this plugin is given here: jQuery UI - Draggable Demos
{ "language": "en", "url": "https://stackoverflow.com/questions/7545623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery custom tabs with next/prev links I am convert the jquery-ui tabs into a more basic version that is easily customisable although I have come across a couple of problems: * *How would I change the code into a reusable plugin/function that I can then use in the next/prev links on click? *Also I have a problem with the second tab is adding the next link. *Would there be any point in adding the cookie plugin to remember the tab also? I have tried to also write the code so that it adds the tab ID to the hash of the URL allowing direct bookmarking to a tab if the URL has a hash on the end. JS Fiddle code can be viewed here: http://jsfiddle.net/pmnzT/21 A: I've fixed next and prev links here you could find a working version. Second next link didn't appear because there is an error in the html, you inverted tab2 with tab4 now it's fixed. For remember your position why you don't use the localstorage? Is a lighter solution than use cookies. here some info :) For transform your code in a plug-in you could check this out link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Table cell fixed height and border issue in Firefox I have a table displaying some data and I need the table cell <td> to have a fixed height and a bottom border. The problem is that Firefox is rendering the cell height differently than Chrome or IE8. For example I have the following css rules: table { width: 100%; border-collapse: collapse; } table td { height: 35px; border-bottom: 1px solid #000; } Firefox renders the border inside the cell defined height so it shows 34px height + 1px border. Chrome and IE however render the full height and display the border outside/below that so it shows 35px height + 1px border. Here's a preview of the issue http://jsbin.com/oseqiz/9/. (open it in both Firefox and Chrome/IE to see the difference). Is this a known bug in Firefox or are the 2 other browsers doing things incorrectly. If so, is there any fix for it? I'd like to point out that I don't like having the extra <div> inside the <td> like I did for the second table in the above jsbin example. I implemented it like that so the rendering issue can be seen easily. A: Ok, please read this css property box-sizing has no effect on the box model A workaround could be, is to set td { display: inline-block; } And than use td { box-sizing: content-box; } For a cross-browser same height <td> A: This issue seems to have been fixed with the latest version of Firefox (which at this time is version 40), and the height and border is now rendered consistently within all the mentioned browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: parent.location.reload in iframe not working IE I need refresh in parent site / refresh my browser when I click testing. I have source index.php: <iframe id="test" src="/careertest/q.php"></iframe> and in q.php: <a href="#" onclick="parent.location.reload(true);">testing</a> Its working in FF LAtest version + Chrome but not working in IE 9. He said "script70 :Permission denied." I am already change parent.location.reload(true) with: window.parent.location =window.parent.location.href; or document.domain=document.location.href; but still not working... A: Try adding "window" after parent. parent.window.location.reload(true); A: use this function function reloadParentPage() { var selfUrl = unescape(parent.window.location.pathname); parent.location.reload(true); parent.window.location.replace(selfUrl); parent.window.location.href = selfUrl; } A: This works in IE, Chrome and Firefox and may be others window.top.location.reload();
{ "language": "en", "url": "https://stackoverflow.com/questions/7545633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL cut results from table I have the following query: SELECT cust_id,cust_name,SUM(calls.duration) as duration FROM calls, telephone WHERE calls.from_t_no = telephone.t_no AND calls.duration <=60 group by telephone.cust_id, telephone.cust_name Which give the following results; cust_id cust_name duration 0123456789 Avi 18 1234567890 Benny 27 2345678901 Gadi 13 3456789012 Dalia 69 4567890123 Hilla 5 5678901234 Varda 14 7890123456 Haim 20 8901234567 Tali 20 9012345678 Yoram 46 I also have this query: SELECT cust_id,cust_name,SUM(calls.duration) as duration FROM calls ,telephone WHERE to_t_no = telephone.t_no AND calls.duration >=500 group by telephone.cust_id, telephone.cust_name Which provides the following results: cust_id cust_name duration 2345678901 Gadi 50022 4567890123 Hilla 50000 the second query is actually another filter or condition which the first query should match. I cannot include the second query within the first query because it uses different columns. I need to "subtract" the second query from the first query. How do I do that? A: If you truly can't merge the queries, you can JOIN the results like this: SELECT T0.cust_id, T0.cust_name, T0.duration FROM ( SELECT cust_id,cust_name,SUM(calls.duration) as duration FROM calls, telephone WHERE calls.from_t_no = telephone.t_no AND calls.duration <=60 group by telephone.cust_id, telephone.cust_name) T0 JOIN (SELECT cust_id,cust_name,SUM(calls.duration) as duration FROM calls ,telephone WHERE to_t_no = telephone.t_no AND calls.duration >=500 group by telephone.cust_id, telephone.cust_name) T1 ON T0.cust_id = T1.cust_id A: Try to post the complete structure of your table and describe what you really need. If i understand correctly the problem the conditions that you are exposing are mutually exclusive. I think that there is not possible that any record match both conditions because the final query will look like this: SELECT cust_id,cust_name,SUM(calls.duration) as duration FROM calls ,telephone WHERE to_t_no = telephone.t_no AND calls.from_t_no = telephone.t_no AND calls.duration <=60 AND calls.duration >=500 group by telephone.cust_id, telephone.cust_name; If what you want is a general solution to make a "query over a query" you can use this kind of sentence: SELECT field1, field2 FROM (SELECT field1, field2, ..., fieldn FROM table WHERE condition) AS filteredTable WHERE anyCondition;
{ "language": "en", "url": "https://stackoverflow.com/questions/7545639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create multidimensional array Can anyone give me a sample/example of JavaScript with a multidimensional array of inputs? Hope you could help because I'm still new to the JavaScript. Like when you input 2 rows and 2 columns the output of it will be 2 rows of input and 2 columns of input. Like this: [input][input] [input][input] A: Hope the following code suits your requirement var row= 20; var column= 10; var f = new Array(); for (i=0;i<row;i++) { f[i]=new Array(); for (j=0;j<column;j++) { f[i][j]=0; } } A: function Array2D(x, y) { var array2D = new Array(x); for(var i = 0; i < array2D.length; i++) { array2D[i] = new Array(y); } return array2D; } var myNewArray = Array2D(4, 9); myNewArray[3][5] = "booger"; A: very simple var states = [,]; states[0,0] = tName; states[0,1] = '1'; states[1,0] = tName; states[2,1] = '1'; . . . states[n,0] = tName; states[n,1] = '1'; A: var size = 0; var darray = new Array(); function createTable(){ darray[size] = new Array(); darray[size][0] = $("#chqdate").val(); darray[size][1]= $("#chqNo").val(); darray[size][2] = $("#chqNarration").val() ; darray[size][3]= $("#chqAmount").val(); darray[size][4]= $("#chqMode").val(); } increase size var after your function. A: So here's my solution. A simple example for a 3x3 Array. You can keep chaining this to go deeper Array(3).fill().map(a => Array(3)) Or the following function will generate any level deep you like f = arr => { let str = 'return ', l = arr.length; arr.forEach((v, i) => { str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l); }); return Function(str)(); } f([4,5,6]) // Generates a 4x5x6 Array http://www.binaryoverdose.com/2017/02/07/Generating-Multidimensional-Arrays-in-JavaScript/ A: var numeric = [ ['input1','input2'], ['input3','input4'] ]; numeric[0][0] == 'input1'; numeric[0][1] == 'input2'; numeric[1][0] == 'input3'; numeric[1][1] == 'input4'; var obj = { 'row1' : { 'key1' : 'input1', 'key2' : 'input2' }, 'row2' : { 'key3' : 'input3', 'key4' : 'input4' } }; obj.row1.key1 == 'input1'; obj.row1.key2 == 'input2'; obj.row2.key1 == 'input3'; obj.row2.key2 == 'input4'; var mixed = { 'row1' : ['input1', 'inpu2'], 'row2' : ['input3', 'input4'] }; mixed.row1[0] == 'input1'; mixed.row1[1] == 'input2'; mixed.row2[0] == 'input3'; mixed.row2[1] == 'input4'; http://jsfiddle.net/z4Un3/ And if you're wanting to store DOM elements: var inputs = [ [ document.createElement('input'), document.createElement('input') ], [ document.createElement('input'), document.createElement('input') ] ]; inputs[0][0].id = 'input1'; inputs[0][1].id = 'input2'; inputs[1][0].id = 'input3'; inputs[1][1].id = 'input4'; Not real sure how useful the above is until you attach the elements. The below may be more what you're looking for: <input text="text" id="input5"/> <input text="text" id="input6"/> <input text="text" id="input7"/> <input text="text" id="input8"/> var els = [ [ document.getElementById('input5'), document.getElementById('input6') ], [ document.getElementById('input7'), document.getElementById('input8') ] ]; els[0][0].id = 'input5'; els[0][1].id = 'input6'; els[1][0].id = 'input7'; els[1][1].id = 'input8'; http://jsfiddle.net/z4Un3/3/ Or, maybe this: <input text="text" value="4" id="input5"/> <input text="text" value="4" id="input6"/> <br/> <input text="text" value="2" id="input7"/> <input text="text" value="4" id="input8"/> var els = [ [ document.getElementById('input5'), document.getElementById('input6') ], [ document.getElementById('input7'), document.getElementById('input8') ] ]; var result = []; for (var i = 0; i < els.length; i++) { result[result.length] = els[0][i].value - els[1][i].value; } Which gives: [2, 0] In the console. If you want to output that to text, you can result.join(' ');, which would give you 2 0. http://jsfiddle.net/z4Un3/6/ EDIT And a working demonstration: <input text="text" value="4" id="input5"/> <input text="text" value="4" id="input6"/> <br/> <input text="text" value="2" id="input7"/> <input text="text" value="4" id="input8"/> <br/> <input type="button" value="Add" onclick="add()"/> // This would just go in a script block in the head function add() { var els = [ [ document.getElementById('input5'), document.getElementById('input6') ], [ document.getElementById('input7'), document.getElementById('input8') ] ]; var result = []; for (var i = 0; i < els.length; i++) { result[result.length] = parseInt(els[0][i].value) - parseInt(els[1][i].value); } alert(result.join(' ')); } http://jsfiddle.net/z4Un3/8/ A: Quote taken from Data Structures and Algorithms with JavaScript The Good Parts (O’Reilly, p. 64). Crockford extends the JavaScript array object with a function that sets the number of rows and columns and sets each value to a value passed to the function. Here is his definition: Array.matrix = function(numrows, numcols, initial) { var arr = []; for (var i = 0; i < numrows; ++i) { var columns = []; for (var j = 0; j < numcols; ++j) { columns[j] = initial; } arr[i] = columns; } return arr; } Here is some code to test the definition: var nums = Array.matrix(5,5,0); print(nums[1][1]); // displays 0 var names = Array.matrix(3,3,""); names[1][2] = "Joe"; print(names[1][2]); // display "Joe" We can also create a two-dimensional array and initialize it to a set of values in one line: var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]]; print(grades[2][2]); // displays 89 A: you can create array follow the code below: var arraymultidimensional = [] arraymultidimensional = [[value1,value2],[value3,value4],[value5,value6]]; Result: [v1][v2] position 0 [v3][v4] position 1 [v5][v6] position 2 For add to array dinamically, use the method below: //vectorvalue format = "[value,value,...]" function addToArray(vectorvalue){ arraymultidimensional[arraymultidimensional.length] = vectorvalue; } Hope this helps. :) A: Declared without value assignment. 2 dimensions... var arrayName = new Array(new Array()); 3 dimensions... var arrayName = new Array(new Array(new Array())); A: I know this is ancient but what about... 4x4 example (actually 4x<anything>): var matrix = [ [],[],[],[] ] which can filled by: for (var i=0; i<4; i++) { for (var j=0; j<4; j++) { matrix[i][j] = i*j; } } A: I've created an npm module to do this with some added flexibility: // create a 3x3 array var twodimensional = new MultiDimensional([3, 3]) // create a 3x3x4 array var threedimensional = new MultiDimensional([3, 3, 4]) // create a 4x3x4x2 array var fourdimensional = new MultiDimensional([4, 3, 4, 2]) // etc... You can also initialize the positions with any value: // create a 3x4 array with all positions set to 0 var twodimensional = new MultiDimensional([3, 4], 0) // create a 3x3x4 array with all positions set to 'Default String' var threedimensionalAsStrings = new MultiDimensional([3, 3, 4], 'Default String') Or more advanced: // create a 3x3x4 array with all positions set to a unique self-aware objects. var threedimensional = new MultiDimensional([3, 3, 4], function(position, multidimensional) { return { mydescription: 'I am a cell at position ' + position.join(), myposition: position, myparent: multidimensional } }) Get and set values at positions: // get value threedimensional.position([2, 2, 2]) // set value threedimensional.position([2, 2, 2], 'New Value') A: Create uninitialized multidimensional array: function MultiArray(a) { if (a.length < 1) throw "Invalid array dimension"; if (a.length == 1) return Array(a[0]); return [...Array(a[0])].map(() => MultiArray(a.slice(1))); } Create initialized multidimensional array: function MultiArrayInit(a, init) { if (a.length < 1) throw "Invalid array dimension"; if (a.length == 1) return Array(a[0]).fill(init); return [...Array(a[0])].map(() => MultiArrayInit(a.slice(1), init)); } Usage: MultiArray([3,4,5]); // -> Creates an array of [3][4][5] of empty cells MultiArrayInit([3,4,5], 1); // -> Creates an array of [3][4][5] of 1s A: I came up with let rows = 5; let cols = 4; let defaultValue = 0; Array(rows).fill([]).map((x) => x = Array(cols).fill(defaultValue)); resulting into (5) [Array(4), Array(4), Array(4), Array(4), Array(4)] 0: (4) [0, 0, 0, 0] 1: (4) [0, 0, 0, 0] 2: (4) [0, 0, 0, 0] 3: (4) [0, 0, 0, 0] 4: (4) [0, 0, 0, 0] length: 5 A: I've written a one linear for this: [1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0); I feel however I can spend more time to make a JSON.parse(JSON.stringify())-free version which is used for cloning here. Btw, have a look at my another answer here. A: I know this is an old question but here is something to try: Make your multidimensional array, and place it inside an html tag. This way you can precisely aim your array'd input: //Your Holding tag for your inputs! <div id='input-container' class='funky'></div> <script> //With VAR: you can seperate each variable with a comma instead of: //creating var at the beginning and a semicolon at the end. //Creates a cleaner layout of your variables var arr=[['input1-1','input1-2'],['input2-1','input2-2']], //globall calls these letters var so you dont have to recreate variable below i,j ; //Instead of the general 'i<array.length' you can go even further //by creating array[i] in place of 'i<array.length' for(i=0;arr[i];i++){ for(j=0;arr[i][j];j++){ document.getElementById('input-container').innerHTML+= "<input class='inner-funky'>"+arr[i][j]+"</input>" ; }} </script> Its simply a neater way to write your code and easier to invoke. You can check my demo here!
{ "language": "en", "url": "https://stackoverflow.com/questions/7545641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "159" }
Q: JSON parsing error with CouchDB design document: unclosed string due to indentation whitespaces? I use the following CouchDB design document for testing purposes. I use carriage return \n and tabs \t to indent my Javascript code. As far as I understand JSON, I think that whitespaces in those places are OK. But Ruby couchrest fails parsing that and JSLint too. I have to strip the \n and \t out of the design document before parsing it. Why is that ? The JSON introduction page on json.org mentions that "Whitespace can be inserted between any pair of tokens. " It is a little bit difficult to render tabs here so I have included a parsed string with \n and \t. { "_id": "_design/test", "views": { "all": { "map": "function(doc) { if (doc.nom) emit(doc._id, doc); }" }, "asin_doc": { "map": "function(doc) { if (doc.category) emit(doc.asin, doc); }" }, "asin": { "map": "function(doc) { if (doc.category) emit(doc.asin, null); }" } } } The same document in a long string (Ruby): "{\n\t\"_id\": \"_design/test\",\n\t\"views\": {\n\t\t\"all\": {\n\t\t\t\"map\": \"function(doc) {\n\t\t\t\tif (doc.nom) emit(doc._id, doc);\n\t\t\t}\"\n\t\t},\n\t\t\"asin_doc\": {\n\t\t\t\"map\": \"function(doc) {\n\t\t\t\tif (doc.category) emit(doc.asin, doc);\n\t\t\t}\"\n\t\t},\n\t\t\"asin\": {\n\t\t\t\"map\": \"function(doc) {\n\t\t\t\tif (doc.category) emit(doc.asin, null);\n\t\t\t}\"\n\t\t}\n\t}\n}\n" JSLint tells me that there is a problem at line 5 character 20. Problem at line 5 character 20: Unclosed string. "map": "function(doc) { Problem at line 5 character 20: Stopping. (25% scanned). JSON: bad. I can't see where the string is not properly closed. Any idea ? A: Newline and tab are not allowed in a string. See the JSON RFC, specifically: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF EDIT: What json.org is talking about, I think, is this: Insignificant whitespace is allowed before or after any of the six structural characters. The "structural characters" are: [ ] { } : ,
{ "language": "en", "url": "https://stackoverflow.com/questions/7545643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with "multiple definition" Say I have a very little header file like so: #ifndef A_H_ #define A_H_ void print(); int getInt() { //ERROR HERE return 5; } #endif /* A_H_ */ And a source file implementing print like so: #include "a.h" void print() { printf("%d\n",getInt()); //WARNING HERE } And my main() function code: #include <stdio.h> #include <stdlib.h> #include "a.h" int main(void) { print(); return EXIT_SUCCESS; } Notice that getInt is defined in the header file and invoked in the source file. When I compile I get multiple definition ofgetInt'` in the header file, but I've only defined it once! The source file (.c) only invokes it. What is my problem? Thanks A: You're probably including your header file into another source file too. You may try to move the definition to the .c file or declare getInt() as inline. A: You should move getInt() into a.c, i.e. a.h: #ifndef A_H_ #define A_H_ void print(void); int getInt(void); #endif /* A_H_ */ a.c: #include <stdio.h> #include "a.h" void print(void) { printf("%d\n",getInt()); } int getInt(void) { return 5; } main.c: #include <stdio.h> #include <stdlib.h> #include "a.h" int main(void) { print(); return EXIT_SUCCESS; } As a rule of thumb, interfaces (i.e. prototypes for externally accessible function, plus related typedefs and constants etc) belong in .h files, while omplementations (i.e. actual function definitions, plus private (static) functions and other internal stuff) belong in .c files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLAlchemy: Re-saving model's unique field after trying to save non-unique value In my SQLAlchemy app I have the following model: from sqlalchemy import Column, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) class MyModel(declarative_base()): # ... label = Column(String(20), unique=True) def save(self, force=False): DBSession.add(self) if force: DBSession.flush() Later in code for every new MyModel objects I want to generate label randomly, and just regenerate it if the generated value is already exist in DB. I'm trying to do the following: # my_model is an object of MyModel while True: my_model.label = generate_label() try: my_model.save(force=True) except IntegrityError: # label is not unique - will do one more iteration # (*) pass else: # my_model saved successfully - exit the loop break but get this error in case when first generated label is not unique and save() called on the second (or later) iteration: InvalidRequestError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (IntegrityError) column url_label is not unique... When I add DBSession.rollback() in the position (*) I get this: ResourceClosedError: The transaction is closed What should I do to handle this situation correctly? Thanks A: If your session object rolls back essentially you have to create a new session and refresh your models before you can start again. And if you are use zope.sqlalchemy you should be using transaction.commit() and transaction.abort() to control things. So your loop would look something like this: # you'll also need this import after your zope.sqlalchemy import statement import transaction while True: my_model.label = generate_label() try: transaction.commit() except IntegrityError: # need to use zope.sqlalchemy to clean things up transaction.abort() # recreate the session and re-add your object session = DBSession() session.add(my_model) else: break I've pulled the use of the session object out of the object's save method here. I am not entirely sure how the ScopedSession refreshes itself when being used at the class level as you have done. Personally, I think embedding SqlAlchemy stuff inside your models doesn't really work well with SqlAlchemy's unit of work approach to things any how. If your label object really is a generated and unique value, then I would agree with TokenMacGuy and just use a uuid value. Hope that helps. A: Databases don't have a consistent way of telling you why a transaction failed, in a form that is accessible to automation. You can't generally try the transaction, and then retry because it failed for some particular reason. If you know of a condition that you want to work around (like a unique constraint), what you have to do is check the constraint yourself. In sqlalchemy, that's going to look something like this: # Find a unique label label = generate_label() while DBsession.query( sqlalchemy.exists(sqlalchemy.orm.Query(Model) .filter(Model.lable == label) .statement)).scalar(): label = generate_label() # add that label to the model my_model.label = label DBSession.add(my_model) DBSession.flush() edit: Another way to answer this is that you shouldn't automatically retry the transaction; You could instead return an HTTP status code of 307 Temporary Redirect (with some salt in the Redirected URL) so that the transaction really is started fresh. A: I faced similar problem in my webapp written in Pyramid framework. I found a bit different solution for that problem. while True: try: my_model.label = generate_label() DBSession.flush() break except IntegrityError: # Rollback will recreate session: DBSession.rollback() # if my_model was in db it must be merged: my_model = DBSession.merge(my_model) The merge part is crucial if the my_model was stored before. Without merge session would be empty so flush would not take any action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Changing class of object to subclass (& general questions on inheritance) Suppose I have a class clubMember and a class user. Only club members can be users, users have login data additional to other club member vars, and club members’ characteristics influence what rights as users they have, so user extends clubMember. Now suppose a club member wants to use the grails servlet I am currently programming. Creating a new user instance would lead to a double entry, plus I would lose all the links existing between the previous member and other classes. So perhaps converting the type of the clubMember to user would be the best way to proceed? If so, how could that be done (in Groovy)? Or, could you recommend me an implemention method other than subclasses? Ideally, requests such as “list all members” should also return users, is this even the case with subclasses? (Edit: It is the case in my grails app) Related: Java: Creating a subclass object from a parent object, Is it ever valid to convert an object from a base class to a subclass A: If you want one value of a certain type to become a new value of a different type, then you have in Groovy basically two ways: * *asType: In for example "foo as Bar" Groovy will convert the expression to "foo.asType(Bar.class)", which means you can add an asType method to the class of foo to do the conversion for you. In your case you would add asType to User and let it handle ClubMember. *explicit or implicit cast: In "(Bar) collection" Groovy will look for a constructor in Bar that can take a fitting number of arguments for the collection and will then create a new Bar object out of it. Actually it is not limited to collections, an array will do as well. Anyway... In your example you could add a constructor that takes ClubMember to User and then cast the collection containing the member you want to convert. On a side node... if you assign the collection to a Bar typed variable, this conversion will also happen (implicit cast). If you want the conversion method (I am so free and call the constructor a conversion method as well) not in the class, you can still use a category for the asType version or runtime meta programming to add an asType method as you need or a constructor as you need. But what Tim suggested in his comment, to have ClubMember as member of User seems really to be the most easy version
{ "language": "en", "url": "https://stackoverflow.com/questions/7545648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning a result I want a JavaScript function that posts to a php, and returns the value, so that calling the function from another function in JavaScript gives me the value. To illustrate better please look at my current code: function sumValues(number1, number2) { var return_val; $.post("sum_values.php", {number1: number1, number2: number2}, function(result) { return_val = result; }); return return_val; } However, the above is returning undefined. If I put alert(result) inside the function part in $.post, I can see the result. However if I call the function from another JavaScript file the return value return_val is 'undefined'. How can I put the result from $.post inside return_val so that the function can return it? A: AJAX is asynchronous meaning that by the time your function returns results might not have yet arrived. You can only use the results in the success callback. It doesn't make sense to have a javascript performing an AJAX request to return values based on the results of this AJAX call. If you need to exploit the results simply invoke some other function in the success callback: function sumValues(number1, number2) { $.post("sum_values.php", { number1: number1, number2: number2 }, function(result) { callSomeOtherFunction(result); }); } and inside the callSomeOtherFunction you could show the results somewhere in the DOM. A: $.post is asynchronous by default (docs). You could either pass the async:false option (blocks the browser, not a good user experience) or you should consider using callback functions (better IMHO). function sumValues(number1, number2,callback) { $.post("sum_values.php", {number1: number1, number2: number2},callback); } sumValues(1,3,function(result){ doSomething(result); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7545649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Job scheduling using standard Java libraries As mentioned in the tags, this is homework, using only standard java libraries. The task is to create a program that schedules orders (which consist of pizzas) to be cooked in different ovens. Orders have a dealine, which must be met and pizzas have a cook time and a cooldown time, inherently all pizzas must be cooked by the deadline but cannot be cooked so early that their time out of the oven exceeds the cooldown time. If it is determined that it is not possible to fulfil the order by the deadline an exception is thrown. The main problem I cannot get my head around is how would I make the program reschedule the ovens to fit a new order in. I cannot think of how to start this and would really appreciate any help! A: You can start reading earliest deadline first scheduling. It seem that your pizza processing time (cook + cool + etc.) can be calculated beforehand, so PriorityQueue could be helpful. The PizzaOrder would implement Comparable interface, which compares the deadline of the order. A: A good place to start is to turn that middle paragraph into objects with behavior and state defied, eg class Order List<Pizza> pizzas; class Oven int maxPizzas; List<Pizza> cooking; cook(pizza: Pizza); class Pizza int cookTimeMins; int coolTimeMins; long cookTimeStart; class PizzaShop List<Oven> ovens; List<Order> orders; scheduleOrder(order: Order) throws Exception From there start pseudo coding what you want to happen in the various methods. Start with those building blocks and you will find the problem becomes easier to solve when not looking at the problem as a whole, but in small chunks. A: It is hard to know with the information you provide, but it seems it could be a good scenario to use a rule engine such as JBoss Rules (Drools), if you want to experiment with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a User control in dispatcher and add it to a control in the UI I have a long time processing operation, and for that it has to be done in the backGround, But the problem is: * *When I create the user control, and then add it to the UI, (listView) control, WPF doesn't show the UC (user control), but the listView seems to be populated withe the same number of UC i created. I used the backgroundWorker, then i used the Dispatcher of the listView, then the main Dispatcher, but all with the same problem i wonder if i can use the UIThread for that, but i dont know how. My code is: private void btn_click(object sender, System.Windows.RoutedEventArgs e) { string path = fileSourcesCombo.SelectedItem.ToString(); converter = getConverter(path); this.Dispatcher.BeginInvoke(new Action(delegate() { System.Data.DataTable dataTable = converter.getDataTable(); dataGrid.Dispatcher.Invoke(new Action(delegate() { dataGrid.ItemsSource = dataTable.DefaultView; } )); List<MyAttribute> attributes = converter.attributes; foreach (MyAttribute attribute in attributes) { string name = attribute.name; string type = attribute.type; CustomAttribute customAtt = new CustomAttribute(name, type); ListViewControl.Dispatcher. Invoke(new Action(delegate() { ListViewControl.Items.Add(customAtt); })); } } ),System.Windows.Threading.DispatcherPriority.Background); } * *Converter.getDataTable() takes long time. *dataGrid.Dispatcer.Invoke works properly, because it updates and exciting control. *ListViewControl.Dispatcher doesn't seem to work properly, neither this.Dispatcher as i said before there is no compiling error generated, it's just that the list view seems to be populated with empty items on all of the method i tried. EDIT : when i changed the ListView into a ListItem it worked, but i dont know why?? any how i still would like to use the listView control instead.. This is the Xaml code where it works: <Grid Margin="8,0"> <ListView x:Name="testpanel" Margin="8" BorderThickness="0" DisplayMemberPath="" Style="{DynamicResource SimpleListBox}" ItemContainerStyle="{DynamicResource SimpleListBoxItem}"> </ListView> </Grid> if i remover the DynemicResource from : ItemContainerStyle , it doesn't work A: Please post the XAML for your ListView. Are you possibly missing a DisplayMemberPath? That is how it would behave if it has Items but does not know what to display. A: It's not exactly possible to tell what is to blame but here are a few things that may or may not help: * *If you do not use the ListView.View you should just use a ListBox. *If you add UI-Elements to the control you should not use a DisplayMemberPath. *Everything inside a BeginInvoke should already be on the UI-thread, so those additional dispatcher-calls inside should be redundant. (Read the threading todel reference) *If converter = getConverter(path) is being called on a Background thread that part where you create a thread is either missing from your code or weird things are happening, i.e. calling an event-handler in code. *The control in your XAML is called testpanel but in the code you call ListViewControl.Items.Add, i hope that's just some inconsistency in you code-posting. *The ItemContainerStyle could contain all sorts of things that would mess things up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How concurrency implementation in Nhibernat 3.1 I have a project by nhibernate 3.1 . I need to concurrency implementation in project. I Add "Version" to hbm file : <class name="Person" table="Person_Person" > <id name="Id" type="Int64" unsaved-value="0" > <generator class="native" /> </id> <version name="Version" /> <property name="FirstName" column="FirstName" type="String(255)" update="true" insert="true" access="property" not-null="false" /> <property name="LastName" column="LastName" type="String(255)" update="true" insert="true" access="property" not-null="false" /> </class> Also i add a version field to entity : virtual protected int Version { get; set; } Also i add a version field to DataBase by int type. This implementation is correct only for once. It just works when version value in database is '0' . After first update this row in table, this value change to '1'. But for next update when version field is not '0' for example '1' , throw exception by this message: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [RCISP.Domain.Entities.Person#4] What should I do? Stack trace is : at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session) at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Int32[] dirtyFields, Boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object obj, Object rowId, ISessionImplementor session) at NHibernate.Action.EntityUpdateAction.Execute() at NHibernate.Engine.ActionQueue.Execute(IExecutable executable) at NHibernate.Engine.ActionQueue.ExecuteActions(IList list) at NHibernate.Engine.ActionQueue.ExecuteActions() at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) A: Looks like you doing it right. It should work. Try following: * *Make sure that no other session is modifying the same object (StaleObjectStateException that you getting might be legitimate). *Make sure that nothing in the database itself is updating Version column (trigger for example) *Make sure that nothing in your code is changing the Version property. It is for NHibernate use only. *Remove unsaved-value="0" from id mapping. See if it works after that. *Update your answer with a stack trace and the actual Version values in the database and in the object (right before you save the object). A: I believe you have to turn on dynamic-update to get optimistic concurrency checking to work. See this blog entry. <class name="Person" table="Person_Person" dynamic-update="true">
{ "language": "en", "url": "https://stackoverflow.com/questions/7545663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a CPAN module for converting seconds to English? Is there a CPAN module that can convert a number of seconds to a human-readable English description of the interval? secToEng( 125 ); # => 2 min 5 sec secToEng( 129_600 ); # => 1 day 12 h The format isn't important as long as it's human-readable. I know that it would be trivial to implement. A: Since Perl v5.9.5, the modules Time::Seconds and Time::Piece are part of the core Perl distribution. So you can use them without installing additional modules. perl -MTime::Seconds -e 'my $s=125; my $ts=new Time::Seconds $s; print $ts->pretty, "\n"' # 2 minutes, 5 seconds perl -MTime::Seconds -e 'my $s=129_600; my $ts=Time::Seconds->new($s); print $ts->pretty, "\n"' # 1 days, 12 hours, 0 minutes, 0 seconds You can also use stuff like $ts->weeks, $ts->minutes, etc. A: I wasn't able to find such code a while back, so I wrote these two routines. The second sub uses the first and does what you are looking for. #----------------------------------------------------------- # format_seconds($seconds) # Converts seconds into days, hours, minutes, seconds # Returns an array in list context, else a string. #----------------------------------------------------------- sub format_seconds { my $tsecs = shift; use integer; my $secs = $tsecs % 60; my $tmins = $tsecs / 60; my $mins = $tmins % 60; my $thrs = $tmins / 60; my $hrs = $thrs % 24; my $days = $thrs / 24; if (wantarray) { return ($days, $hrs, $mins, $secs); } my $age = ""; $age .= $days . "d " if $days || $age; $age .= $hrs . "h " if $hrs || $age; $age .= $mins . "m " if $mins || $age; $age .= $secs . "s " if $secs || $age; $age =~ s/ $//; return $age; } #----------------------------------------------------------- # format_delta_min ($seconds) # Converts seconds into days, hours, minutes, seconds # to the two most significant time units. #----------------------------------------------------------- sub format_delta_min { my $tsecs = shift; my ($days, $hrs, $mins, $secs) = format_seconds $tsecs; # show days and hours, or hours and minutes, # or minutes and seconds or just seconds my $age = ""; if ($days) { $age = $days . "d " . $hrs . "h"; } elsif ($hrs) { $age = $hrs . "h " . $mins . "m"; } elsif ($mins) { $age = $mins . "m " . $secs . "s"; } elsif ($secs) { $age = $secs . "s"; } return $age; } A: The DateTime modules are what you want. DateTime::Duration and DateTime::Format::Duration will do what you need. A: It turns out that Time::Duration does exactly this. $ perl -MTime::Duration -E 'say duration(125)' 2 minutes and 5 seconds $ perl -MTime::Duration -E 'say duration(129_700)' 1 day and 12 hours From the synopsis: Time::Duration - rounded or exact English expression of durations Example use in a program that ends by noting its runtime: my $start_time = time(); use Time::Duration; # then things that take all that time, and then ends: print "Runtime ", duration(time() - $start_time), ".\n"; Example use in a program that reports age of a file: use Time::Duration; my $file = 'that_file'; my $age = $^T - (stat($file))[9]; # 9 = modtime print "$file was modified ", ago($age); A: DateTime can be used: #!/usr/bin/env perl use strict; use warnings; use DateTime; use Lingua::EN::Inflect qw( PL_N ); my $dt = DateTime->from_epoch( 'epoch' => 0 ); $dt = $dt->add( 'seconds' => 129_600 ); $dt = $dt - DateTime->from_epoch( 'epoch' => 0 ); my @date; push @date, $dt->days . PL_N( ' day', $dt->days ) if $dt->days; push @date, $dt->hours . PL_N( ' hour', $dt->hours ) if $dt->hours; push @date, $dt->minutes . PL_N( ' minute', $dt->minutes ) if $dt->minutes; push @date, $dt->seconds . PL_N( ' second', $dt->seconds ) if $dt->seconds; print join ' ', @date; Output 1 day 12 hours
{ "language": "en", "url": "https://stackoverflow.com/questions/7545664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: git: work with git-svn when there are merges As far as I understand, git-svn does not support pushing merge commits. Is there a way to make it work with such commits? We have tried to use rebase to create a linear history. However, this fails with conflicts on whitespace errors. Is there a way of linearizing the history so there are no conflicts? A: The simplest way of rebasing merged commits to svn is to squash them: assuming we rebase branch dev to trunk git checkout trunk git merge --squash dev you might have to fix real merge conflicts between trunk and dev. At the end you have one commit which you can well git svn dcommit. The downside of this method is that you loose granularity of your commits in SVN. If this is a problem, you could employ a rebase-style merging strategy for git (e.g. http://unethicalblogger.com/2010/04/02/a-rebase-based-workflow.html ). A: It's not straightforward, but possible. * *Check out your feature branch $ git checkout feature1 *Create a Subversion branch, preferrably with the same name and rebase your local git branch $ git svn branch feature1 $ git rebase remotes/feature1 *When you push your changes, they will go to the Subversion branch, not to the trunk. $ git svn dcommit The only way to do e merge that I am aware of is using a temporary SVN checkout and using svn merge. For merges that can be performed automatically, without conflicts, scripting the last steps (SVN repository lookup, temporary checkout, merge) has worked well for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting Grid border in WP7 I'm trying to create grid with borders but with this code, only the first cell has border: <Grid Margin="24,96,24,288" d:LayoutOverrides="GridBox"> <Grid.RowDefinitions> <RowDefinition Height="0.150*"/> <RowDefinition Height="0.150*"/> <RowDefinition Height="0.150*"/> <RowDefinition Height="0.150*"/> <RowDefinition Height="0.150*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.150*"/> <ColumnDefinition Width="0.150*"/> <ColumnDefinition Width="0.150*"/> <ColumnDefinition Width="0.150*"/> <ColumnDefinition Width="0.150*"/> <ColumnDefinition Width="0.150*"/> <ColumnDefinition Width="0.150*"/> </Grid.ColumnDefinitions> <Border BorderBrush="#FFFFFF" BorderThickness="1"/> </Grid> How do I create solid border for all the cells? A: Wrap the Grid into a Border : <Border BorderBrush="#FF0000" BorderThickness="5" Margin="24,96,24,288"> <Grid> .... </Grid> </Border> The way you did was adding a Border-element into the Grid-Control - so of course the first cell (if you don't set Grid.Row/Grid.Column both will default to 0) was drawn with one ;) If you want to create a border for each cell then you have to wrap each content into a Border-element or you have to edit the template for the grid. As another alternative you could try to style the Grid (here is a nice article) Here is another question from this site concerning a similar thing: Styling a WPF layout grid background To make this a bit clearer the easiest (if not most refined) way to get a (even) border for each cell is to really set the boarder for each cell AND for the grid yourself (either in markup or code) - here is a simplified example: <Border BorderBrush="#FF0000" BorderThickness="2" Grid.Row="0" Grid.Column="0" Margin="24,96,24,288" > <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Border BorderBrush="#FF0000" BorderThickness="2" Grid.Row="0" Grid.Column="0"/> <Border BorderBrush="#FF0000" BorderThickness="2" Grid.Row="0" Grid.Column="1"/> <Border BorderBrush="#FF0000" BorderThickness="2" Grid.Row="1" Grid.Column="0"/> <Border BorderBrush="#FF0000" BorderThickness="2" Grid.Row="1" Grid.Column="1"/> </Grid> </Border>
{ "language": "en", "url": "https://stackoverflow.com/questions/7545674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to sort multiple sorted data set from DB in C#? I have a partitioned table in SQL SERVER, there is a clustered index on ID, and the table is partitioned by period_key. The ID is unique inside partition, but not unique cross partitions. What I need is to find all the unique ID. The simplest way is just use select unique ID from tab But that need to sort the DB in database which need quit a lot of temp disk, so lots of disk IO is required. Since the system is already IO bounded, I am thinking about cut the disk IO. Since we can read each partition in order by using the cluster index, suppose we have 10 partition, we can read one row from each partition, then compare them, and output the record with the min ID, say from partition X, and then read the next row from the partition X. And again compare these 10 rows, output the record with the min ID, etc. Just like external sort. I don't have experience in C#, but know java. Could anyone give me some idea how to implement it in c#? A: OK, if the requirement is to bypass the sort on the DB server side, and rather work out if an ID is unique or not on the client side, you can do something like this - select all ID values (no distinct in the query): SELECT ID FROM tab Then loop through all the values, adding them to a List. When that's done, you can ask the list to give back a version of itself with the duplicates removed. Here's a simplistic example: List<int> allIDs = new List<int>(); foreach (DataRow row in someDataSet.Tables[0].Rows) { allIDs.Add((int) row["ID"]); } List<int> uniqueIDs = allIDs.Distinct(); Disclaimer - I wrote that off the top of my head, so it might contain errors. This post contains a faster implementation based on HashSet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Swapping li elements between multiple un-ordered lists using jQuery I'm trying to allow the user to move the 'post-it' notes from one un-ordered list of tasks to another. Ideally when the user drags the task it should be removed from its current container and appended to the new list. Pseudo HTML <ul class="task-bucket" id="backlog-tasks"> <!-- task a --> <!-- task b --> <!-- task c --> </ul> <ul class="task-bucket" id="do-tasks"> <!-- task d --> </ul> <ul class="task-bucket" id="doing-tasks"> <!-- task e --> </ul> <ul class="task-bucket" id="done-tasks"> <!-- task f --> </ul> I'd like for tasks to be draggable between lists, e.g. when task e is finished it can be dragged into #done-tasks. If you have a solution, feel free to build it on top of: http://jsfiddle.net/Zwedh/2/ Working solution: http://jsfiddle.net/RD5M6/3/ A: $(function(){ $('.task-bucket').sortable({ connectWith: '.task-bucket' }); $('.task').draggable({ connectToSortable: '.task-bucket' }); $('ul', 'li').disableSelection(); }) The solution is much simpler than I had originally anticipated! http://jqueryui.com/demos/sortable/ A: Check out jQuery UI's Droppable
{ "language": "en", "url": "https://stackoverflow.com/questions/7545677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharing Methods Between Child Objects I'm trying to share methods between objects that belong to a parent object. I have a main object, which has child objects that handle different tasks. These are created using the main objects constructor: class engine { public function __construct() { $this->db = new db(); $this->url = new url(); $this->template = new template(); } } Here's an example of how I would use my main object: $engine = new engine(); $engine->db->connect(); $engine->url->parse(); $engine->template->render(); How could the child objects access the methods of the other children (e.g. how could template->render() call url->parse()) ? A: You can set static property of a class and call it staticaly: static public function parse() { <some code> } and call it like Url::parse(); from $template->render();
{ "language": "en", "url": "https://stackoverflow.com/questions/7545679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: issues requiring files in php from multiple locations I have a single PHP file that i require in many different php files. The PHP file stores DB info and also requires another file called something.php.... Now, say I stored the PHP file (with db info) called my_db_info.php in a folder called config. I then have another PHP file that was stored in two folders above the config folder, called all_functions. Now to require the file with db info I'd write require('folder1/config/my_db_info.php'); Now this would require my_db_info.php fine but the file required in my_db_info.php (something.php) will not be included which will cause a fatal error. so when I test the php in the all_functions folder, i get a fatal error telling me that the file (something.php) required in the actual db file (my_db_info.php) could not be found. then, when I alter the my_db_info.php file and change the require line to decrease how many folders it goes up or down, example: require('../something.php'); To require('../../something.php'); It seems to work. But i have to change the folder up/down count to what the main file (in the all_functions folder) is. so as if i was requiring something.php in that file... Which means, when i want to require my_db_info.php into another file, which is in a completely different location to the file in the all_functions folder (5 folders up for example), I will have to make another my_db_info.php for it to all work properly.... Why does this happen, and is there any way I can fix this? Thanks A: To me, it seems the easiest thing for you to do, is the directly include the PHP files rather than giving the relative path (which is how you're including them). Try using $_SERVER['DOCUMENT_ROOT'] (which will give you something like /home/username/htdocs) If I understand your setup correctly, you have the following 2 directories in a directory (possibly in the root): / /all_functions /config The instead of including with multiple include("../my_db_info.php"); change to include($_SERVER['DOCUMENT_ROOT']."/config/my_db_info.php"); and repeat as needed be for other directories. If you do it this way, it will work for multiple directories away from where the config+all_functions directories are located. Edit (in response to comment) If $_SERVER['DOCUMENT_ROOT'] is unavailable, then you could always manually write the document root, then define it as a constant, then call it in each script. Eg. define(rootpath, "/home/username/htdocs"); include(rootpath."/config/my_db_info.php"); Then you can use rootpath as your defined constant in my_db_info.php (etc) if needed be, the downside is that you'd have to write this in every script - though fingers crossed that $_SERVER['DOCUMENT_ROOT'] is available for you. A: 2021 Update Now I prefer to use namespace with autoload instead of traditional importing. <?PHP namespace Whatever; class Important {...} <?PHP use App\Whatever; $important = new Important(); https://www.php.net/manual/en/language.namespaces.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7545683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# 'as' Keyword and Derived Classes I am working my way through "Sams Teach Yourself C# in 21 Days", obviously, this makes me a novice programmer. Please don't be too harsh. So far, being objective, I've feel I've done quite well understanding the topics. I am not looking for the answer, but hopefully be pointed in the right direction. :) Anyway, I have this code: // EXERCISE 11.4 using System; public class Person { public string Name; public Person() { } public Person( string nm ) { Name = nm; } public virtual void displayFullName() { Console.WriteLine( "Person {0}", Name ); } } class Employee : Person { //public ushort hireYear; public Employee() : base() { } public Employee( string nm ) : base( nm ) { } public override void displayFullName() { Console.WriteLine( "Employee: {0}", Name ); } } class Contractor : Person { //public string Company; public Contractor() : base() { } public Contractor( string nm ) : base( nm ) { } public override void displayFullName() { Console.WriteLine( "Contractor: {0}", Name ); } public void DisplayCompany() { Console.WriteLine( "Company: {0}", Company ); } } class MyApplication { public static void Main() { Person [ ] myCompany = new Person[5]; int Counter = 0; string Buffer, Buffer2; do { do { Console.Write( "\nEnter \'c\' for Contractor, \'e\' for Employee then press ENTER: " ); Buffer = Console.ReadLine(); } while( Buffer == "" ); if( Buffer[0] == 'c' || Buffer[0] == 'C' ) { Console.Write( "\nEnter the contractor\'s name: " ); Buffer = Console.ReadLine(); // DO OTHER CONTRACTOR STUFF Contractor Contr = new Contractor( Buffer ); myCompany[Counter] = Contr as Person; } else if( Buffer[0] == 'e' || Buffer[0] == 'E' ) { Console.Write( "\nEnter the employee\'s name: " ); Buffer = Console.ReadLine(); // DO OTHER EMPLOYEE STUFF Employee emp = new Employee( Buffer ); myCompany[Counter] = emp as Person; } else { Person pers = new Person( "Not an Employee or Contractor" ); myCompany[Counter] = pers; } Counter++; } while( Counter < 5 ); Console.WriteLine( "\n\n\n===========================" ); for( Counter = 0; Counter < 5; Counter++ ) { if( myCompany[Counter] is Employee ) { Console.WriteLine( "Employee: {0}", myCompany[Counter].Name ); } else if( myCompany[Counter] is Contractor ) { Console.WriteLine( "Contractor: {0}.", myCompany[Counter].Name ); } else { Console.WriteLine( "Person: {0}", myCompany[Counter].Name ); } } Console.WriteLine( "===========================" ); Console.Read(); } } In the excercise I've to modify the Contractor or Employee class and add either a hireYear or Company data member respectively. Which would look like this: class Employee : Person { public ushort hireYear; public Employee() : base() { } public Employee( string nm ) : base( nm ) { } public Employee( string nm, ushort hy ) : base( nm ) { hireYear = hy; } public override void displayFullName() { Console.WriteLine( "Employee: {0}", Name ); } } OR class Contractor : Person { public string Company; public Contractor() : base() { } public Contractor( string nm ) : base( nm ) { } public Contractor( string nm, string c ) : base( nm ) { Company = c; } public override void displayFullName() { Console.WriteLine( "Contractor: {0}", Name ); } public void DisplayCompany() { Console.WriteLine( "Company: {0}", Company ); } } The changes to the MainApplication would be: if( Buffer[0] == 'c' || Buffer[0] == 'C' ) { string Buffer2; Console.Write( "\nEnter the contractor\'s name: " ); Buffer = Console.ReadLine(); Console.Write( "\nEnter the contractor\'s company: " ); Buffer2 = Console.ReadLine(); Contractor Contr = new Contractor( Buffer, Buffer2 ); myCompany[Counter] = Contr as Person; } OR else if( Buffer[0] == 'e' || Buffer[0] == 'E' ) { string BufferHireYear; Console.Write( "\nEnter the employee\'s name: " ); Buffer = Console.ReadLine(); Console.Write( "\nEnter the year employee was hired: " ); BufferHireYear = Console.ReadLine(); Employee emp = new Employee( Buffer, BufferHireYear ); myCompany[Counter] = emp as Person; } I am quite happy until this point, I think. My confusion starts when I need to print out the results. My thinking is that when the objects are "cast" back into the myCompany array, they are added as objects of type person. The class for Person does not contain the data members Company or HireYear, so how can I access those data members? Thank-you for reading through this posting, I am sure someone will be able to help. I've got to learn. Matt A: You need to cast your objects back to Employee so that you can use the members defined by Employee. Employee emp = (Employee)myCompany[Counter]; If myCompany[Counter] isn't actually an Employee, this will throw an InvalidCastException. When putting Employees in the array, you don't need to cast, since Employee is always convertible to Person. You only need to cast explicitly if there is a chance that it won't work. A: If you need printing/handling that is special for each sub-type you can special case the handling of each sub type in the output code. foreach (Person person in myCompany) { if (person is Employee) { Employee e = (Employee)person; Console.WriteLine("HireYear: {0}", e.HireYear); // etc.. Another option would be for the Person base class to offer an abstract description property and each sub-class could override and then the output functions could call description when printing. A: I may be jumping ahead here, but you may be interested at this point in the topic of "polymorphism". Taking advantage of polymorphism here, instead of having the calling code retrieve and print the individual details based on the type of Person, you simply tell the person to print or retrieve their own details based on what kind of person they are. So in this case, if you make a virtual function (similar to displayFullName) that prints out the full details of this instance, you can just call that on the person, and it will execute the appropriate version based on the actual type of Person on which it was invoked. However, you can also cast the instance to the specific type and access it's members as described in the other answers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android: Google APIs (Android API 13) I am trying to install Third party add-ons using Android SDK. Below is what I am trying to install. Android SDK >> Available packages >> Third party Add-ons >> Google Inc. >> Google APIs by Google Inc., Android API 13, revision 1 It gives me error like this. Downloading Google APIs by Google Inc., Android API 13, revision 1 File not found: C:\Program Files (x86)\Android\android-sdk\temp\google_apis-13_r01.zip (Access is denied) I am not sure what is the problem. Can you please help me to install this? Thanks. A: You need to run the SDK manager as Administrator for it to install updates otehrwise Windows refuses to let it create files. A: I got a way to remove this error. I just applied read & write permissions to tmp folder of android sdk, and it worked! Thanks for your answers. A: If you can, try moving the SDK out of C:\Program Files (x86) A: If your SDK manager is installed as a Eclipse plugin and don't know how to 'run as administrator'. Try go to 'C:\Program Files (x86)\Android\android-sdk', right click 'SDK Manager.exe' -> 'run as administrator' should solve
{ "language": "en", "url": "https://stackoverflow.com/questions/7545686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use array.push on array with a defined index? How do I use array.push to add an object with a custom index in an array? I have this script but it doesnt work. Chrome's Javascript console is not outputting errors var tempList = new Array(); $('#add').click(function(){ var split = $('#itemid').val().split('_'); var itemid = split['0']; var lbs = $('#lbs').val(); tempList.push(tempList['itemid'] = lbs); for (var i; i<=(tempList.length - 1); i++){ if (i==0){ var list = tempList[i]+ '<br />'; } else{ var list = list + tempList[i]+ '<br />'; } } alert(list); }); A: Old answer: Your script may not work, because you have to initialise the index of the loop: var i=0; Question (new, at the comment chain): Hi, hope you dont mind another question but how do I display the content of tempList[] in a table? Answer: See the code below. After the loop, I have included several ways to append the data/table to the body, because you didn't specify which method you wanted. var tempList = {}; $('#add').click(function(){ var split = $('#itemid').val().split('_'); var returnTable = "<thead><tr><th>ItemId</th><th>Lbs</th></tr></thead><tbody>"; var itemid = split[0]; if(/^\d+$/.test(itemid)) return; //itemId is not a valid number: return now. var lbs = $('#lbs').val(); tempList[itemid] = lbs; //refer by value, removed quotes around `itemId`. for (var i in tempList){ returnTable += "<tr><td>" + i + "</td><td>" + tempList[i] + '</td></tr>'; } returnTable += "</tbody>"; var tbl = document.createElement("table"); tbl.innerHTML = returnTable; //Various methods to add the table to your document are shown below // For each example, I assume that that specific element exists //When the data should be APPENDED to an existing TABLE ("#existingTable") var tblTo = document.getElementById("existingTable").tBodies[0]; for(var i=0, len=tbl.tBodies[0].rows.length; i<len; i++){ tblTo.appendChild(tbl.tBodies[0].rows[0]); //Removes the row from the temporary table, appends row to tblTo } //When the new table should replace the previous table ("#prevTable"): var prevTbl = document.getElementById("prevTable"); prevTbl.parentNode.replaceChild(tbl, prevTbl); //When the table should be APPENDED to a container ("#container") document.getElementById("output").appendChild(tbl); //When the new table should replace the contents of a container ("#container") var container = document.getElementById("container"); container.innerHTML = ""; container.appendChild(tbl); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7545688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }