text
stringlengths
15
59.8k
meta
dict
Q: Special characters in Response.RedirectPermanent I was redirecting to a URL which has some German special characters in it like: ü . Although in the Firefox this special character remains as it is: ü, but in IE & Chrome it is being changed to : %c3%bc . How can i prevent this to happen in IE & chrome? I was using Response.RedirectPermanent() . A: This conversion does not change anything. On reqest it will be converted back. This conversion happened because chars in URL is limited. For more information look at http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/15963035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: On change event not working in two elements I have an HTML markup element <div class="icon-upload"> <div class="icon-edit"> <input type='file' id="icoUpload" onchange="getURL(this)" class="icoUpload" accept=".png, .jpg, .jpeg"/> <label for="icoUpload"></label> </div> <div class="icon-preview"> <div id="icoPreview" style="background-image: url(assets/img/dash/Add-icon.png);"> </div> </div> And JS code is this function getURL(input) { if (input && input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { input.parentElement .nextElementSibling .firstChild .nextElementSibling .style .backgroundImage = 'url('+e.target.result +')'; } reader.readAsDataURL(input.files[0]); } } So basically what it does is take the input type file's image URL and shows a preview. It is working perfectly fine. Now when I add another element of class .icon-upload by simply duplicating, onchange attribute on the second element is not working. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/66328472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: where to place .htaccess for apache cgi-bin I have a python script under /usr/lib/cgi-bin/ folder. This script is accessible from URL: http://localhost/cgi-bin/test.py Now I want to set a Apache env variable using SetEnv in a .htaccess file. Where must the .htaccess file be placed, so I can access the env variable in my python script? Thanks F481 A: As they wrote here, htaccess works in all directories except cgi-bin. But, as you can see from here, there's a way around it. Basically, you edit the <Directory "C:/path/to/cgi-bin"> section of your httpd.conf file - and put there whatever would have been in the .htaccess file in cgi-bin. Remember to restart your apache after changes to httpd.conf One more tidbit: there's probably already a <Directory "/var/www/cgi-bin"> in your httpd.conf. Edit it - having duplicate sections causes gray hairs. The above worked for me for password protecting the cgi-bin directory, as using .htaccess in cgi-bin didn't work. Inserting it into the <Directory "C:/path/to/cgi-bin"> section of my httpd.conf file did work. It now says: <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all AuthType Basic AuthName "Scripts" AuthUserFile /var/secret/.htpasswrd Require valid-user Satisfy All </Directory>
{ "language": "en", "url": "https://stackoverflow.com/questions/28953713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: isset() and empty() - what to use Could you help me to improve my coding style?:) In some tasks I need to check - is variable empty or contains something. To solve this task, I usually do the following. Check - is this variable set or not? If it's set - I check - it's empty or not? <?php $var = '23'; if (isset($var)&&!empty($var)){ echo 'not empty'; }else{ echo 'is not set or empty'; } ?> And I have a question - should I use isset() before empty() - is it necessary? TIA! A: You can just use empty() - as seen in the documentation, it will return false if the variable has no value. An example on that same page: <?php $var = 0; // Evaluates to true because $var is empty if (empty($var)) { echo '$var is either 0, empty, or not set at all'; } // Evaluates as true because $var is set if (isset($var)) { echo '$var is set even though it is empty'; } ?> You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone. A: Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true. $a=null; $b=false; $c=true; var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared //array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) } //array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) } You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'. So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''. A: It depends what you are looking for, if you are just looking to see if it is empty just use empty as it checks whether it is set as well, if you want to know whether something is set or not use isset. Empty checks if the variable is set and if it is it checks it for null, "", 0, etc Isset just checks if is it set, it could be anything not null With empty, the following things are considered empty: * *"" (an empty string) *0 (0 as an integer) *0.0 (0 as a float) *"0" (0 as a string) *NULL *FALSE *array() (an empty array) *var $var; (a variable declared, but without a value in a class) From http://php.net/manual/en/function.empty.php As mentioned in the comments the lack of warning is also important with empty() PHP Manual says empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set. Regarding isset PHP Manual says isset() will return FALSE if testing a variable that has been set to NULL Your code would be fine as: <?php $var = '23'; if (!empty($var)){ echo 'not empty'; }else{ echo 'is not set or empty'; } ?> For example: $var = ""; if(empty($var)) // true because "" is considered empty {...} if(isset($var)) //true because var is set {...} if(empty($otherVar)) //true because $otherVar is null {...} if(isset($otherVar)) //false because $otherVar is not set {...} A: In your particular case: if ($var). You need to use isset if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not use isset. The same goes for empty, only that empty also combines a check for the truthiness of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var, or isset($var) && $var == true. If you only want to test a variable that should exist for truthiness, if ($var) is perfectly adequate and to the point. A: Empty returns true if the var is not set. But isset returns true even if the var is not empty. A: $var = 'abcdef'; if(isset($var)) { if (strlen($var) > 0); { //do something, string length greater than zero } else { //do something else, string length 0 or less } } This is a simple example. Hope it helps. edit: added isset in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.
{ "language": "en", "url": "https://stackoverflow.com/questions/7191626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "111" }
Q: Can't modify the variables contained in another var I have a file command_file containig a large number of commands destined to configure a router. Those lines depend on variables ($rsdp and $x2 for this example) that I collecte in my code. Here's the two first lines as an example: /configure service sdp $rsdp mpls create /configure service sdp $rsdp mpls description "to-$x2" but when I lunch the perl script reading the file and sending the lines as commands to the router using Net::SSH::Expect, the variables don't change and get the wanted value. I tried using qq but same result. So the commands sent don't get changed. Thanks in advance for you time my $k; my $acdc = 'command_file'; open (my $ac, "$acdc") or die ; while (my $dc = <$ac>){ $ssh->send($dc); $k = $ssh->read_line(); print "$k\n"; } B:router# /configure service sdp $rsdp mpls create Error: Invalid parameter. B:router# /configure service sdp $rsdp mpls description "to-$x2" Error: Invalid parameter. A: What you're trying to do here is essentially templating: you specify the structure of the commands in one place, and the values that go in them in another. There are many templating solutions but an easy one for in-line templates like this is Text::Template, and just needs a minimal change to your input strings. use strict; use warnings; use Text::Template 'fill_in_string'; # presuming this text is from an external source that can't access these variables my $template = '/configure service sdp {$rsdp} mpls description "to-{$x2}"'; my $rsdp = 'foo'; my $x2 = 'bar'; # now these variables are defined my $command = fill_in_string $template, HASH => {rsdp => $rsdp, x2 => $x2}; A: So you're reading text strings from your input file. Those text strings contain mentions of Perl variables and you want those variables to be expanded in the string without you doing anything to achieve that. I'm sorry, but life isn't that easy :-) The text strings you read from your input file are just dumb text strings. They know nothing about Perl variables. It's up to you to put in the clever work to make this work how you want it to work. Some people will tell you to use eval to do this. Please ignore them. It's too dangerous. What we will do is look for specific strings in your text (strings that will look like the variable names you are interested in) and substitute them for the current values stored in those variables. For example: $dc =~ s/\$rsdp\b/$rsdp/g; $dc =~ s/\$x2\b/$x2/g; Notice that I've: * *Escaped the $ in the pattern on the left-hand side of the substitution, so it's just a $ and not a variable sigil. *Marked the end of the variable name with \b which marks a "word boundary". This is so we only match our specific variable name and not any other, longer variable name that happens to start with our variable name. *Using a global replacement (/g) in case the same variable name appears more than once in the input string. This needs to happen at the start of your while loop - after you have read the text from the file and before you send it as a command.
{ "language": "en", "url": "https://stackoverflow.com/questions/57905671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what does native="true" stand for in a Qt designer form I am doing a diff between 2 project versions and noticed that some of the ui files have extra attributes in the xml that I have not put there myself: where would native="true" come from? what would make it get added to the ui? A: Qt GUIs can be displayed in many themes. native="true" forces the application to use the operating system's theme (on Linux, some QT apps look terrible because they don't look like the rest of the native apps).
{ "language": "en", "url": "https://stackoverflow.com/questions/6257908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Nasm - How does the program keep track of which register has stored negative or positive values Obviously there is the Sign-Flag. But when I have a code chunk like: ;starts with parry, zero set mov eax, 100 ; mov does not affect the flags neg eax ; sets carry, adjust and sign, unsets zero mov ebx, 4000000000; mov does not affect the flags mov ecx, eax ; mov does not affect the flags mov edx, 50 ; mov does not affect the flags add ebx, edx ; unsets all set flags, value of ebx is 4000000050 I have some trouble understanding how the program knows that add ebx, edx is 4000000050. Remember that the sign flag was still set from negating eax. And because assembly has no types like C which distinguish between signed and unsigned and ebx highest bit is set, the value stored in ebx could be its real value or it could be its 2's complement. We don't know. At least that is my understanding. So how does the program knows that ebx is +4000000000 and not a negative value which 2's complement is 4000000000 in binary. A: The processor doesn't know. It is the responsibility of the programmer to keep track of which registers/memory locations contain signed numbers and which contain unsigned numbers. A 32-bit register can either store numbers in the range -2147483648 .. 2147483647 or in the range 0 .. 4294967295. The processor doesn't know which of these two ranges the programmer intends to use. The beauty of 2's complement arithmetic is that the processor can perform most operations without needing to know. Some of the operations where the processor does need to know are: division, multiplication where the result is twice the width of the operands, and comparison. For multiplication and division, there are separate opcodes for signed vs. unsigned. For comparison, the comparison opcode is the same, but the conditional branch opcodes used to check the result of the comparison are different depending on whether the programmer wants to treat the operands as signed or unsigned.
{ "language": "en", "url": "https://stackoverflow.com/questions/59447857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET Loading Data into Table with Navigation Property I have a created Entity Framework.I am trying to add a new songs and New album to the table. For example when I try to add a new song I used the method below and it tells me "Object reference not set to an instance of an object" on the s.Artist.ArtistName. I have a webform that shows a list of Artists in a drop down menu and now I want to add a new song for that artist. How do I do that? public Song AddNewSongNav(String ArtistName, String SongName) { using (var context = new MyEntities()) { var s = new Song(); s.SongTitle = SongName; s.Artist.ArtistName = ArtistName; s.Artist.WikipediaUrl="http://en.wikipedia.org/Testing"; context.Songs.AddObject(s); context.SaveChanges(); return s; } } The frame work for the Artist Table has ArtistID,ArtistName and WikiPediaURL. It has a navivgation property for Album and Song. It is linked to Song as 1 to many and Album as 1 to Many. It has a Song table, which has a SongID, SongTitle and Artist_ArtistID. It has a navigation property of Artist and Album. It's linked as a many to many to the Albums table. Finally the Album table has an AlbumID,AlbumTitle,CoverArt,Year,Genre,MimeType and Artist_ArtistID. It has a navigation property of Artist and Song. A: The Artist property is not automatically created - you have to create an instance of the artist first: var s = new Song(); s.SongTitle = SongName; s.Artist = new Artist(); s.Artist.ArtistName = artistName;
{ "language": "en", "url": "https://stackoverflow.com/questions/10156736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery clone image, but only when dragged from outside container I have 2 html elements, 1.<div class="drag">..example.jpg..</div> contains images that can be dragged/cloned/dropped. 2.<div class="drop-zone"></div> is the div they can be dropped into, retain dragging, but not be clone-able. Demo: http://jsfiddle.net/rGUma/2/. It's working BUT, I do not want the images that are dropped into .drop-zone to be cloned when dragged. The cloning should only be possible if they are dragged from outside the container. ( drag an image inside the box, then drag that image around and you see it continues to be cloned). Is there a simple way to do this that I'm overlooking , or should the code above be completely redone using a different method? Code reference: $(document).ready(function($) { $(".drop-zone").droppable({ accept: '.drag', drop: function(event, ui) { $(this).append($(ui.helper).clone()); $(".drag").addClass("item"); $(".item").removeClass("ui-draggable"); $(".item").draggable({ containment: '.drop-zone' }); } }); $(".drag").draggable({ helper: 'clone' }); });​ A: Basically, right now, the drop event occurs again and again, whether you're dragging images from outside or inside the container. The simplest solution is to check whether an image is already inside the container, and if so, do not add it to the container: jQuery(function($) { $('.drop-zone').droppable({ accept: '.drag', drop: function(event, ui) { var $clone = ui.helper.clone(); if (!$clone.is('.inside-drop-zone')) { $(this).append($clone.addClass('inside-drop-zone').draggable({ containment: '.drop-zone' })); } } }); $('.drag').draggable({ helper: 'clone' }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/9763409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using R to calculate trumpet curves from flow data I'm looking for a way to calculate Trumpet Curves from intravenous set flow data using R (and preferably ggplot2 although that's not vital). Here is some flow data from fluid warming pumps: http://pastebin.com/vJmGcJmn So far I have this: flow<-read.table(file="flow.dat",header=T) flow$diff<-c(0,diff(flow$Mass)) ggplot(data=flow, aes(x=Secs,y=diff)) + geom_line() Note that the trumpet graphs required are as per ISO 60601-2-24 (if that means anything!) This flow was set up at 150ml/minute. A: Sorry this took so long, pressed for time. The data you provided don't seem to fit your description of what the trumpet curve's suppose to represent or I'm missing something big. I would appreciate it if you could, in short, describe what needs to be done with the data. When you manage to shape your data for output, you can stick it into the code below and it should produce a plot. I'll make it up to you to customize it to your needs. # generate some random data trump <- data.frame( curve1 = rev(sort(rchisq(100, df = 2))) * rnorm(100, mean = 5, sd = 0.1) + 3, curve2 = -rev(sort(rchisq(100, df = 2))) * rnorm(100, mean = 5, sd = 0.1) - 3 ) trump <- trump[seq(from = 1, to = 100, by = 3), ] ggplot(trump, aes(x = 1:nrow(trump), y = curve1)) + geom_line() + geom_point() + geom_line(aes(y = curve2)) + geom_point(aes(y = curve2)) + geom_hline(aes(yintercept = 0), linetype = "solid") + # overall percentage error geom_hline(aes(yintercept = 5), linetype = "dashed") + # set rate xlab("Observation windows (in minutes)") + ylab("% error") + annotate("text", x = 8, y = -1.5, label = "overall percentage error") + annotate("text", x = 5, y = 3, label = "set rate") + annotate("text", x = 10, y = -24, label = "min. error") + annotate("text", x = 10, y = 24, label = "max. error") + theme_bw() A: Many thanks to Roman for his help. This is the way we ended up doing it. flow<-read.table("iv.txt",comment.char="#",header=TRUE) Q<-as.data.frame(c(0,(60*diff(flow$wt,1,1)/0.5))) # Q is used for flow in the standard names(Q)<-"Q" # Now combine them l<-list(flow,Q) dflow<-as.data.frame(l) t1flow<-subset(dflow, dflow$secs>60*60 & dflow$secs<=120*60) # require the second hour of the data t1flow$QE<-((t1flow$Q-setflow)/setflow)*100 # calculate the error library(TTR) # use this for moving averages # # Avert your eyes! I know there must be a slicker way of doing this ..... # # Calculate the moving average using a sample rate of every 4 readings (2 mins of 30sec readings) QE2<-SMA(t1flow$QE,4) minQE2<-min(QE2,na.rm=TRUE) maxQE2<-max(QE2,na.rm=TRUE) # now for the 5 minute window QE5<-SMA(t1flow$QE,10) minQE5<-min(QE5,na.rm=TRUE) maxQE5<-max(QE5,na.rm=TRUE) # Set window to 11 mins QE11<-SMA(t1flow$QE,22) minQE11<-min(QE11,na.rm=TRUE) maxQE11<-max(QE11,na.rm=TRUE) # Set window to 19 mins QE19<-SMA(t1flow$QE,38) minQE19<-min(QE19,na.rm=TRUE) maxQE19<-max(QE19,na.rm=TRUE) # Set window to 31 mins QE31<-SMA(t1flow$QE,62) minQE31<-min(QE31,na.rm=TRUE) maxQE31<-max(QE31,na.rm=TRUE) # # OK - you can look again :-) # # create a data frame from this data trump<-data.frame(c(2,5,11,19,31),c(minQE2,minQE5,minQE11,minQE19,minQE31),c(maxQE2,maxQE5,maxQE11,maxQE19,maxQE31)) names(trump)<-c("T","minE","maxE") A<-mean(t1flow$QE) # calculate the overall mean percentage error error_caption<-paste("overall percentage error = ",A,"%") # create the string to label the error line # plot the graph ggplot(trump, aes(x = T, y = minE)) + geom_line() + geom_point(color="red") + geom_line(aes(y = maxE)) + geom_point(aes(y = maxE),colour="red") + geom_hline(aes(yintercept = 0), linetype = "dashed") + # overall percentage error geom_hline(aes(yintercept = A), linetype = "solid") + # set rate xlab("Observation windows (in minutes)") + ylab("% error") + scale_x_continuous(breaks=c(0,2,5,11,19,31),limits=c(0,32)) + # label the x axis only at the window values annotate("text", x = 10, y = A-0.5, label = error_caption) + # add the error line label opts(title="Trumpet curve for Test Data") Also available hYou can see the final graph [here][2] A: i'm currently try to solve trumpet curve calculation error. based on IEC 60601-2-24 : 1998 - SECTION EIGHT – ACCURACY OF OPERATING DATA AND PROTECTION AGAINST HAZARDOUS OUTPUT. here my R code : flow<-read.table("c:\\ciringe.txt",comment.char="#",header=TRUE) #parameters # setflow = 1 # P = 1,2,5,11,19,31 P1<-1 P2<-2 P5<-5 P11<-11 P19<- 19 P31<-31 P1m = ((60 - P1) / 0.5 ) + 1 P2m = ((60 - P2) / 0.5 ) + 1 P5m = ((60 - P5) / 0.5 ) + 1 P11m = ((60 - P11) / 0.5 ) + 1 P19m = ((60 - P19) / 0.5 ) + 1 P31m = ((60 - P31) / 0.5 ) + 1 setflow<-1 mQE1<-0.5 mQE2<-0.25 mQE5<-0.1 mQE11<-0.045 mQE19<-0.0263 mQE31<-0.0161 Q<-as.data.frame(c(0,(60*diff(flow$wt,1,1)/0.5*0.998))) # Q is used for flow in the standard names(Q)<-"Q" # Now combine them l<-list(flow,Q) dflow<-as.data.frame(l) t1flow<-subset(dflow, dflow$secs>=3600 & dflow$secs<=7200) # require the second hour of the data #overall t1flow$QE<-(((t1flow$Q-setflow)/setflow)*100) # calculate the error t1flow$QE1<-(((t1flow$Q-setflow)/setflow)*100) * mQE1 # calculate the error t1flow$QE2<-(((t1flow$Q-setflow)/setflow)*100) * mQE2 # calculate the error t1flow$QE5<-(((t1flow$Q-setflow)/setflow)*100) * mQE5 # calculate the error t1flow$QE11<-(((t1flow$Q-setflow)/setflow)*100) * mQE11 # calculate the error t1flow$QE19<-(((t1flow$Q-setflow)/setflow)*100) * mQE19 # calculate the error t1flow$QE31<-(((t1flow$Q-setflow)/setflow)*100) * mQE31 # calculate the error library(TTR) # use this for moving averages # # Avert your eyes! I know there must be a slicker way of doing this ..... # # Calculate the moving average using a sample rate of every # 4 readings (2 mins of 30sec readings) # now for the 1 minute window QE1<-SMA(t1flow$QE1,2) minQE1<-min(QE1,na.rm=TRUE) maxQE1<-max(QE1,na.rm=TRUE) # now for the 2 minute window QE2<-SMA(t1flow$QE2,4) minQE2<-min(QE2,na.rm=TRUE) maxQE2<-max(QE2,na.rm=TRUE) # now for the 5 minute window QE5<-SMA(t1flow$QE5,10) minQE5<-min(QE5,na.rm=TRUE) maxQE5<-max(QE5,na.rm=TRUE) # Set window to 11 mins QE11<-SMA(t1flow$QE11,22) minQE11<-min(QE11,na.rm=TRUE) maxQE11<-max(QE11,na.rm=TRUE) # Set window to 19 mins QE19<-SMA(t1flow$QE19,38) minQE19<-min(QE19,na.rm=TRUE) maxQE19<-max(QE19,na.rm=TRUE) # Set window to 31 mins QE31<-SMA(t1flow$QE31,62) minQE31<-min(QE31,na.rm=TRUE) maxQE31<-max(QE31,na.rm=TRUE) # # OK - you can look again :-) # # create a data frame from this data trump<- data.frame(c(1,2,5,11,19,31),c(minQE1,minQE2,minQE5,minQE11,minQE19,minQE31), c(maxQE1,maxQE2,maxQE5,maxQE11,maxQE19,maxQE31)) names(trump)<-c("T","minE","maxE") A<-mean(t1flow$QE) # calculate the overall mean percentage error error_caption<-paste("overall percentage error = ",A,"%") # create the string to label the error line # plot the graph library(ggplot2) ggplot(trump, aes(x = T, y = minE)) + geom_line() + geom_point(color="red") + geom_line(aes(y = maxE)) + geom_point(aes(y = maxE),colour="red") + geom_hline(aes(yintercept = 0), linetype = "dashed") + # overall percentage error geom_hline(aes(yintercept = A), linetype = "solid") + # set rate xlab("Observation windows (in minutes)") + ylab("% error") + scale_x_continuous(breaks=c(0,2,5,11,19,31),limits=c(0,32)) + # label the x axis only at the window values annotate("text", x = 10, y = A-0.5, label = error_caption) # add the error line label actually, i'm not understand summation series as stated in the ISO docs (percentage variation) A: Your formulae don't match the equations in ISO 60601-2-24. The spec is a bit tedious to go thru but there are no 2-minute windows or moving averages. First, get your data formatted as 1-minute samples (per the spec). Do a data array with 1 minute intervals and columns of: colTotalLiquid = 1 #total liquid (precalculated from weight) colProgRate = 2 #prog rate colQi = 3 # rate Q(i) from IEC60601-2-24 obsWindow = (2, 5, 11, 19, 31) # observation windows in minutes analysisT1start = 60 # start of analysis period T1 analysisT1end = 120 # end of analysis period T1 t1err = dict.fromkeys(obsWindow, None) progRate = data[analysisT1start][colProgRate] A = 100 * (((data[analysisT1end][colTotalLiquid] - data[analysisT1start][colTotalLiquid]) * hours / (analysisT1end - analysisT1start)) - progRate) / progRate t1TrumpetX = [] #mintes t1TrumpetY1 = [] #Ep(max) t1TrumpetY2 = [] #Ep(min) t1TrumpetY3 = [] #mean err t1TrumpetY4 = [] #prog Rate for p in obsWindow: m = (analysisT1end - analysisT1start) - p + 1 t1err[p] = {'m': m} EpMax = 0 EpMin = 0 for j in range(1, m + 1): errSum = 0 for i in range(j, j + p): errSum += (1.0/p) * 100 * ( data[analysisT1start + i][colQi] - progRate ) / progRate if errSum > EpMax: EpMax = errSum if errSum < EpMin: EpMin = errSum t1err[p]['EpMax'] = EpMax t1err[p]['EpMin'] = EpMin t1TrumpetX.append(p) t1TrumpetY1.append(EpMax) t1TrumpetY2.append(EpMin) t1TrumpetY3.append(A) t1TrumpetY4.append(0) tplot = PdfPages('trumpet curve.pdf') p1 = plt.figure() plt.plot(t1TrumpetX, t1TrumpetY1) plt.plot(t1TrumpetX, t1TrumpetY2) plt.plot(t1TrumpetX, t1TrumpetY3) plt.plot(t1TrumpetX, t1TrumpetY4, '--') plt.legend(('Ep(max)','Ep(min)', 'overall error', 'set rate'), fontsize='xx-small', loc='best') plt.title(baseName + ': IEC60601-2-24 Trumpet Curve for Second Hour', fontsize='x-small') plt.xlabel('Observation window (min)', fontsize='x-small') plt.ylabel('Percentage error of flow', fontsize='x-small') plt.ylim((-15, 15)) ax = plt.axes() ax.set_xticks(obsWindow) tplot.savefig(p1) plt.close(p1) tplot.close(p1) That should get you the standard's trumpet curve. There's no requirement to put a numerical label on the overall error A, but you could do that with an annotation.
{ "language": "en", "url": "https://stackoverflow.com/questions/11422202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to determinate best implementation of Kubernetes cluster I had recently began to walk in to the Kubernetes world, there is a lot of information and most of time I get really confused; Then I'd like to ask how I can choose the better way to administrate an infrastructure will like this: The node and the Kubernetes master are isolated in different DMZ, the port and the direction will be opened as described in the picture. Which way you will use to let the pods going to be executed on the right node? (for example, an Nginx pod go only on Web1 and/or web2 and a pgSQL pod go only executed on DB1 and/or DB2) use the server labeling system is good enough or have better solution to manage this? A second doubt I have is the service have to be reachable from the external word directly from the node, so if I want to use replicas, the Web1 and Web2 should listen on same IP address the service is exposed, I suppose, or could this be managed via the kube-proxy? At the moment I thinking about configure a distributed switch between the nodes and set the external ip address of the pod one of the IP attached to the distributed switch. It is also a good solution or have some better way to do it? A: Which way you will use to let the pods going to be executed on the right node? nodeSelector, simplest way because you add a label to the node kubectl label nodes k8s-node-1 disktype=ssd which can be verified by kubectl get nodes --show-labels and inside pod yaml under spec you add: nodeSelector: disktype: ssd Node affinity, is more complex and more expressive as you are no longer limited to exact matches. Keep in mind this is still a beta feature. A second doubt I have is the service have to be reachable from the external word directly from the node, so if I want to use replicas, the Web1 and Web2 should listen on same IP address the service is exposed, I suppose, or could this be managed via the kube-proxy? Here, I think you will need to use Type LoadBalancer as a Service, most cloud providers have they own internal LoadBalancer GCP, AWS, Azure. There is also MetalLB which is implementation for bare metal Kubernetes clusters. Hope this helps You. EDIT: OP recommends using Node restriction which in his example a better solution to let pods running dynamically on a sub-set of node in the cluster.
{ "language": "en", "url": "https://stackoverflow.com/questions/54021657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: :hover pseudo-class of CSS does not work in IE7 I have problem with the :hover pseudo-class of CSS. I am using it like tr.lightRow:hover { color:red } It works in Safari and Firefox but it does not work in IE7. Please help me. A: IE7 supports :hover, at least in standards mode. It may not in quirks mode. A: IE has a history of bad CSS support. Originally only a tags supported :hover. And also you couldn't have something like a:hover span to indicate that only the span tag should change when hovering the parent a. If you want correct :hover functionality across all IE versions, you need to use javascript and onmouseover/onmouseout. It also helps if you use an xhtml doctype, to enable standards mode. A: IE 6 only supports the :hover pseudo class on links, but IE 7 supports it on most elements. As David mentioned, it might not work in quirks mode. The reason would then be that IE mostly reverts back to something closer to IE 4 in quirks mode, allowing a lot of IE specific features and removing several standards compliant features. If you want the :hover functionality on a block element and support back to IE 6, you can use a link element and make it a block element using CSS. Note that a link only can contain inline elements (e.g. no divs) so if you want block elements inside the link you would have to set that using CSS also: CSS: .hoverlink { display: block; } .hoverlink:hover { background: #eee; } .hoverlink .item { display: block; } HTML: <a href="..." class="hoverlink"> <span class="item">Line 1</span> <span class="item">Line 2</span> <span class="item">Line 3</span> </a> (You might want to consider the impact on search engines using the technique also. A link has better impact if it just contains the text describing what it links to.) A: :hover is not supported by every element e.g. it works on <a> but breaks on <div> afaik A: I've run into this a few times - have a look at the following link .. http://www.bernzilla.com/item.php?id=762 "if you want support for :hover on all elements and not just the <a> tag, make sure you're using a strict DOCTYPE so IE7 doesn't kick in to quirks mode."
{ "language": "en", "url": "https://stackoverflow.com/questions/2077411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: starting cherrypy properly How do I properly start cherrypy? It worked for me with 3.0 but now I can serve the content but have to start my service everytime I touch the source even though the autoreloader is running. I already added the cherrypy.engine.block() statement, which works but cherrypy stops serving my application then (no answer within the browser, even though it opens the TCP port properly). So any clue or insight on where or what to look for? This is on stdout: [30/Dec/2012:17:05:28] ENGINE Bus STARTING<br> [30/Dec/2012:17:05:28] ENGINE Started monitor thread 'Autoreloader'.<br> [30/Dec/2012:17:05:28] ENGINE Started monitor thread '_TimeoutMonitor'.<br> [30/Dec/2012:17:05:28] ENGINE Serving on 0.0.0.0:8080<br> [30/Dec/2012:17:05:28] ENGINE Bus STARTED<br> [30/Dec/2012:17:05:28] ENGINE Bus STARTING<br> [30/Dec/2012:17:05:28] ENGINE Monitor thread 'Autoreloader' already started.<br> [30/Dec/2012:17:05:28] ENGINE Monitor thread '_TimeoutMonitor' already started.<br> [30/Dec/2012:17:05:28] ENGINE Already serving on 0.0.0.0:8080<br> [30/Dec/2012:17:05:28] ENGINE Bus STARTED<br> How I start it: cherrypy.tree.mount(login(), '/', configPath)<br> cherrypy.tree.mount(reservation(), '/reservation', configPath)<br> cherrypy.tree.mount(administration(), '/reservation/administration', configPath)<br> cherrypy.server.socket_host= "0.0.0.0"<br> cherrypy.engine.start() A: As Makoto says, it looks like you have started CherryPy twice. Are you calling both engine.start/engine.block along with cherrypy.quickstart? If so, remove one or the other. A: My Problem was the usage of and old version (actually the latest one linked on their site!) of cherrypy in conjunction with python 3.3. Taking the latest packages from bitbucket solved this for me!
{ "language": "en", "url": "https://stackoverflow.com/questions/14092933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AttributeError: 'BlockManager' object has no attribute 'refs' I am trying to write a python program that show me the stock price chart for google. import matplotlib.pyplot as plt import matplotlib.dates as mdates from pandas_datareader import data as pdr import yfinance as yf yf.pdr_override() #set the start and end date start_date = "2020-03-01" end_date = "2020-04-12" #choose stock ticker symbol ticker = "GOOGLE" #get stock price stock = pdr.get_data_yahoo(ticker, start=start_date, end=end_date) print(stock) #obtain dates stock["Date"]=stock.index.map(mdates.date2num) #choose figure size fig = plt.figure(dpi=128, figsize=(10, 6)) #format date to place on the x-axis formatter = mdates.DateFormatter('%m/%d/%Y') plt.gca().xaxis.set_major_formatter(formatter) # Plot data. plt.plot(stock['Date'], stock['Adj Close'], c='red') # Format plot. plt.title("The Stock Price", fontsize=16) plt.xlabel('Date', fontsize=10) fig.autofmt_xdate() plt.ylabel("Price", fontsize=10) plt.show() But the program keeps showing me this error. AttributeError: 'BlockManager' object has no attribute 'refs' the error keeps focusing on this exception 'Date' somehow during handle it another exception occurred. Update on the problem: somehow solved itself I don't know how but I run the same code again after 24 h and it gave me the desired output.
{ "language": "en", "url": "https://stackoverflow.com/questions/75491469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apply CSS rule to all elements inside? I have some elements that goes like this <div class="t-widget t-window"> Your code goes here </div> For that element and all elements i want to apply this rule -webkit-box-sizing : content-box; -moz-box-sizing : content-box; box-sizing : content-box; How easy that can be done? A: You can do it using the below CSS setting: CSS: .t-widget, .t-widget ~ * { /* The ~ * selects all elements following it */ color: red; /* Added just for illustration */ -webkit-box-sizing : content-box; -moz-box-sizing : content-box; -o-box-sizing : content-box; box-sizing : content-box; } HTML: <div>Your code goes here</div> <!-- Style will not be applied to this --> <div class="t-widget t-window">Your code goes here</div> <!-- Style will be applied from this point on --> <div>Your code goes here</div> <div>Your code goes here</div> <div>Your code goes here</div> Demo Edit: Just now saw your comment that you want for child elements. For that use the below CSS. .t-widget, .t-widget * { color: red; -webkit-box-sizing : content-box; -moz-box-sizing : content-box; -o-box-sizing : content-box; box-sizing : content-box; } Updated Demo Here you can have a look at the comprehensive list of CSS3 Selectors.
{ "language": "en", "url": "https://stackoverflow.com/questions/24755032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java reading .txt file to array I've been trying to workout this excersise all day, but not having any luck. Thanks in advance for any help. Here's the problem The approach you are to implement is to store each integer in an array of digits, with one digit per array element. We will be using arrays of length 50, so we will be able to store integers up to 50 digits long. We have to be careful in how we store these digits. Consider, for example, storing the numbers 38423 and 27. If we store these at the “front” of the array with the leading digit of each number in index 0 of the array, then when we go to add these numbers together, we’re likely to add them like this: 38423 27 To simulate this right-shifting of values, we will store each value as a sequence of exactly 50 digits, but we’ll allow the number to have leading 0’s. For example, the problem above is converted into: 0000000000000000000038423 0000000000000000000000027 Now the columns line up properly and we have plenty of space at the front in case we have even longer numbers to add to these. The data for your program will be stored in a file called sum.txt. Each line of the input file will have a different addition problem for you to solve. Each line will have one or more integers to be added together. Take a look at the input file at the end of this write-up and the output you are supposed to produce. Notice that you produce a line of output for each input line showing the addition problem you are solving and its answer. Your output should also indicate at the end how many lines of input were processed. You must exactly reproduce this output. You should use the techniques described in chapter 6 to open a file, to read it line by line, and to process the contents of each line. In reading these numbers, you won’t be able to read them as ints or longs because many of them are too large to be stored in an int or long. So you’ll have to read them as String values using calls on the method next(). Your first task, then, will be to convert a String of digits into an array of 50 digits. As described above, you’ll want to shift the number to the right and include leading 0’s in front. The String method charAt and the method Character.getNumericValue will be helpful for solving this part of the problem. You are to add up each line of numbers, which means that you’ll have to write some code that allows you to add together two of these numbers or to add one of them to another. This is something you learned in Elementary School to add starting from the right, keeping track of whether there is a digit to carry from one column to the next. Your challenge here is to take a process that you are familiar with and to write code that performs the corresponding task. Your program also must write out these numbers. In doing so, it should not print any leading 0’s. Even though it is convenient to store the number internally with leading 0’s, a person reading your output would rather see these numbers without any leading 0’s. You can assume that the input file has numbers that have 50 or fewer digits and that the answer is always 50 digits or fewer. Notice, however, that you have to deal with the possibility that an individual number might be 0 or the answer might be 0. There will be no negative integers in the input file. You should solve this problem using arrays that are exactly 50 digits long. Certain bugs can be solved by stretching the array to something like 51 digits, but it shouldn’t be necessary to do that and you would lose style points if your arrays require more than 50 digits. The choice of 50 for the number of digits is arbitrary (a magic number), so you should introduce a class constant that you use throughout that would make it easy to modify your code to operate with a different number of digits. Consider the input file as an example of the kind of problems your program must solve. We might use a more complex input file for actual grading. The Java class libraries include classes called BigInteger and BigDecimal that use a strategy similar to what we are asking you to implement in this program. You are not allowed to solve this problem using BigInteger or BigDecimal. You must solve it using arrays of digits. Your program should be stored in a file called Sum.java. Input file sum.txt 82384 204 435 22 31 12 999 483 28350 28345 39823 95689 234856 3482 55328 934803 7849323789 22398496 8940 32489 859320 729348690234239 542890432323 534322343298 3948692348692348693486235 5834938349234856234863423 999999999999999999999999 432432 58903 34 82934 49802390432 8554389 4789432789 0 48372934287 0 0 0 0 7482343 0 4879023 0 8943242 3333333333 4723 3333333333 6642 3333333333 Output that should be produced 82384 = 82384 204 + 435 = 639 22 + 31 + 12 = 65 999 + 483 = 1482 28350 + 28345 + 39823 + 95689 + 234856 + 3482 + 55328 + 934803 = 1420676 7849323789 + 22398496 + 8940 + 32489 + 859320 = 7872623034 729348690234239 + 542890432323 + 534322343298 = 730425903009860 3948692348692348693486235 + 5834938349234856234863423 = 9783630697927204928349658 999999999999999999999999 + 432432 + 58903 + 34 = 1000000000000000000491368 82934 + 49802390432 + 8554389 + 4789432789 + 0 + 48372934287 = 102973394831 0 = 0 0 + 0 + 0 = 0 7482343 + 0 + 4879023 + 0 + 8943242 = 21304608 3333333333 + 4723 + 3333333333 + 6642 + 3333333333 = 10000011364 Total lines = 14 My code thus far public class Sum { public static void main(String args[]) throws FileNotFoundException{ File file = new File("sum.txt"); Scanner scanner = new Scanner(file); String[] myInts = new String[50]; int mySpot = 0; while(scanner.hasNext()){ myInts[mySpot] = scanner.next(); mySpot++; } for(int i = 0; i < myInts.length; i++){ } System.out.println(Character.getNumericValue(myInts[0])); System.out.println(Arrays.toString(myInts)); } } A: When all else fails read the instructions: "The approach you are to implement is to store each integer in an array of digits, with one digit per array element. We will be using arrays of length 50, so we will be able to store integers up to 50 digits long." Tells me that this line: String[] myInts = new String[50]; Has some significant problems. Tip 1: Don't call it myInts when it's an array of String objects. Things are hard enough already. Tip 2: Understand that new String[50] is not going to give you a string sized to 50 characters. It's going to give you space to store references to 50 string objects. Tip 3: Understand that each line of your input can be solved separately so there is no need to remember anything from the lines you've solved before. Tip 4: Read one line at a time into String line; Tip 5: After reading a line solve the display problem in two parts: left side and right side of ='s. Tip 6: Left side: display the line with spaces replaced with space + space. line.replace(" "," + "); Tip 7: Right side: use line.split(" ") to split line on space, loop the split array of strings, each of these strings is what you'll be converting to int arrays. Tip 8: "convert a String of digits into an array of 50 digits" <- Life will be easier if you write a method that does this. Take a String. Return an int[]. private int[] makeIntArray(String num) Take care of the "right shifting/leading zero" problem here. Tip 9: int and long aren't big enough to hold the bigger numbers so break the number String down to Strings of digits before converting to int[]. Tip 10: Read Splitting words into letters in Java Tip 11: Read Split string into array of character strings Tip 12: Once you have single characters you can use Integer.parseInt(singleCharString[index--]) if you broke it down to an array of strings or Character.digit( chr[index--], 10); if you broke it down to an array of characters. Tip 13: "write some code that allows you to add together two of these numbers or to add one of them to another." Read that carefully and it tells you that you really need to declare two vars. int[] sum = new sum[SIZE]; and int[] next = new next[SIZE]; where size is private final static int SIZE = 50; Tip 14: adding two of these int[] numbers to produce a new int[] would be another good time to make a method. int[] sum(int[] op1, int[] op2) Tip 15: Since all our int[]'s are right shifted already and always 50 long start a loop with i at 49 and count down. result[i-1] = (op1[i] + op2[i] + carry) % 10; and carry = (op1[i] + op2[i] + carry) / 10 will come in handy. Make sure to stop the loop at 1 or [i-1] will go index out of bounds on you. Tip 16: Test, Test, and Test again. Make small changes then test. Small change, test. Don't just type and pray. Use the debugger if you like but personally I prefer to check values like this System.out.println("line: " + line);//TODO remove debugging code A: Tip #1: Initialize the array with 0. That way, when you process the file, all you have to worry about is to replace the index locations with the digits obtained from your file. Tip #2: You have to do some repeated division by 10 and modulus operation to extract the digits from the number (or binary shift if you prefer). For example, to split the the digits from '27', you can do 27 % 10 (7) and 27 / 10 (2). The key here is to store the result as int. After all, each digit is a whole number (not a floating point number). For number of greater magnitude, you will need to discard the process digit position so that the number gets smaller. You will now when you are done when the quotient of the division is equal to zero. Therefore, you can say in pseudo-code: DIVIDE number by 10 WHILE number > 0 (something like that) Tip #3, you will have to iterate in reverse to store the digits in the array. If the array has a length of 50, you will start with LENGTH-1 and count down to ZER0. Tip #4: Use an array of ints not an array of Strings if the problem allows you to. Use Integer.parseInt(String s) to convert the numeric String to a primitive int. A: I think the question says to read each digit into a different array of standard size while you are reading all the words into a same a same array. and it will also be good to process this line by line something like this Scanner scanner = new Scanner(file); int[][] myInts = new int[wordSize][]; int mySpot = 0; while (scanner.hasNextLine()) { Scanner scanner1 = new Scanner(scanner.nextLine()); while (scanner1.hasNext()) { String s = scanner1.next(); int i; for ( i= 0; i < wordSize - s.length(); i++) { myInts[i][mySpot] = 0; } i--; for (int j=0;j < s.length(); i++,j++) { myInts[i][mySpot] = Character.digit(s.charAt(i), 10); } mySpot++; } // do the additions here and add this line to output file }
{ "language": "en", "url": "https://stackoverflow.com/questions/27052681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Macro for editing data I am looking for Macro VBA code for performing the following actions, which I am required to do manually almost everyday. I am writing down the steps which I have to do manually so that process is clear to the users replying to this query: * *Copy from a .txt file and paste in excel workbook data, which looks like this LT Insulators – Shackle Insulators – Wipro Industries Lightning Arrestors – Elpro International Conductors – ACSR Raccoon – HHI Industries The data is pasted in Column A. This data is of variable length and can be between 500-700 rows. *Use Text to Columns (Delimited with ‘-‘ as separator) to distribute the data in Col A and B where there are 2 phrases and C where there are 3 phrases. Where there are 2 phrases, I need the data in Col B to move to Column C (as this is the Col for Makes). For 2 phrase data, after the Text to Columns action , Col C will remain blank and probably that should be the criterion for moving the data from Col B to Col C. After this step, the table should look like this : LT Insulators Shackle Insulators Wipro Industries Lightning Arrestors Elpro International Conductors ACSR Raccoon HHI Industries *Then I apply =TRIM() function to both Col A and C (Col B not required) since the data is from a text file. The trimmed values can be in other columns also, which can be value pasted in the original column. *Sort the data in column A & B with C as the sort key. I am not very literate with macro VBA coding and therefore not been able draw the right thing up. Any help would be greatly appreciated. Here is my code which returns an error of Runtime 1004. Paste method failed or something like that. Sub Dataedit() ' ' Dataedit Macro ' Edits data for report ' ' ActiveSheet.Paste Range("A1:A154").Select Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True Columns("A:A").ColumnWidth = 27 Columns("B:B").ColumnWidth = 28.57 Columns("A:A").ColumnWidth = 31.29 Range("B1:B11").Select Selection.Cut Destination:=Range("C1:C11") Range("C1:C11").Select Columns("C:C").ColumnWidth = 15.43 ActiveWindow.SmallScroll Down:=6 Range("B13:B14").Select Selection.Cut Destination:=Range("C13:C14") Range("B18:B19").Select Selection.Cut Destination:=Range("C18:C19") Range("C18:C19").Select ActiveWindow.SmallScroll Down:=9 Range("B27:B28").Select Selection.Cut Destination:=Range("C27:C28") Range("B30:B32").Select Selection.Cut Destination:=Range("C30:C32") Range("C30:C32").Select ActiveWindow.SmallScroll Down:=9 Range("B36:B45").Select Selection.Cut Destination:=Range("C36:C45") Range("C36:C45").Select ActiveWindow.SmallScroll Down:=12 Range("B46:B53").Select Selection.Cut Destination:=Range("C46:C53") Range("C46:C53").Select ActiveWindow.SmallScroll Down:=9 Range("B55:B62").Select Selection.Cut Destination:=Range("C55:C62") Range("C55:C62").Select ActiveWindow.SmallScroll Down:=12 Range("B64:B67").Select Selection.Cut Destination:=Range("C64:C67") Range("C64:C67").Select ActiveWindow.SmallScroll Down:=30 Range("B94:B104").Select Selection.Cut Destination:=Range("C94:C104") Range("B105").Select Selection.Cut Destination:=Range("C105") Range("C105").Select ActiveWindow.SmallScroll Down:=27 Range("B128:B136").Select Selection.Cut Destination:=Range("C128:C136") Range("C128:C136").Select ActiveWindow.SmallScroll Down:=-147 Range("E1").Select ActiveCell.FormulaR1C1 = "=TRIM(RC[-4])" Range("F3").Select Columns("E:E").ColumnWidth = 20.71 Columns("F:F").ColumnWidth = 27.71 Range("F1").Select ActiveCell.FormulaR1C1 = "=TRIM(RC[-3])" Range("E1:F1").Select Selection.AutoFill Destination:=Range("E1:F154"), Type:=xlFillDefault Range("E1:F154").Select Range("F160").Select ActiveWindow.SmallScroll Down:=-183 Range("E1:E154").Select Selection.Cut ActiveWindow.SmallScroll Down:=-15 Range("E5").Select Application.CutCopyMode = False Selection.Copy Range("F4").Select Application.CutCopyMode = False Range("E1:E154").Select Selection.Copy Range("A1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = False Range("F1:F154").Select Selection.Copy Range("C1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("D15").Select Application.CutCopyMode = False Range("E1:F154").Select Selection.ClearContents Range("D11").Select ActiveWindow.SmallScroll Down:=-51 Range("A1:C154").Select ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C1:C154") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("C1:C154") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets("Sheet1").Sort .SetRange Range("A1:C154") .Header = xlGuess .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With ActiveWindow.SmallScroll Down:=81 ChDir "D:\" ActiveWorkbook.SaveAs Filename:="D:\File List.xlsm", FileFormat:= _ xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False Selection.ClearContents Range("E10").Select ActiveWorkbook.Save End Sub A: This is my take. Not sure if the paste is working as it should. I've avoided the use of select as it only slows down the code. I've also trimmed the data from columns A & C in situ rather than copying it over to E & F columns. I've assumed that the data is in a workbook called Book1. You can of course rename the workbook and worksheet in the macro. Sub DataEdit() Dim wb As Workbook Dim ws As Worksheet Dim GCell As Range Dim NumberOfRowsOfData, Count As Integer Set wb = Workbooks("Book1") With wb Set ws = .Worksheets("Sheet1") With ws Set GCell = .Range("A1") GCell.PasteSpecial GCell.TextToColumns DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ :="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True Set GCell = .Range("A:A") NumberOfRowsOfData = .Range("A10000").End(xlUp).Row GCell.ColumnWidth = 27 Set GCell = .Range("B:B") GCell.ColumnWidth = 28.57 Set GCell = .Range("C:C") GCell.ColumnWidth = 31.29 For Count = 1 To NumberOfRowsOfData If .Cells(Count, 3) = "" Then .Cells(Count, 3).Value = Cells(Count, 2).Value .Cells(Count, 2).ClearContents .Cells(Count, 1).Value = Trim(.Cells(Count, 1).Value) .Cells(Count, 3).Value = Trim(.Cells(Count, 3).Value) End If Range("A1:C" & NumberOfRowsOfData).Sort key1:=Range("C1:C" & NumberOfRowsOfData), order1:=xlAscending, Header:=xlNo Next Count End With End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/37594319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: g++ unable to find standard lib functions I'm trying to compile g++ source code. The code is from a research group in Taiwan. Presumably the code compiles for them just fine. However, when I compile, g++ is unable to find standard lib methods such as atoi and abort. I get the following error when I try to compile: grdb/parser.cpp: In member function ‘virtual void Parser07::parse(Builder*)’: grdb/parser.cpp:40: error: ‘abort’ was not declared in this scope grdb/parser.cpp: In member function ‘void Parser07::parseRoutingRegion()’: grdb/parser.cpp:55: error: ‘atoi’ was not declared in this scope I'm using g++ 4.4.7. Programs I write are able to compile using those functions. I was just wondering if I was forgetting something stupid. Again, this code is able to work for the group I got it from. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/23447369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update href in AngularJS before navigating to the URL In an AngularJS application I have the following code: <a target="_blank" ng-href="{{someProperty.href}}" ng-click="someMethod($event)">Hello!</a> Now, someMethod() and someProperty belong to the same service. Initially, someProperty.href has a default value. What I need to do is that when the user clicks on the link, some calculation is performed and someProperty.href gets a new value. This new value need to be reflected in the ng-href and the user should be redirected to that new href. A: tried reconstructing it and it seems to work, clicking on the link opens a new tab with the new url. https://plnkr.co/edit/gy4eIKn02uF0S8dLGNx2?p=preview <a target="_blank" ng-href="{{someService.someProperty.href}}" ng-click="someService.someMethod()"> Hello! <br/> {{someService.someProperty.href}} </a> A: You can do it as like the below code ;(function(angular) { angular.module('myApp.directives') .directive('myExample', myExample); myExample.$inject = ['$timeout']; function myExample($timeout) { return { restrict: 'A', scope: { myExample: '&', ngHref: '=' }, link: function(scope, element, attrs) { element.on('click', function(event) { event.preventDefault(); $timeout(function() { scope.myExample(); scope.$apply(); var target = attrs.target || '_blank'; var url = scope.ngHref; angular.element('<a href="' + url + '" target="' + target + '"></a>')[0].click(); }); }); } }; } })(angular); In Controller ;(function(angular) { 'use strict'; angular.module('myApp.controllers').controller('HomeController', HomeController); HomeController.$inject = ['$scope']; function HomeController($scope) { $scope.url = 'http://yahoo.com'; $scope.someFunction = function() { $scope.url = 'http://google.com'; }; } })(angular); In HTML You can use like <div ng-controller="HomeController"> <a ng-href="url" my-example="someFunction()" target="_blank">Click me to redirect</a> </div> Here instead of ng-click I have used custom directive which simulates the ng-click but not as exactly as ng-click If the parent scope function is async you change your directive and someFunction in controller as like below @Directive ;(function(angular) { angular.module('myApp.directives') .directive('myExample', myExample); myExample.$inject = ['$timeout']; function myExample($timeout) { return { restrict: 'A', scope: { myExample: '&', ngHref: '=' }, link: function(scope, element, attrs) { element.on('click', function(event) { event.preventDefault(); scope.myExample().then(function() { $timeout(function() { scope.$apply(); var target = attrs.target || '_blank'; var url = scope.ngHref; angular.element('<a href="' + url + '" target="' + target + '"></a>')[0].click(); }); }); }); } }; } })(angular); @Controller ;(function(angular) { 'use strict'; angular.module('myApp.controllers').controller('HomeController', HomeController); HomeController.$inject = ['$scope', '$q']; function HomeController($scope, $q) { $scope.url = 'http://yahoo.com'; $scope.someFunction = function() { var deferred = $q.defer(); $scope.url = 'http://google.com'; deferred.resolve(''); return deferred.promise; }; } })(angular); Here I just simulated the async, it may be your http call too A: make sure the value in href tag is updated after you click on it. Try debugging the ng-click function. According to the official documentation: Using AngularJS markup like {{hash}} in an href attribute will make the link go to the wrong URL if the user clicks it before AngularJS has a chance to replace the {{hash}} markup with its value. Until AngularJS replaces the markup the link will be broken and will most likely return a 404 error. The ngHref directive solves this problem. In your case, i think the old link is not getting updated with the new values of the model. Hence, redirecting to old link. A: Try calling a function on ui-sref or ng-href which will return the state name that you want to redirect. Something like this html: <a ui-href="{{GetUpdatedHref()}}" >Hello!</a> controller.js $scope.GetUpdatedHref = function(){ //perform your http call while it's being processed show a loader then finally return the desired state (page location) return "main.home" } If this doesn't work for you use ng-click instead of ui-sref and then $state.go("main.home") inside function. Hope this may resolve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/44176607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is an update with a join standard sql compliant Is the following standard SQL compliant? If not, then why not? UPDATE a SET a.Y = 2 FROM TABLE_A a INNER JOIN TABLE_B b ON a.X = b.X WHERE b.Z = blahblah A: The ANSI compliant way to write the query is: UPDATE TABLE_A SET Y = 2 WHERE b.Z = blahblah AND EXISTS (SELECT 1 FROM TABLE_B b WHERE TABLE_A.X = b.X); To the best of my knowledge, neither ANSI nor ISO provide rationales for why they do not do something. I could speculate that the FROM clause causes issues when there are multiple matches on a given row. Personally, I would not want to be in the room during the arguments about which order the updates take place.
{ "language": "en", "url": "https://stackoverflow.com/questions/32267841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple include(s) in analysis_options.yaml? I'd like to combine two (or more) analysis_options.yaml files for my project but wasn't able to find a way how to do that. This works: include: package:pedantic/analysis_options.yaml ... This works too: include: package:flutter/analysis_options_user.yaml # note different "base" lint rules ... But I'd need something like this: include: - package:pedantic/analysis_options.yaml - package:flutter/analysis_options_user.yaml ... ...which results in following error: warning: The include file - package:pedantic/analysis_options.yaml - package:flutter/analysis_options_user.yaml in /home/.../analysis_options.yaml cannot be found. (include_file_not_found at [...] analysis_options.yaml:1) Has anyone encountered/resolved same problem? A: You can only include one analysis options file. Plus package:pedantic/analysis_options.yaml and package:flutter/analysis_options_user.yaml enforce different rules. Example: * *Pedantic does not use empty_statements *analysis_options_user.yaml uses it
{ "language": "en", "url": "https://stackoverflow.com/questions/57360923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: I can't input/output a character string to make a business card book. numbers become # -*- coding: utf-8 -*- class NameCard: def __init__(self, name, age, IG, phone): self.name = name self.age = age self.IG = IG self.phone = phone def __str__(self): return "name: {}, age: {}, IG: {}, phone: {}"\ .format(self.name, self.IG, self.age, self.phone) def get_menu(): while True: try: menu = int(input("menu: ")) return menu except: print("You entered the menu incorrectly. Please re-enter.") def get_namecard_info(): name = input("name: ") age = input("age: ") IG = input("IG: ") phone = input("phone: ") card = NameCard(name, age, IG, phone) return card def find_namecard(namecard_list, phone): for i, card in enumerate(namecard_list): if phone==card.phone: return i return -1 namecard_list = [] while True: print("INSERT(1), SEARCH(2), MODIFY(3), DELETE(4), EXIT(0)") menu = get_menu() if menu==1: new_card = get_namecard_info() namecard_list.append(new_card) elif menu==2: find_phone = input("The phone number of the person you are looking for : ") index = find_namecard(namecard_list, find_phone) if index>=0: print(namecard_list[index]) else: print("No data found.") elif menu==3: print("Select menu number 3") elif menu==4: print("Select menu number 4") elif menu==5: print("Select menu number 5") for card in namecard_list: print(card) elif menu > 5: print("You entered the menu incorrectly. Please re-enter.") elif menu==0: break ** If I enter a name, I get this error. ** enter image description here ** But when I input a number, it works normally. ** enter image description here It's probably a data type problem, but I don't know which part is wrong. As far as I know, python does not have to declare the data type of a variable when receiving input, which is the difference from the C language. Does it change when using a class or function or when using the format function? What code do I need to modify to make it work? A: What version of Python are you using? This seems to be happening for versions prior to 3 in which input has a different behavior: input() error - NameError: name '...' is not defined You could try with name = raw_input("name: ") instead as pointed out in the answer. A: I tested your script and it's working fine in my system as well as I checked the code that also seems OK . Here is the output I have tested it in VS Code using Python 3.8.5 in the 64-bit system. So maybe the problem is in the version of Python because before Python3 there was a notion of raw_input. Let me know your Python version.
{ "language": "en", "url": "https://stackoverflow.com/questions/68528199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open graph fitness.runs returning no data I have a bunch of Nike+ run data which i'm assuming (based on the below article) is published to the open graph. It certainly looks that way in my timeline. https://developers.facebook.com/blog/post/2012/08/29/early-success-stories--fitness-and-open-graph/ Frustratingly while my music.listens request works fine and returns all of my Spotify listens, my request for fitness.runs returns no data. Is this simply because Nike haven't integrated correctly with the Open Graph. Or perhaps I need to request extended permissions in my Auth token? https://developers.facebook.com/docs/reference/opengraph/action-type/fitness.runs Any ideas? A: As with all actions you need the correct permissions, in this case user_actions.fitness So the data returned from /me/fitness.runs for Nike will look like { "data": [ { "id": "10101118696330517", "from": { "name": "Philippe Harewood", "id": "13608786" }, "start_time": "2013-03-22T23:15:56+0000", "end_time": "2013-03-22T23:26:36+0000", "publish_time": "2013-03-24T15:50:00+0000", "application": { "name": "Nike", "namespace": "nikeapp", "id": "84697719333" }, "data": { "course": { "id": "476811255725972", "url": "http://nikeplus.nike.com/plus/activity/running/detail/2118587303?external_share_id=CE32E1C4-93D8-48A7-A08F-6D5B4C13EE6A&is_new_meta=true", "type": "fitness.course", "title": "1.12 miles" } }, "type": "fitness.runs", "no_feed_story": false, "likes": { "count": 0, "can_like": true, "user_likes": false }, "comments": { "count": 0, "can_comment": true, "comment_order": "chronological" } }, { "id": "10101118696155867", "from": { "name": "Philippe Harewood", "id": "13608786" }, "start_time": "2013-03-19T22:03:32+0000", "end_time": "2013-03-19T22:18:37+0000", "publish_time": "2013-03-24T15:49:46+0000", "application": { "name": "Nike", "namespace": "nikeapp", "id": "84697719333" }, "data": { "course": { "id": "502469216483599", "url": "http://nikeplus.nike.com/plus/activity/running/detail/2118587302?external_share_id=EBF6BC1D-BDEA-4EE5-B18D-FBC576610F13&is_new_meta=true", "type": "fitness.course", "title": "1.49 miles" } }, "type": "fitness.runs", "no_feed_story": false, "likes": { "count": 0, "can_like": true, "user_likes": false }, "comments": { "count": 0, "can_comment": true, "comment_order": "chronological" } } ], "paging": { "next": "https://graph.facebook.com/13608786/fitness.runs?limit=25&offset=25&__after_id=10101118696155867" } }
{ "language": "en", "url": "https://stackoverflow.com/questions/15641389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What algorithm can compute the edit distance between two strings with arbitrary insert, delete, replace and swap costs? I want to compute the edit distance between two strings, using 4 operations: character insertion, deletion, replacement and swapping. Each operation is associated with a cost. For instance, if the first three costs are equal to 10 and the last is equal to 1, we have: distance(abc,bca) = 2 (swap a and b then swap a and c) distance(abc,bae) = 11 (swap b and a then replace c by e) distance(abcd,bdca) = 4 I read the Wikipedia article about Damerau-Levenshtein distance, but the algorithm they give works only if 2 × swapping cost ≥ insert cost + delete cost.
{ "language": "en", "url": "https://stackoverflow.com/questions/47143825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to merge master into branch in github for windows? I am new to github and try to merge master branch into my branch then commit my work ,how I can do that using github for windows . A: If your trying to do a merge for a local branch use http://www.wdtutorials.com/drupal-7/github-windows-tutorial-3-branching-local-merging#.VYsBlRNVhBc This is a pretty good github source for beginners. http://rogerdudler.github.io/git-guide/ A: open terminal cd to your local root git add . git commit -m "your commit" git push This will move all of your local changes to master *If you are working with someone else that has updated code you will need to do a git pull before the push
{ "language": "en", "url": "https://stackoverflow.com/questions/31033844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TimesTen database connection issue in python I have 2 machines setup: * *RDP terminal with timesten client 11.2.1 and pyodbc==3.0.7 and works great. I use this connection string: cnxn = pyodbc.connect('DSN=myhostip;UID=myusername;PWD=mypass') *local machine with timesten client 11.2.2 and pyodbc==4.0.22 (I've also tried older versions, like 3.0.7) and when I use the connection string: cnxn = pyodbc.connect('DSN=myhostip1;UID=myusername1;PWD=mypass1') I get this error: pyodbc.Error: ('HY010', u'[HY010] [Microsoft][ODBC Driver Manager] The driver is incapable of supporting the current environment attributes. (0) (SQLDriverConnect)'). Both databases on both machines are practically the same, so difference is only in timesten driver version. Or what else could be the problem? I have set up DSNs on both machines, and I connect to them in SQLDeveloper. I've tried different timesten clients and pyodbc versions, but got same error everytime. It's the only way that I know of to connect to timesten DB, can anyone please help me solve this error, or maybe tell about another way,except pyodbc, to connect? A: See this answer on how to connect to TimesTen via Python: python access to TimesTen Use cx_Oracle via tnsnames.ora as this is the method that Oracle will support in TimesTen 18.1.3 Please avoid using any ODBC based method to connect to Python as none of these techniques are developed or tested by Oracle.
{ "language": "en", "url": "https://stackoverflow.com/questions/48343096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swagger-UI how much modification can be done I have some questions regarding swagger-ui. I have downloaded the swagger-ui from here and have played around with the index.html and tried modifying it. From what I understand the UI is dynamically generated based on the open api specification doc either in a yaml or json file format. My questions are as follows * *How much modification can be done to the UI that is being generated by the Swagger? *Can "Try Out" functionality be modified to have more control? What I want to do is have few input fields which are not generated by swagger and use them as input for an api call, make UI more dynamic in nature. *Does the Swagger-UI depend on any sort of API gateway to make calls to api endpoints? Thanks, Salil A: How much modification can be done to the UI that is being generated by the Swagger? Swagger UI can be tweaked in very different ways mainly via JS or CSS. You can have a look to https://swagger.io/docs/open-source-tools/swagger-ui/customization/overview/ Can "Try Out" functionality be modified to have more control? What I want to do is have few input fields which are not generated by swagger and use them as input for an api call, make UI more dynamic in nature. You should have a look to the link I shared above but not sure this is doable like this. If I had to do such kind of thing I would rather look at how to complete the original OpenAPI definition (the yaml/JSON file) before passing it to Swagger UI. Note that there is also a "interceptor" feature in Swagger UI that allow to modify requests before sending them for instance. This might interest you. Does the Swagger-UI depend on any sort of API gateway to make calls to api endpoints? Not at all. Swagger UI just uses your browser to call the API at the URL documented by the OpenAPI file. A: Stack Overflow doesn't work well when there are multiple questions as part of one "Question". Having said that, I'll answer what I know. * *As far as I can tell, you can modify the yaml or JSON source as much as you like. You can write an entire file from scratch, or import it from any editor. *For this sort of testing, I think you might want to look for a more in-depth testing tool such as Postman. That's not something I have any experience with, but from what I hear it could help with "what if I send this request?" sceanrios.
{ "language": "en", "url": "https://stackoverflow.com/questions/67672475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create PDF using iTextSharp in asp.net Can anyone tell me how to use iTextSharp.text in asp.net for creating the PDF file, but heading, font size should be as per our needs? A: Document pdfDoc = new Document(PageSize.A4, 25f, 20f, 20f, 10f); using (MemoryStream memoryStream = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); Phrase phrase = null; PdfPCell cell = null; Color color = null; pdfDoc.Open(); int columns = grdGridPrint.Columns.Count; // Table and PdfTable classes removed in version 5.XXX PdfPTable table = new PdfPTable(columns); // table.TotalWidth = 500f; phrase = new Phrase(); phrase.Add(new Chunk("Heading in PDF \n", FontFactory.GetFont("Arial", 14, Font.BOLD, Color.BLACK))); phrase.Add(new Chunk("\n", FontFactory.GetFont("Arial", 6, Font.NORMAL, Color.BLACK))); cell = ClsPDF.PhraseCell(phrase, PdfPCell.ALIGN_CENTER); cell.VerticalAlignment = PdfCell.CHUNK; // table.AddCell(cell); cell.Colspan = 7; // Colspan for Giving Spaces to Heading if you have to show data in grid of 10 columns that time Colspan =10 table.AddCell(cell); //table.HeaderRows = 1; iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, Color.BLACK); // padding can only be set for cells, __NOT__ PdfPTable object int padding = 2; float[] widths = new float[columns]; for (int x = 0; x < columns; x++) { widths[x] = (float)grdGridPrint.Columns[x].ItemStyle.Width.Value; string cellText = Server.HtmlDecode(grdGridPrint.HeaderRow.Cells[x].Text); // Cell and Color classes are gone too cell = new PdfPCell(new Phrase(cellText, fontTable)) { }; table.AddCell(cell); } // next two lines set the table's __ABSOLUTE__ width table.SetTotalWidth(widths); table.LockedWidth = true; for (int i = 0; i < grdGridPrint.Rows.Count; i++) { if (grdGridPrint.Rows[i].RowType == DataControlRowType.DataRow) { for (int j = 0; j < columns; j++) { string cellText = Server.HtmlDecode(grdGridPrint.Rows[i].Cells[j].Text); cell = new PdfPCell(new Phrase(cellText, fontTable)) { Padding = padding }; //if (i % 2 != 0) //{ // //cell.BackgroundColor = new System.Drawing.ColorTranslator.FromHtml("#C2D69B"); //} table.AddCell(cell); } } } Response.ContentType = "application/pdf"; PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); pdfDoc.Add(table); pdfDoc.Close();
{ "language": "en", "url": "https://stackoverflow.com/questions/48304174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: UIWebview without Cache I want to load a webview without cache? //Create a URL object. NSURL *url = [NSURL URLWithString:urlAddress]; //URL Request Object NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView. [kdgWebView loadRequest:requestObj]; A: Objective-C: // Remove and disable all URL Cache, but doesn't seem to affect the memory [[NSURLCache sharedURLCache] removeAllCachedResponses]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; [[NSURLCache sharedURLCache] setMemoryCapacity:0]; You can find more information in http://blog.techno-barje.fr/post/2010/10/04/UIWebView-secrets-part2-leaks-on-release/ Swift: URLCache.shared.removeAllCachedResponses() URLCache.shared.diskCapacity = 0 URLCache.shared.memoryCapacity = 0 A: You can change your cache policy, using the code: NSURLRequest *requestObj = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval: 10.0]; A: I try to answer a similar question here. I hope it was useful for you! The last solution works for HTML but not for images, css and js linked in html. How to clear UIWebView cache? A: I've tried all of these solutions but none of them work every single time. My main test was an html page with an image set as a background in the html page. This html page and image are downloaded locally on my iPad through a "sync" method i have written. The only way to keep the cache fully reset is the constantly change the url of the image in the html page so it thinks it's a unique image each time. For example in my html: <body background="image.png?v123"> So each page change i make i have to update the version number: <body background="image.png?v1234"> etc, etc. You can change the url in anyway you want, it just has to be different. Well i'm tired of doing this. Now When i download content locally, I am instead dynamically changing the containing folder's name. Since this folder is a parent folder and all of my links are relative it means i don't have to edit my html files each time. So far it seems to be working ok. I wish these other methods were consistent as it would be so much easier to simply reset the cache. So in my requests its the baseURL which is causing my cache to reset, not the query string to my url or background image, or css file, etc, etc. NSString *myURL = @"index.html"; NSURL *baseURL = [NSURL fileURLWithPath:@"FULL_PATH_TO_DOCS/MYFOLDERV123"]; [myTargetWebView loadHTMLString:myURL baseURL:baseURL];
{ "language": "en", "url": "https://stackoverflow.com/questions/9744644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Python3 Iterate over a file printing multiple lines Say I have a text file(test.txt) with the following lines line0 line1 line2 line3 line4 line5 line6 line7 line8 line9 It's easy to iterate over it fh=open("./test.txt") for x in fh: print(x) fh.close() What I'm trying to do is print lines 2 lines, like this, line0 line2 line1 line3 So essentially I'm trying to access the current line and the a line 2 lines down from the current location. I have been messing around with the itererator but not got anywhere. I'd welcome all input please. Thanks A: The easiest way would be to just read the whole file: fh = open("./test.txt") lines = fh.readlines() for i in range(len(lines) - 2): print(lines[i]) print(lines[i + 2]) A: and Welcome to Stackoverflow You can try this. left = next(fh) center = next(fh) while True: try: right = next(fh) except StopIteration: break print('{}\n{}'.format(left, right) left = center center = right This returns line0 line2 line1 line3 line2 line4 line3 line5 and so on... A: You can use itertools.tee to replicate the file iterator, skip the first two values of the second iterator returned by tee, and then zip the two iterators to produce the desired pairs of lines so that you can chain and join them for output: from itertools import tee, chain l, n = tee(fh) next(n) next(n) print(''.join(chain.from_iterable(zip(l, n)))) With your sample input, this outputs: line0 line2 line1 line3 line2 line4 line3 line5 line4 line6 line5 line7 line6 line8 line7 line9 A: also an option which does not read the whole file in one go but just stores 2 lines at a time: txt = """line0 line1 line2 line3 line4 line5 line6 line7 line8 line9""" with StringIO(txt) as file: a, b = next(file), next(file) for c in file: print(a, end='') print(c, end='') a, b = b, c with the output line0 line2 line1 line3 line2 line4 line3 line5 line4 line6 line5 line7 line6 line8 line7 line9 you'd have to replace the StringIO part with your file of course. A: Here is a generator that handles any number of lines including odd length files: def alternate(f): write = False for line in f: if not write: keep = line else: yield line yield keep write = not write if write: # handle odd-line-count files. yield line with open('test.txt') as f: for line in alternate(f): print(line,end='') Example input (odd length): line0 line1 line2 line3 line4 line5 line6 line7 line8 line9 line10 Output: line1 line0 line3 line2 line5 line4 line7 line6 line9 line8 line10
{ "language": "en", "url": "https://stackoverflow.com/questions/53563599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ajaxSetup not working, its not adding default variable field When I use $.ajaxsetup and trigger $.post, its not adding the default data to the post. or is it only meant for default data if not data supplied? <script> window.csrf = { csrf_token: '<?php echo $_SESSION['csrf_token']; ?>' }; $.ajaxSetup({ data: window.csrf }); $(document).ready(function() { // CSRF token is now automatically merged in AJAX request data. $.post('/awesome/ajax/url', { foo: 'bar' }, function(data) { console.log(data); }); }); </script> A: Move $.ajaxSetup({ data: window.csrf }); in document.ready(). And like other answers point out, if you want to send csrf-token, you have to use headers key in ajaxSetup. A: Here is the method binding the csrf token if you are using laravel In head of app.blade.php <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> In JS. // CSRF Token $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); A: You are passing data in post method which is overriding the one in ajaxSetup jQuery.post( url [, data ] [, success ] [, dataType ] ) $.post('/awesome/ajax/url', { foo: 'bar' }, function(data) Instead, you should pass it in headers, Refer How can I add a custom HTTP header to ajax request with js or jQuery?. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/52437201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Semaphores for different parts of the same shared memory block in C I have a question on how to set up a shared memory segment for my program. In my program I want to have a main structure to contain 50 different accounts. Something that looks like this. struct list{ struct account[50]; }; Within each account there is just some basic info struct account{ int x; char * y; }; Now, I want my entire list to be located in a shared memory segment as different child processes of my main process will be updating different accounts in the list. However, I only want a child process to be able to access a certain account in this list. How exactly would I go about setting up a shared memory segment that can be locked down by a child process in different parts? For example, I want a semaphore that can lock down access to account[32] in the shared memory segment. This means that another process could be updating account[29] in the shared memory segment at the same time with no problem. I am not really looking for concrete code examples (although those would be helpful), but more of a conceptual understanding of the best way to set up shared memory for this program. Thanks. A: If I understood what this is about, I see two alternatives: The first one is to modify struct account, so there's one extra field, a semaphore. Any process should P() on the semaphore before it accesses the other account's fields, and V() when it's done with it. The second would be to modify struct list, adding an extra array of semaphores, same size as the array of accounts, assigning each semaphore in the array with the same-indexed account, and using P() and V() on it again, before and after accessing the corresponding account.
{ "language": "en", "url": "https://stackoverflow.com/questions/29705697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to upload a background image using actionscript 3.0 code? Need your help. I am trying it first time. I have used following code. But i get this in my console: started loading file SecurityError: Error #2000: No active security context. and my image url is in same folder as my script file. var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, fileLoaded); loader.load(new URLRequest("C:\Documents and Settings\Owner\Desktop\23Aug\demo1\mic.jpg"), context); var context:LoaderContext = new LoaderContext(); context.applicationDomain = ApplicationDomain.currentDomain; trace("started loading file"); addChild(loader); function fileLoaded(event:Event):void { trace("file loaded"); } A: Reasons to throw securityError exception. * *Invalid path, *Trying to access a URL, that not permitted by the security sandbox, *Trying a socket connection, that exceeding the port limit, and *Trying to access a device, that has been denied by the user(Ex., camera, microphone.) try this private var _loader:Loader = new Loader(); private var _context:LoaderContext = new LoaderContext(); private var _url:URLRequest = new URLRequest("demo1/mic.jpg"); _context.checkPolicyFile = false; _loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageloaded); //_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError); _loader.load(_url, _context); private function onImageloaded(e:Event):void{ addChild(e.target.content); } A: Use slashes instead of back slashes : loader.load(new URLRequest("C:/Documents and Settings/Owner/Desktop/23Aug/demo1\mic.jpg"), context); But the best way is to use relative path like "./mic.jpg" and do not use absolute path.
{ "language": "en", "url": "https://stackoverflow.com/questions/12104291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Progress bar value not bound to data-bind value attribute using Knockout.js I have a progress bar, and I added a condition that, if the value is below 100, the color should be red; and if it is 100, the color should change to green. But when I debug the code I see the progress value return 0 even if some value is assigned to value attribute. Below is the progress bar code, and I am assigning value 100 within the data-bind attribute. <div class="card-header float-right" style="width:50%; padding-left:100px;"> <progress id="myProgress" data-bind="attr: { value: 100, }" min="0" max="100"></progress> </div> Below is the javascript code; when I debug and check progress value, it displays 0. $(document).ready(function () { var progressvalue = $("#myProgress").val(); var progressText = $("#myProgress").text(); if (progressvalue == 100) { $('#myProgress').addClass("progress-100"); $('#myProgress').removeClass("progress-below"); } else { $('#myProgress').addClass("progress-below"); $('#myProgress').removeClass("progress-100"); } }); A: You do not need the data-bind attribute from what I can see in your current code (though you may have a reason outside of what you've shown). Edit: For Knockout.js, you will of course need the data-bind attribute. All you need to do is set a value for your <progress> element, and then make sure you're updating it as whatever process it represents is progressing. <progress id="myProgress" value="10" max="100"></progress> Edit: For Knockout.js, you need to tie your data-bind attributes to a ViewModel field, and that ViewModel field would need to be associated with an Observable. You could do something like this (a toy example that just increments the progress value by 10 each second, but shows how you could update your ViewModel, as well as trigger a class change after reaching a threshold value): <div class="card-header float-right" style="width:50% ; padding-left:100px"> <progress id="myProgress" data-bind="value: progressValue, class: progressClass" max="100" ></progress> </div> <script> const INITIAL_PROGRESS = 1; const PROGRESS_THRESHOLD = 90; const BELOW_THRESHOLD_CLASS = "progress-below"; const ABOVE_THRESHOLD_CLASS = "progress-100"; let progressViewModel = { progressValue: ko.observable(INITIAL_PROGRESS), progressClass: ko.observable(BELOW_THRESHOLD_CLASS) }; ko.applyBindings( progressViewModel, document.getElementById("myProgress") ); ko.when( function() { return progressViewModel.progressValue() > PROGRESS_THRESHOLD; }, function(result) { progressViewModel.progressClass(ABOVE_THRESHOLD_CLASS); } ); for (let i = 1; i < 11; i++) { window.setTimeout(function() { progressViewModel.progressValue(i * 10); }, i * 1000); } </script> Then you have to figure out how you want your Observable value(s) updated. A: If you're using KnockoutJS, the actual progress is probably an observable property on your viewmodel. Let's say it is actually called progress, then you would bind to it like this: <div class="card-header float-right" style="width:50% ; padding-left:100px"> <progress id="myProgress" data-bind="attr: { value: progress }" min="0" max="100"></progress> </div> For styling, you should use the css or class bindings to assign a class to the progress bar, based on the progress. Here's a Fiddle with a little example, although I've used the Bootstrap progress element and not the actual native progress element since it's a nightmare to style: https://jsfiddle.net/thebluenile/20zsqn5w/
{ "language": "en", "url": "https://stackoverflow.com/questions/57961087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Size of a small window Do windows have any limit in size?. I tried to give for instance 100px and 50px in storyboard Size Inspector. When I publish it shows much larger. A: After many things, I could figure out the solution. In fact, there is no problem to make a window 100 x 50 px or even smaller. The problem is that I had to close the window of the simulator before run again. In my case, such a small window had no Title bar and no close button. So I had to publish with the Title bar, close it, stop the running and then I could run again with the new size and position I give to the window. So, without closing the window in the simulator it is not possible to see the results of a new size.
{ "language": "en", "url": "https://stackoverflow.com/questions/58365772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Function parameter is never for parameter to be used within JSON parse I'm going through my code and neatening it up to make it easier to understand. In my code, I parse the same JSON at different points to get different data from the JSON. I want to create a function which I call, and pass a parameter and it will return the information from the JSON. My JSON looks like this: { "Date": "11:10:02 28-02-19", "Number1": 2031, } The function I am trying to use is this: function dataJson(key) { fetch("http://file/location/data.json?newversion") // supported in modern browsers. .then(res => res.json()) // parses into JSON. Fails if given improper json .then(data => { return data.key; }) } and I am calling it within my script like: dataJson(Date); It should return 11:10:02 28-02-19 but I get the error Uncaught ReferenceError: Date is not defined And in VS Code it tells me that key is declared but never read. When I have this in my script I would just use data.Date and it would return what I want. How do I call the function with a parameter and pass the parameter into the JSON parse to return the data I want? A: Uncaught ReferenceError: Date is not defined Date is a variable name. You need a string. "Date". And in VS Code it tells me that key is declared but never read. .key doesn't refer to a variable. See also: Dynamically access object property using variable NB: dataJson has no return statement so it isn't going to return anything. See also How do I return the response from an asynchronous call?.
{ "language": "en", "url": "https://stackoverflow.com/questions/54924434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Dropdown menu item moves other elements to the right I've been trying to create this basic menu from scratch but I've got a little problem: whenever I hover the 'Categories' menu for example(which is a dropdown element), the elements to the right get automatically moved even farther. HTML: <div id = "navbar"> <ul> <li>News</li> <li>News</li> <li>News</li> <li>News</li> <li>Market</li> <li class = "navbar_multiple">&nbsp;&nbsp;Categories <ul> <li>Travel</li> <li>Entertainment</li> <li>Fun</li> </ul> </li> <li>Fun</li> </ul> </div> CSS: apparently too long - but included in the jsFiddle below Here's the jsFiddle: http://jsfiddle.net/ktvde9qo/4/ I want to make it so that when the user hovers over the 'Categories' item, it would create the dropdown menu under it but keep its dimension as it was. How can I do that? A: I would try the following approach using the following CSS: #navbar > ul > li { float: left; margin-left: 21px; font-family: 'Open Sans', sans-serif; font-size: 14px; text-transform: uppercase; color: #fff; border-top: 2px solid transparent; padding-top: 8px; position: relative; line-height: 1.5; height: 24px; } #navbar > ul > li > ul { list-style: none; position: absolute; /* change this */ margin-left: 0px; padding-left: 0px; margin-top: -5px; /* this can control the whitespace... */ } Add position: relative to the li elements in your primary navigation, and add some line height and height values as needed. For the secondary navigation, change position to absolute on the ul and tweak the top margin to close any whitespace. See demo at: http://jsfiddle.net/audetwebdesign/adw5hp84/ By using absolute positioning of the secondary menus, you take them out of the flow of the main menu bar and you don't have to worry that the length of the labels will affect the primary navigation layout. Note that there is probably more detailed work to be done on styling the spacing between links and so on. A: Get rid of the width in #navbar > ul > li.navbar_multiple:hover > ul > li: #navbar > ul > li.navbar_multiple:hover > ul > li { display:block; height:20px; padding-left: 10px; margin-left: 0px; } Updated your fiddle: http://jsfiddle.net/ktvde9qo/11/ EDIT: To make all submenu items have the same width, simply remove (or comment out) the following lines, alternatively modify them for your needs: #navbar > ul > li > ul > li:first-child { margin-top: 8px; padding-top: 9px; width: 100%; } Fiddle updated: http://jsfiddle.net/ktvde9qo/13/ EDIT 2: To make the submenu items longer than the main menu item, just add a longer width to the submenu item and a shorter one to the main: The submenu item: #navbar > ul > li > ul > li { padding-left: 0px; display: none; text-transform: none; font-size: 12px; padding: 4px 4px 8px 6px; padding-top: 10px; border-top: 1px solid #39718e; background-color: #316885; width:200px; /* changed this */ } The main menu item: #navbar > ul > li.navbar_multiple { margin-left: 13px; width:100px; /* changed this */ } Final fiddle update: http://jsfiddle.net/ktvde9qo/18/ A: Can you try it? If contents will add in drop down list like Entertainment to Entertaiment Daily Programs also this will be works #navbar > ul > li > ul{ width:150px; } A: I think you are looking for something like that: css #navbar { height: 35px; background-color: #4c9fcd; position: relative; top: 0px; z-index: 1001; } #navbar > ul { list-style: none; text-align: left; padding-left: 25px; margin-top: 0px; } #navbar > ul > li { float: left; margin-left: 21px; font-family: 'Open Sans', sans-serif; font-size: 14px; text-transform: uppercase; color: #fff; border-top: 2px solid transparent; padding-top: 8px; } #navbar > ul > li:first-child { margin-left: 0px; } #navbar > ul > li.navbar_multiple { margin-left: 13px; //padding-left: 5px; } #navbar > ul > li:hover { border-top: 2px solid white; cursor: pointer; //background-color: #316885; } #navbar > ul > li > ul { list-style: none; position: relative; margin-left: 0px; padding-left: 0px; } #navbar > ul > li > ul > li { padding-left: 0px; display: none; text-transform: none; font-size: 12px; padding: 4px 4px 8px 6px; padding-top: 10px; border-top: 1px solid #39718e; background-color: #316885; } #navbar > ul > li > ul > li:first-child { margin-top: 8px; padding-top: 9px } #navbar > ul > li > ul > li:last-child { border-bottom: 3px solid #4c9fcd; } #navbar > ul > li.navbar_multiple:hover > ul > li { display: block; height:20px; padding-left: 10px; margin-left: 0px; } #navbar > ul > li.navbar_multiple > ul > li:hover { background-color: #0d3f5a; } #navbar > ul > li.navbar_multiple:hover { background-color: #316885; padding-right: 0px !important; } fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/25742383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Update a scrollview image based on a UISwitch on a modal view Let me explain. I have an iPhone app, nearly, that displays an image in a scrollView controlled by the MainViewController. I open an OptionsView that shows a UISwitch that is linked to the settings bundle. The link to the settings is all good. When the user clicks the UISwitch on the OptionsView and clicks the Done button, I want to close the modal view and for the image to be replaced with the alternative image. An On image, or an Off image. The NSUserDefaults are all correct, and I have an if/else in the MainViewController under the ViewDidLoad method. This works each time the app is loaded into the simulator, but doesn't control the image when the app is running and the UISwitch is changed. It seems to me that the if/else should be in something other than ViewDidLoad or I need to get the Done button to somehow update the image. Could anyone point me in the right direction? A: Did you synchronized the NSUserDefaults after changing the value of the switch? Try calling [[NSUserDefaults standardUserDefaults] synchronize]; after you set the new value and see if that helps. Also try moving your if/else statement in the - (void)viewWillAppear:(BOOL)animated method because - (void)viewDidLoad is only called once when the view is loaded but not when the modal view is closed.
{ "language": "en", "url": "https://stackoverflow.com/questions/6832606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Failed to register device When I run googlesamples-assistant-pushtotalk --device-model-id 'my-model-id' project-id 'my-project-id' I get the following error: NFO:root:Connecting to embeddedassistant.googleapis.com WARNING:root:Device config not found: [Errno 2] No such file or directory: '/Users/rick/Library/Application Support/googlesamples- assistant/device_config.json' INFO:root:Registering device ERROR:root:Failed to register device: { "error": { "code": 403, "message": "Could not create the device instance. Account doesn't have permission to perform this operation for project sign-language-with-nao. See https://developers.google.com/assistant/sdk/guides/library/python/embed/register-device", "status": "PERMISSION_DENIED" } } I used google-oauthlib-tool and confirmed access with the account of the projects owner. I also set up a device-model (with googlesamples-assistant-devicetool register-model) which worked fine. I'm on mac using python 3.6 and google-assistant-sdk 0.4.2 Any Ideas what permissions are missing? I made sure my Account is the owner of the project. A: Check the .asoundrc file on the /home/pi folder. Mine did the same thing because I had extra commands in that file that mucked everything up.
{ "language": "en", "url": "https://stackoverflow.com/questions/48622331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dependsOnMethods which returns a value I have a trivial scenario in which a method is dependent on other method. And the other method returns a value - So the class looks as - public class Temp1 { @Test public Integer test1() { Reporter.log("<b>in test1</b>"); System.out.println("in test1"); return null; } @Test(dependsOnMethods={"test1"}) public void test2() { Reporter.log("in test2"); System.out.println("in test2"); } } Now when I execute this, I encounter following exception - org.testng.TestNGException: com.core.tests.Temp1.test2() is depending on nonexistent method com.core.tests.Temp1.test1 at org.testng.internal.MethodHelper.findMethodsNamed(MethodHelper.java: 143) at org.testng.internal.MethodHelper.topologicalSort(MethodHelper.java: 472) at org.testng.internal.MethodHelper.sortMethods(MethodHelper.java: 544) at org.testng.internal.MethodHelper.internalCollectAndOrderMethods(MethodHelper.java: 77) at org.testng.internal.MethodHelper.collectAndOrderMethods(MethodHelper.java: 49)......................... Though if there is no return type with method test1(), it works well. Is there any way to get through this? Thanks ~T A: Although it seems not to be mentioned in the documentation, I also experienced that classes annotated with @Test must have a void return type. If you need data provided by some other method, you could try the Data Provider mechanism of TestNG.
{ "language": "en", "url": "https://stackoverflow.com/questions/4688509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Count(*) and Count(field_name) return difference output in oracle There are two simple queries (because they are so simple, I am confused): The first one: select count(*) from (select e.id as employee_id from offic o left join employee e on o.employee_id = e.id) where employee_id is null The second one: select count(employee_id) from (select e.id as employee_id from offic o left join employee e on o.employee_id = e.id) where employee_id is null The only difference between these two query is count(employee_id) and count(*), the rest of them exactly are same but the result of them are difference. The second query return zero while there are some null value. What is wrong or some thing else that I do not know? A: The second query counts rows that have a non-empty (NOT NULL) EMPLOYEE_ID column value. The first one counts all rows, regardless what's in EMPLOYEE_ID. [EDIT: a simple example which shows what's being counted] Reading comments below, well, some of them seem to be wrong (or I misunderstood the author's intent) so - here you go (based on 11.2.0.4.0). SQL> select * From a1_test; COL1 COL2 COL3 ---------- ---------- ---------- 1 3 1 2 1 2 3 2 3 3 SQL> SQL> select 2 count(*) cnt, 3 count(1) cnt_1, 4 count(2) cnt_2, 5 count(3) cnt_3, 6 -- 7 count(col1) cnt_c1, 8 count(col2) cnt_c2, 9 count(col3) cnt_c3 10 from a1_test; CNT CNT_1 CNT_2 CNT_3 CNT_C1 CNT_C2 CNT_C3 ---------- ---------- ---------- ---------- ---------- ---------- ---------- 5 5 5 5 3 3 4
{ "language": "en", "url": "https://stackoverflow.com/questions/51925681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MVC "post back" DropDown List onchange when selected Here is what I have so far: @Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = "UpdateProduct(this);" }) <script language="JavaScript"> $('#id').on('change', function () { var data = { prodID: 5, catID: 8 }; // < added test values $.post('GiftList/UpdateProduct', data, function (responseData) { //callback function }); }); </script> This is my action method for the Update : [HttpPost] public ActionResult UpdateProduct(int prodID, int catID) { ........ product.Category= catID; _productService.UpdateProduct(product); ... I just don't' know how to "wire" it all. Original question: I have a DropDown that, when an item is Selected, some code is run and the Product table in the database is updated. This dropdown contains items from the Category Table (id and name): @Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = "UpdateProductsDB(this);" }) I'll need to pass in the 'id' field from the Category selected. I also need to pass in the Product Id from the Product table for the update. I have access to the Product Id ('id') in the View by: @foreach (var item in Model.Products) { .... item.Id A hidden field I added: <input id="item_Id" name="item.Id" type="hidden" value="43" /> Is this even possible with MVC? From my searches, it seems jQuery will do it. Please give as many details as you can because I don't know jQuery at all. <tr><span >Panasonic HDC-SDT750K</span> <input id="item_Id" name="item.Id" type="hidden" value="41" /> </tr> <tr> <td width="125px" height="20px" align="right">Model: </td> <td width="325px" align="left"> <span style="display:inline-block;width:325px;"></span> </td> ................ <select id="id" name="id" onchange="UpdateProductsDB(this);"> <option value="5">Accessories</option> <option selected="selected" value="1">Desktops</option> <option value="8">Camera, photo</option> <option value="9">Cell phones</option> <option value="12">Jewelry</option> . . . </select> </td> <td ><a href="/DBMJ33/GiftList/Edit/id41">Edit</a></td> <td ><a href="/DBMJ33/GiftList/Delete/id41">Delete</a> A: This should get you on the right track. //your javascript $('#myDropdown').on('change', function(){ var data = {someData : someDataValue, someMoreData : someMoreDatavalue}; $.post('myControllerName/UpdateProduct', data, function(responseData){ //callback function }); }); //in your controller [HttpPost] public ActionResult UpdateProduct(int someData, string someMoreData) { //do something with your data } A: Try this @Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = string.Format("UpdateProductsDB(this, {0})", item.id) }) And your UpdateProductsDB function will now accept id as well. function UpdateProductsDB(categorySelected, productId) { ... } Also depending on the type of your id, if it is an integer than you can just use: string.Format("UpdateProductsDB(this, {0})", item.id) But if it is a GUID or a string you will have to put single quotes around: string.Format("UpdateProductsDB(this, '{0}')", item.id) A: Turns out I didn't need jQuery or AJAX at all, just these 3 lines. When an item is selected in the drop down, this "posts back" or runs immediately : @using (Html.BeginForm("UpdateProduct", "GiftList")) { @Html.Hidden("prodID", item.Id) @Html.DropDownList("catID", (SelectList)ViewBag.Values, new { onchange = "this.form.submit();" }) }
{ "language": "en", "url": "https://stackoverflow.com/questions/23367157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: @Valid and @RequestBody in controller method I have a strange issue that I cant resolve or find the answer to. I've defined my own validator: @Component public class SingleInstanceValidator implements ConstraintValidator<SingleInstanceRule, Plan> { @Autowired(required = true) private UserService userService; ... } Without the @Valid annotation I cant get the injection to work and instead need to inject like this. @Component public class SingleInstanceValidator implements ConstraintValidator<SingleInstanceRule, Plan> { @Autowired(required = true) private UserService userService; @Override public void initialize(SingleInstanceRule singleInstanceRule) { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } ... } This worked to make it inject the UserService. However, with this solution I could not get @ExceptionHandler to work and the injection would also fail in our tests. With @Valid I can make both the injection and @ExceptionHandler to function properly (catching BindException.class) However... and this is the issue I dont get. I cannot use @RequestBody together with @Valid, the @Autowired doesnt work then, and the @ExceptionHandler wont work. So before we had this: @RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=UTF-8") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Plan create(@RequestBody final Plan entity) throws Exception { ... } and now I want this: ... (same annotations before) public Plan create(@Valid @RequestBody final Plan entity) throws Exception { ... } But this will fail. I tried and figured this would work and it did ... (same annotations before) public Plan create(@Valid Plan entity) throws Exception { ... } But we need to have the @RequestBody annotation, otherwise some relations are lost of the Plan entity. Does anyone have any idea how we could achieve using both @Valid and @RequestBody and still be able to autowire the custom validator and handle exceptions using the @ExceptionHandler annotation?
{ "language": "en", "url": "https://stackoverflow.com/questions/25724736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make the calendar inverted colors, or change other color characteristics? Background: At time of writing, Fomantic-UI is the live-development fork of Semantic-UI which will one day be rolled into Semantic-UI and is for the mean time the de facto supported genus of Semantic-UI. Fomantic has a capable calendar / date picker, but how can I make it appear with inverted colors? $('#standard_calendar') .calendar(); $('#inverted_calendar') .calendar({ className: { table: 'ui inverted celled center aligned unstackable table' } }); <link href="https://fomantic-ui.com/dist/semantic.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://fomantic-ui.com/dist/semantic.js"></script> <body> <div class='daContent'> <p> An example of a Fomantic calendar. </p> <span>Standard colors calendar</span> <div class="ui calendar" id="standard_calendar"> <div class="ui input left icon"> <i class="calendar icon"></i> <input type="text" placeholder="Date/Time"> </div> </div> </p> </body> A: Copied from a Disord conversation: The answer is to include a setting for the calendar table css within the calendar invocation JS. See snippet below where I have added the second, inverted calendar to illustrate. Notes: It appears that the ccalendar > className > table CSS setting is an entire replacement for the table css class settings. As a benefit, this could allow more refined tweaking. As a negative, if the component CSS were altered and our code remained unaltered then this might be a breaking change case. $('#standard_calendar') .calendar(); $('#inverted_calendar') .calendar({ className: { table: 'ui inverted celled center aligned unstackable table' } }); <link href="https://fomantic-ui.com/dist/semantic.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://fomantic-ui.com/dist/semantic.js"></script> <body> <div class='daContent'> <p> The first calendar is using standard colors, the second is inverted. </p> <span>Standard colors calendar</span> <div class="ui calendar" id="standard_calendar"> <div class="ui input left icon"> <i class="calendar icon"></i> <input type="text" placeholder="Date/Time"> </div> </div> </p> <p> <span>Inverted colors calendar</span> <div class="ui calendar" id="inverted_calendar"> <div class="ui input left icon"> <i class="calendar icon"></i> <input type="text" placeholder="Date/Time"> </div> </div> </p> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/59820486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java greater than, less than comparison I'm kind of confused because of my code and what to really search so please help me, I have integers they varry from 1 to the maximum amount of integers, what code should I use for example I want every integer less than 1000 to be equal to 1 and less than 2000 to be equal 2, and so on, is there an automatic comparison in java instead of doing each thousand by its own? EDIT: I want when it is also 1000 or 2000 or what ever to be exactly as divided by without adding one, so 1000 is equal to 1, is there a way to check if there is a remainder? A: I believe you simply need: int newNum = ( num - 1 ) / 1000 + 1; This gives you: 0 -> 1 1 -> 1 300 -> 1 979 -> 1 1000 -> 1 1015 -> 2 1999 -> 2 2000 -> 2 2001 -> 3 A: Apparently what I wanted was int i = 1000; if (i % 1000 >0){ i = i/1000 + 1; } else{ i = i/1000; } System.out.print(" " + i); thanks anyways for helping, I just didn't realize it was a single stupid thing
{ "language": "en", "url": "https://stackoverflow.com/questions/34567844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting a nodejs buffer into a javascript object with functions I know that converting a buffer to a json object is trivial with: JSON.parse(buffer) But what about converting a buffer that contains a javascript object with functions to a real javascript object ?? I have files that contact objects with functions and I need to read these files in and save them to another master object. While the task of reading the files is not a problem, I cannot find any way of converting the buffer back into a real javascript object again. This is a very simple example of a file 'test.js' that I am trying to load { get:function(){return 'hello'}, somevar: "xxx", put: function(){return 'world'} } Reading this data in it is a buffer, I can't convert using JSON as this contains functions and I cannot read using utf8 encoding as it will become a string ! var funcs = {} fs.readFile('test.js',function(err,buff){ funcs['test'] = buff; }) Is it possible to read a file and convert it into a real javascript object ? Edit OK, I have found a solution but it is using the dreaded eval(), however this is backend code and as far as I can tell there's no way for anything to be injected by a user from the frontend, I would prefer not to use it but unless there's anything that will work without modifying the format of the files, I will use it: var funcs = {} fs.readFile('test.js','utf8',function(err,buff){ eval('var_='+buff); funcs['test'] = _; }) A: For what it's worth, you could use the Function constructor. It's slightly safer than eval because it doesn't access the local scope. But it can still access global variables. var script = buffer.toString('utf8'); // assuming the file is in UTF-8 var returnObject = new Function('return ' + script); var myObject = returnObject(); A: Depending on the complexity of the code you're dealing with, this approach may or may not suit your needs: You can create a temporary file, say "test-module.js", which includes the object from "test.js" but with a module export prependend, for example: module.exports = { get: function() { return 'hello' }, somevar: 'xxx', put: function() { return 'world' } } Then, from your main file, you can retrieve the file content already available as a Javascript object: var funcs = {} var buff = require('./test-module'); funcs['test'] = [buff.get, buff.put]; Would this solution work for you?
{ "language": "en", "url": "https://stackoverflow.com/questions/48606358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: external multithreading sort I need to implement external multithreading sort. I dont't have experience in multithreading programming and now I'm not sure if my algorithm is good anoth also I don't know how to complete it. My idea is: * *Thread reads next block of data from input file *Sort it using standart algorith(std::sort) *Writes it to another file *After this I have to merge such files. How should I do this? * *If I wait untill input file will be entirely processed until merge I recieve a lot of temporary files *If I try to merge file straight after sort, I can not come up with an algorithm to avoid merging files with quite different sizes, which will lead to O(N^2) difficulty. Also I suppose this is a very common task, however I cannot find good prepared algoritm in the enternet. I would be very grateful for such a link especially for it's c++ implementation. A: Well, the answer isn't that simple, and it actually depends on many factors, amongst them the number of items you wish to process, and the relative speed of your storage system and CPUs. But the question is why to use multithreading at all here. Data too big to be held in memory? So many items that even a qsort algorithm can't sort fast enough? Take advantage of multiple processors or cores? Don't know. I would suggest that you first write some test routines to measure the time needed to read and write the input file and the output files, as well as the CPU time needed for sorting. Please note that I/O is generally A LOT slower than CPU execution (actually they aren't even comparable), and I/O may not be efficient if you read data in parallel (there is one disk head which has to move in and out, so reads are in effect serialized - even if it's a digital drive it's still a device, with input and output channels). That is, the additional overhead of reading/writing temporary files may more than eliminate any benefit from multithreading. So I would say, first try making an algorithm that reads the whole file in memory, sorts it and writes it, and put in some time counters to check their relative speed. If I/O is some 30% of the total time (yes, that little!), it's definitely not worth, because with all that reading/merging/writing of temporary files, this will rise a lot more, so a solution processing the whole data at once would rather be preferable. Concluding, don't see why use multithreading here, the only reason imo would be if data are actually delivered in blocks, but then again take into account my considerations above, about relative I/O-CPU speeds and the additional overhead of reading/writing the temporary files. And a hint, your file accessing must be very efficient, eg reading/writing in larger blocks using application buffers, not one by one (saves on system calls), otherwise this may have a detrimental effect if the file(s) are stored on a machine other than yours (eg a server). Hope you find my suggestions useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/38932827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Select all a-elements that enclose img-elements I am searching. I am searching. Preferably, I would like an CSS-Selector, if not possible, jquery selector would also be nice. A: As it currently is, there are no parent selectors in CSS - yet anyways. You can use the :has selector in jQuery. $('a:has(img)').css("background","red"); jsFiddle example A: jQuery Selector: var anchorThatContainsImage = $('a:has(img)'); Or: $('img').each(function(){ var anchorThatContainsImage = $(this).parent('a'); }); A: With CSS selectors this is currently impossible. It may be possible in Selectors Level 4 with the putative subject identifier, but that is still some way in the future. It is possible with a jQuery selector, however. It's the :has selector: $('a:has(img)') or, more optimally, the has method: $('a').has('img') A: $('a img').parent (); $('a').filter (function () { return $(this).find ('img').length > 0; });
{ "language": "en", "url": "https://stackoverflow.com/questions/19775348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: Laravel - Schedule job for each premium users What I need to do When user purchase premium, I give him premium money. Every week, I need to give premium money again at subscription time. However, if the user is no longer a subscriber, they should no longer receive their premium money. Questions I think I need to use scheduled tasks, but I do not know how to do that on right way. * *How to add tasks dynamically ? *Do I need to put the tasks in the database tasks table ? *How to remove task if user is unsubscribed ? (the check is made in my job but how to remove the task if is unsubscribe) Code I need to run this task. $schedule->job(new CreditPremiumUser($userId))-> weeklyOn(1, '10:42:53'); // 1 = premium purchase day // '10:42:53' = subscription time A: What i did Create table tasks Schema::create('tasks', function (Blueprint $table) { $table->id(); $table->string('type'); // optional $table->string('frequency_function'); $table->string('frequency_params')->nullable(); // optional $table->string('job_name')->nullable(); // optional $table->integer('user_id')->nullable(); // optional $table->timestamps(); }); /* Example task data type = 'subscription_credit' frequency_function = 'weeklyOn' frequency_params = 'a:2:{i:0;i:3;i:1;s:5:"12:20";}' // serialize(array(3, '12:20')) job_name = App/Jobs/Premium/CreditPremiumMoney user_id = 1 */ I need to schedule Job so I have job_name column. For example, depending on your needs, you can add command_name column if you want to schedule the execution of a command. Update Kernel In your App\Console\Kernel.php schedule method write: protected function schedule(Schedule $schedule) { $tasks = Task::all(); foreach ($tasks as $task) { $type = $task->type; // optional $frequencyFunc = $task->frequency_function; $frequencyFuncParams = $task->frequency_params ? unserialize($task->frequency_params) : []; if ($type === 'subscription_credit') { // optional $job = $task->job_name; $userId = $task->user_id; $schedule->job(new $job($userId), 'low', 'redis') ->$frequencyFunc(...$frequencyFuncParams); } else if ($type === '...') { // Other optional type logic } } } You can remove type condition if you do not need it or add multiple types logic if you need type. Try It Add all your tasks to your database. Local Run command php artisan schedule:work and the scheduler will run to process your tasks at the scheduled dataTime Production Add CRON to your server like here On each environment, the scheduler will run every minute and check if there are tasks to execute in tasks table.
{ "language": "en", "url": "https://stackoverflow.com/questions/72895253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set a style for a cell in datagrid I am using a datagrid in flex and need to render each cell with a different style. What could be the best way to set a style to a perticular cell in datagrid/advanced datagrid (flex)? I think one possible option can be extend the datagrid and override the drawRowBackgroungd function. Apart from this can i use some custom item renderer or some property similar to label function of a series, there it used to return label here we need a style. Thanks in advance. A: I think Item renderers are your best option, you can use a canvas as your renderer and do whatever to it based on the data of that cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/2182586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert unicode F1 emojis for use in telegram I can't get all emojis to display correctly and as it seems While any unicode starting with 1F is not accepted by javascript. \1F21A This seems to work \u26a0 How to get the ones starting with 1F to work? slimbot.sendMessage('-xxxxx', ` \u1f4c8`) A: You're probably looking for the \u{1f4c80} escape sequence, which allows arbitrary codepoints not just 4-digit charcodes like \u1234.
{ "language": "en", "url": "https://stackoverflow.com/questions/62869980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom UIViewControllerContextTransitioning and black screen I have a UITableViewController, inside my UITableViewCell i have an imageView when the user taps on it, i present it modally using my own custom UIViewControllerContextTransitioning to make a zoom effect on it, it works like a charm the problem is that when the animation completes and i call the [transitionContext completeTransition:YES]; My UITableView which is now behind my Modal UIViewController is removed form the view hierarchy so i got a black screen behind it [containerView addSubview:toViewController.view]; [UIView animateWithDuration:duration delay:0.0 usingSpringWithDamping:damping initialSpringVelocity:1.0 / damping options:0 animations:^{ // blablabla animation stuff } completion:^(BOOL finished) { [transitionContext completeTransition:YES];// this line makes my UITableView removed form the view hierarchy }]; Here is what i've tried so far : add in the completion bloc the UITableView [[UIApplication sharedApplication ].keyWindow insertSubview:fromViewController.view belowSubview:containerView]; But this only works on iOS8 ... Any ideas how to fix this ? thank you !! A: Try to set modalPresentationStyle of the presenting view controller to UIModalPresentationCustom
{ "language": "en", "url": "https://stackoverflow.com/questions/32170995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql next key lock with ROLLBACK TO SAVEPOINT I faced multiple locking issues with ROLLBACK TO SAVEPOINT command and i think there's a next key lock happen here by mistake mysql version: 8.0.31 my transaction type: REPEATABLE READ Suppose i have this table with some dats: CREATE TABLE book ( id int NOT NULL, name varchar(64) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB; INSERT INTO book (id, name) VALUES (700, 'test_book_700'); INSERT INTO book (id, name) VALUES (750, 'test_book_750'); INSERT INTO book (id, name) VALUES (800, 'test_book_800'); and then i have two connections to mysql server: Connection #1: START TRANSACTION; SELECT * FROM book WHERE name = 'test_book_700'; SAVEPOINT sa_savepoint_1; INSERT INTO book (id, name) VALUES (900, 'test_book_900'); ROLLBACK TO SAVEPOINT sa_savepoint_1; => x_lock will happen for the id > 800 (i don't now why ) (still without final commit or rollback to the main transaction) Connection #2: START TRANSACTION; INSERT INTO book (id, name) VALUES (950, 'test_book_950'); => will wait to the x lock release or it will return lock wait timeout if i use RELEASE SAVEPOINT instead ROLLBACK TO SAVEPOINT the x lock will not happen, very weird behavior, no ? is there a wrong behavior when use ROLLBACK TO SAVEPOINT ?? why the next key lock happen in this case ? and this the TRANSACTION output from the SHOW ENGINE INNODB STATUS that have relevant to this issue INSERT INTO book (id, name) VALUES (950, 'test_book_950') ------- TRX HAS BEEN WAITING 17 SEC FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 383 page no 4 n bits 72 index PRIMARY of table `test`.`book` trx id 286322 lock_mode X insert intention waiting Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0 0: len 8; hex 73757072656d756d; asc supremum;;
{ "language": "en", "url": "https://stackoverflow.com/questions/75348662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extract parameters and result contents from website I have a website where I can input a list of strings and it'll display the results of each in the same format (basically a table). What I want to do is to be able to save the results as well as their corresponding parameters (the input string that I searched) and output them into a file to analyze later. So basically capture my input and the output it returns. It's kind of like, if I search "stack" on google, I want my output file to be "stack" and all the displayed results from the search. I've done some research on web and screen scraping, but I can't find anything that fits my needs. I looked into the curl function in php, but it looks like it can only get the contents of a specific URL, which I don't have since I'll be repeating the searches frequently. I also looked into the HTML Agility Pack and HttpWatch, but they don't seem to be able to extract contents this dynamically. I was wondering if there are any ideas or tips that I could use. I was thinking maybe a plugin or application that I could write that captures the parameters of my request (input strings) and the results sent from the server, but I'm not really sure how to do this, any tips? Or maybe there's an existing one that I wasn't able to find? Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/25540483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use NSURLConnection (NSMutableRequest) timeout I want to timeout the connection or make the connection invalidate or display an alert saying "connection time out", if the response is not received (or connection delegate methods not called) after 5 secs or 10 secs (a certain time period). Does anybody has a solution for this? A: make sure your NSURLConnection's delegate is set and responds to the connection:didFailWithError: method. A connection always calls either this method or connectionDidFinishLoading: upon connection completion. your timeout is received in connection:didFailWithError: so here you can display that connection has timed out
{ "language": "en", "url": "https://stackoverflow.com/questions/8147300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails Model seems valid but doesn't validate My model looks like this, nothing fancy: # Table name: invoices # # id :integer not null, primary key # total :float # discount :float # description :text # created_at :datetime not null # updated_at :datetime not null # company_id :integer # secret :string(255) # address_id :integer # price_per_credit :float # paid :boolean I can create instances of this both on the server and in the rails console, and these instances return true if I call .valid? on them (I turned off all validation for testing purposes). 1.9.3p194 :001 > i = Invoice.new => #<Invoice id: nil, total: nil, discount: nil, description: nil, created_at: nil, updated_at: nil, company_id: nil, secret: nil, address_id: nil, price_per_credit: nil, paid: nil> 1.9.3p194 :002 > i.valid? => true However, for some reason, I can't save these instances to the database. 1.9.3p194 :003 > i.save (0.3ms) begin transaction (0.1ms) rollback transaction => false Locally I'm using sqlite, the production server is running MySQL, but both show this behavior. I'm not really sure what to do to debug this. I did run db:migrate, and my gems are up-to-date. How can I sove this? A: It turned out I had a before_create filter that returned false, causing the save proces to halt. To solve this, I added nil to the class, like this: # BEFORE: def set_paid self.paid = false end # AFTER: def set_paid self.paid = false nil end Hope this helps others too!
{ "language": "en", "url": "https://stackoverflow.com/questions/11290822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Graphs of the mixed effects model residuals using the ggplot2 function I am trying to graph the residual effects of the mixed effects model using the ggplot2 function. However, after performing a search I found some functions available but what seems to me is that for the function nlme they are not working. The graphs that I intend to make are those of the example below: The computational routines that I tried initially are below, see the errors that are appearing when executing the function in ggplot2. library(splines) library(ggplot2) library(nlme) library(gridExtra) datanew1$DummyVariable = as.factor(datanew1$DummyVariable) datanew1$Variable2 = as.factor(datanew1$Variable2) datanew1$Variable3 = as.factor(datanew1$Variable3) ############################################################################# ############################## Model ######################################## ############################################################################# model <- lme(Response~(bs(Variable1, df=3)) + DummyVariable, random=~1|Variable2/Variable3, datanew1, method="REML") completemodel <- update(model, weights = varIdent(form=~1|DummyVariable)) p1 <- qplot(.fitted, .resid, data = completemodel) + geom_hline(yintercept = 0) + geom_smooth(se = FALSE) Erro: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class lme Run `rlang::last_error()` to see where the error occurred. p2 <- qplot(sample =.stdresid, data = completemodel, stat = "qq") + geom_abline() grid.arrange(p1,p2) Erro: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class lme Run `rlang::last_error()` to see where the error occurred. Além disso: Warning message: `stat` is deprecated Another way in which I tried to make the graph was with the function below, but I was not successful. ggplot(completemodel, aes(.fitted, .resid)) + geom_point() Erro: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class lme Run `rlang::last_error()` to see where the error occurred. A: [SOLUTION] library(splines) library(ggplot2) library(nlme) library(gridExtra) datanew1$DummyVariable = as.factor(datanew1$DummyVariable) datanew1$Variable2 = as.factor(datanew1$Variable2) datanew1$Variable3 = as.factor(datanew1$Variable3) model <- lme(Response~(bs(Variable1, df=3)) + DummyVariable, random=~1|Variable2/Variable3, datanew1, method="REML") completemodel <- update(model, weights = varIdent(form=~1|DummyVariable)) df_model <- broom.mixed::augment(completemodel) #> Registered S3 method overwritten by 'broom.mixed': #> method from #> tidy.gamlss broom df_model[".stdresid"] <- resid(completemodel, type = "pearson") p1 <- ggplot(df_model, aes(.fitted, .resid)) + geom_point() + geom_hline(yintercept = 0) + geom_smooth(se=FALSE) p2 <- ggplot(df_model, aes(sample = .stdresid)) + geom_qq() + geom_qq_line() grid.arrange(p1,p2) #> `geom_smooth()` using method = 'gam' and formula 'y ~ s(x, bs = "cs")'
{ "language": "en", "url": "https://stackoverflow.com/questions/65891643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iCarousel is been shown up in previous page when clicked the back button When i press the back button. the iCarousel is still shows up for 1 second.why is this happening and how to stop this.I have used storyboard to create a iCarosel view.. - (void)viewDidUnload { [super viewDidUnload]; self.carousel = nil; } - (void)dealloc { carousel.delegate = nil; carousel.dataSource = nil; } - (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel { return [idOfAllWords count]; } - (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view { UILabel *label = nil; //create new view if no view is available for recycling if (view == nil) { view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 250.0f, 250.0f)]; ((UIImageView *)view).image = [UIImage imageNamed:@"page.png"]; view.contentMode = UIViewContentModeCenter; label = [[UILabel alloc] initWithFrame:view.bounds]; label.backgroundColor = [UIColor clearColor]; label.textAlignment = NSTextAlignmentCenter; label.font = [label.font fontWithSize:50]; label.tag = 1; [view addSubview:label]; } else { label = (UILabel *)[view viewWithTag:1]; } Words *word=nil; word=idOfAllWords[index]; label.text =word.Name; return view; } A: Hiding and unhiding is not the solution. What you need is just one line: yourCarousel.clipsToBounds = YES; A: I actually tried to reproduce your problem and did see that the carousel view stays for a second when 'pop' or back button press happens. This particularly happens when you the carousel is swiped and then the back button pressed. As a workaround, I was able to fix it by setting the iCarousel hidden in the viewWillDisappear method. - (void)viewWillDisappear:(BOOL)animated { [YOUR_CAROUSEL_NAME setHidden:YES]; //This sets the carousel to be hidden when you press Back button } If this looks to be hidden suddenly, you can perhaps try setting the alpha to 0.0 inside an animation block. Something like this: - (void)viewWillDisappear:(BOOL)animated { //[YOUR_CAROUSEL_NAME setHidden:YES]; [UIView animateWithDuration:0.2f animations:^{ [YOUR_CAROUSEL_NAME setAlpha:0.0f]; //This makes the carousel hide smoothly }]; } Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/22279297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to remove a childnode when there is a parent node with ID in Powershell I have an xml file , I want to remove the existing child node from the xml where there are parent nodes with specific ID Using Powershell < Portal PortalID="IPE"> <DBConnection> </DBConnection> <Spicer> <Filetype SpicerViewer="true">.jpg</Filetype> <Filetype SpicerViewer="true">.gif</Filetype> <Banner> <Top> <Left>fdgsf_FileName</Left> <Center>gsdfg_Revision</Center> <Right>Date</Right> </Top> <Bottom> <Left>dfgsdf_FileName</Left> <Center>fgsfd_Revision</Center> <Right>Date</Right> </Bottom> </Banner> </Spicer> </Portal> I have to remove the Banner node completely based on the Portal ID , as I have multiple Portal Id's in my config file A: You may be able to use : [xml]$x=get-content c:\temp\data.xml ($x.portals.portal | ?{ $_.portalID -eq "IPE"}).spicer.banner.removeAll() $x.save("c:\temp\newdata.xml")
{ "language": "en", "url": "https://stackoverflow.com/questions/25132579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ReactJS - Can't get function to load values from separate file after refactoring After attempting to factor out functions within my App class in React into separate files, I am dealing with a whirlwind of import/export issues and was wondering if I could get some advice: First, is factoring out functions from classes within other files/classes a logical thing to do? Second, this is a specific problem that I'm having: Expected Behavior: The function MainTable.tableGen() should return a value which App's render() can process. Actual Behavior: Stepping through the debugger shows that tableGen() is not being fired, but it is recognized. In other words, it is not running the function and returning the value but returning the function as it's printed. Main.js: import MainTable from './app/components/input_table/maintable'; export default class App extends React.Component { constructor(props){ this.MainTable = this.MainTable.bind(this); } MainTable(){ MainTable.tableGen(); //Call the function that's in the external file here } render(){ return ( <div> <table> <tbody onLoad = {this.broadcast()}> {this.MainTable} //The MainTable.tableGen() function populates the table using a series of loops </tbody> </table> <ButtonMenu onRow = {this.onRowButton} onCol = {this.onColumnButton} undo ={this.onUndoAction} redo = {this.onRedoAction} reset = {this.onResetAction} /> </div> ); } } maintable.js: class baseTable extends React.Component{ constructor(props){ //properties super(props); } tableGen(){ ... function code here... } const MainTable = new baseTable; export default MainTable; A: Make sure your tableGen() returns JSX, without quote. return <h3>Hello World</h3>; Then, your MainTable function should have return keyword: MainTable() { return MainTable.tableGen(); } And, invoke the function when referencing it in JSX: {this.MainTable()}
{ "language": "en", "url": "https://stackoverflow.com/questions/51181620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Parse.com get all columns for a pointer i'm using Parse.com with the library for PHP and i wanna get all columns for a pointer to Product in my class RepProdMae, my code is below, but i don't know how obtine all columns, thanks for your help. $pqry = new parseQuery('RepProdMae') ; $pqry->whereInclude("Product") ; $pqry->wherePointer('productId','Product', 'lqf4mmpOgS') ; $pres = $pqry->find() ; print_r($pres) ; this print_r return: stdClass Object ( [results] => Array ( [0] => stdClass Object ( [userId] => stdClass Object ( [__type] => Pointer [className] => _User [objectId] => 3YjQkMwrvf ) [productId] => stdClass Object ( [__type] => Pointer [className] => Product [objectId] => lqf4mmpOgS ) [comments] => nothing [createdAt] => 2014-07-16T01:44:41.549Z [updatedAt] => 2014-07-16T01:44:41.549Z [objectId] => 6VzG9K1BTS ) ) ) And my product class have more colums, my query array is : Array ( [where] => {"productId":{"__type":"Pointer","className":"Product","objectId":"lqf4mmpOgS"}} [include] => Product [limit] => 100 ) A: Your parameter for the Include method should be the column name which is a pointer, not the class name which is pointed to. Try changing this line: $pqry->whereInclude("productId") ;
{ "language": "en", "url": "https://stackoverflow.com/questions/24790052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AngularJS tabs, performance (Nodes & Heaps) I'm developing my first AngularJS App. The App has various features but introducing one in particular I started having performance problems (Nodes and Heap). The section involved is composed of one or more tabs (max six). Each tab contains within it a table, the detail of an element of the table and an additional external filter. The plugin used for table is ng-table. The number of columns in the table can be up to 20. The columns must be sortable, filterable, displayed or hidden and has to be possible to move to rearrange the display order. To do this I had to do a custom header (attached). Find below a screenshot of the performance at the opening of six tabs simultaneously.  Is possible that the problem was made by the old version of ng_table plugin ? Because after upgrade it the performance is improving! What can I do to improve? Please, help me.
{ "language": "en", "url": "https://stackoverflow.com/questions/35623272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: My background on my HTML Email won't show in Outlooks I have a HTML Email which uses tables to position everything - The background shows in a brouser when attributed to the table background tag but doesn't work in outlook - Is there anything anyone can suggest to do? I have tried putting it in CSS, etc but to no avail, Much appreciated. A: You shouldn't be using background image properties in HTML Emails, especially Outlook. Most email clients don't support this attrubute - some web clients will, but its best practise to stick to inline images. A: Outlook needs a chunk of Microsoft's VML code to render backgrounds in Outlook 2007 - 2013 since they use MS Word to render the HTML. Try this: <table border="0" cellpadding="0" cellspacing="0" width="640" style="border-collapse:collapse; padding:0; margin:0px;"> <tr valign="top"> <td background="http://place-hoff.com/640/487" bgcolor="#000000" width="640" height="487" valign="top"> <!--[if gte mso 9]> <v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:640px;height:487px;"> <v:fill type="tile" src="http://place-hoff.com/640/487" color="#000000" /> <v:textbox inset="0,0,0,0"> <![endif]--> <div> <table border="0" cellpadding="0" cellspacing="0" width="640" style="border-collapse:collapse; padding:0; margin:0px;"> </table> </div> <!--[if gte mso 9]> </v:textbox> </v:rect> <![endif]--> </td> </tr> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/27927171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy a file using .mshs script I am trying to copy a file, export.txt from one directory to another within a .mshs script. I currently have: shell copy 'E:\RPTG\Export.txt' 'E:\FCST\'; I'm getting an error that says "end of file breaks the statement." Is there a command to copy a file with .mshs? Thanks! A: Typically you would perform the copy from a batch file itself. For example, your batch file would do the copy, run a MaxL script, and then do other things. That said, you can run shell commands from within MaxL if you need to (I don't usually recommend it though). In this case, you need to pass the whole statement to the shell command. Your statement should work if you write it like this instead: shell "copy 'E:\RPTG\Export.txt' 'E:\FCST\'"; Note that I have enclosed your command in double quotes. There are some nuances to using double quotes and single quotes at the same time, but in this case you should be okay.
{ "language": "en", "url": "https://stackoverflow.com/questions/36090854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why my OpenCV CUDA is running slower than CPU for simple thresholding? My CPU is Intel Core2 Duo T5550, GPU is GeForce 8400M G. CUDA version 5.5.22, OpenCV version 2.4.8. The test code is as follows: double t = (double)getTickCount(); gpu::threshold(src, dst, thres, binMax, THRESH_BINARY); t = ((double)getTickCount() - t)/getTickFrequency(); cout << "Times passed in seconds: " << t << endl; For a 3648*2736 image, the result is CPU: Times passed in seconds: 0.0136336 GPU: Times passed in seconds: 0.0217714 Thanks! A: Perhaps this is not suprising. You GeForce 8400M G is a old mobile card having only 8 cores, see the GeForce 8M series specifications, so you cannot extract much parallelism out of it. Brutally speaking, GPUs are advantageous over multicore CPUs when you are capable of massively extracting parallelism by a large number of cores. In other words, to fastly build up an Egyptian pyramid by slow slaves (GPU cores) you need a large number of slaves. If you have only very few slow slaves (8 in your case), then perhaps it is better to have even fewer (2 CPU cores, for example), but much faster, slaves. EDIT I remembered just now to have bumped into this post Finding minimum in GPU slower than CPU which may help convince you that bad implementations (as underlined by Abid Rahman and Mailerdaimon) may lead to GPU codes that are slower than CPU ones. The situation is even worse if, as pointed out in the answer to the post above, you are hosting also the X display on your already limited GeForce 8400M G card. A: Additionally to what @JackOLantern said: Every Copy operation involving the GPU takes Time! A lot of time compared to just computing with the CPU. This is why @Abid Rahman K comment is a good Idea, he suggested to test again with more complex Code. The advantage of the GPU is in fast parallel processing, on off it disadvantages is the relatively slow transfer rate while copying data to and from the GPU.
{ "language": "en", "url": "https://stackoverflow.com/questions/20985337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cast char to string in C? Im new to C and i encounter a problem with using strcat(). I looked up strcat and noticed that it takes string as arguments but when i split items from a char array is a char and when i use it as a argument for strcat it prints out error. #include <stdio.h> #include <string.h> int main() { char a[10]="abcdefg123"; char *pa=a; char *out[2]={"",""}; int counter=0; while(*pa != '\0'){ if (counter%2==0){ strcat(out[0],*pa); } else{ strcat(out[1],*pa); } counter++; pa++; } printf("%s,%s\n",out[0],out[1]); return 0; } the purpose of the code is to split a string into two string that each contain all the characters in odd position or even position.However, when im tring to dereference the char pointer all i get is a Char but it seems i need string A: Use a temporary string in strcat instead of strcat(out[0],*pa);. Also, make sure that you allocate enough memory for out. int main() { char a[10]="abcdefg123"; char temp[2] = {0}; char *pa=a; // This is not good for `strcat`. // char *out[2]={"",""}; // Use this instead. char out[2][20]={"",""}; int counter=0; while(*pa != '\0'){ temp[0] = *pa; if (counter%2==0){ strcat(out[0], temp); } else{ strcat(out[1], temp); } counter++; pa++; } printf("%s,%s\n",out[0],out[1]); return 0; } A: Point 1. As per the man page of strcat() . .. the dest string must have enough space for the result. Point 2. The second argument for strcat() is const char *, so the call cannot be strcat(out[0],*pa);. You need to use a temporary array for that, which will hold only the value *pa. Otherwise, you can make use of strncat() like strncat(out[0], pa, 1); // copy only 1 char In later case, you don't need to have any temporary array. Reference: From man page, again, The strncat() function is similar, except that it will use at most n bytes from src and src does not need to be null-terminated if it contains n or more bytes. A: strcat() requires a pointer to a null-terminated string. You are dereferencing a pointer (with the * operator) which gives a char. You cannot simply cast a char to a pointer to sting. You might want to be using memcpy() instead of strcat(), but for copying single bytes a simple assignment using * operators on both the left and right sides would be fine. But as others have pointed out your code isn't allocating space for you to copy the chars into, so you're going to need to make additional changes to fix that. Also, you'll have to remember to copy a final null byte to the end of both your output strings. A: In C, a "string" is really just a pointer to a character; the string runs from that character to the terminating 0 byte (the NUL). If you dereference a string pointer, you get the character at that position. If the pointer is pointing to the start of the string, you get the first character of the string. Your program has some problems. For one, you need to allocate space for the new strings. strcat() will try to copy characters wherever you tell it to, but it's your job to make sure that there is room there and that it's okay to write there. The declaration of out just declares two pointers, and initializes them to point to a zero-length constant string. Instead, you need to allocate storage, something like: char out0[64], out1[64]; char *out[]={out0, out1}; This makes two output buffers of 64 characters each, then sets up out with pointers to them. Another problem: you declared a length of 10 for your char array, but then you initialize it with a length-10 string. This means there is no room for a terminating NUL byte and C won't put one. Then strcpy() or strcat() will copy extra garbage from the string, until there happens to be a NUL byte. If you are lucky there will be one right away and you won't spot the error, but if you aren't lucky you will get weird garbage. Just let the compiler count how many bytes in your string and do the right thing. Leave out the length: char a[]="abcdefg123";
{ "language": "en", "url": "https://stackoverflow.com/questions/28373690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I print a binary tree “as a” tree? I made a program that inserts values, sorts them using binary search, and outputs the sorted values. However, I also would like to use the function PrintTree() to print the tree. I can't think of any way to implement a functioning code in that function. Here is my code up until now. #ifndef b_h #define b_h #include <iostream> class BSTNode { public: int Key; BSTNode * Left; BSTNode * Right; BSTNode * Parent; int Height; }; class BST { private: BSTNode * root; BSTNode * insertKey(BSTNode * node, int newKey); void PrintTreeInOrder(BSTNode * node); BSTNode * hasKey(BSTNode * node, int searchKey); public: BST(); ~BST(); void insertKey(int newKey); void PrintTreeInOrder(); bool hasKey(int searchKey); void TreePrint(); }; #endif The header file above. #include "b.h" BST::BST() : root(NULL) { } BSTNode * BST::insertKey(BSTNode * node, int newKey) { if(node == NULL) { node = new BSTNode; node->Key = newKey; node->Left = NULL; node->Right = NULL; node->Parent = NULL; } else if(node->Key < newKey) { node->Right = insertKey(node->Right, newKey); node->Right->Parent = node; } else { node->Left = insertKey(node->Left, newKey); node->Left->Parent = node; } return node; } void BST::insertKey(int newKey) { root = insertKey(root, newKey); } void BST::PrintTreeInOrder(BSTNode * node) { if(node == NULL) return; PrintTreeInOrder(node->Left); std::cout << node->Key << " "; PrintTreeInOrder(node->Right); } void BST::PrintTreeInOrder() { PrintTreeInOrder(root); std::cout << std::endl; } BSTNode * BST::hasKey(BSTNode * node, int key) { if (node == NULL) return NULL; else if(node->Key == key) return node; else if(node->Key < key) return hasKey(node->Right, key); else return hasKey(node->Left, key); } bool BST::hasKey(int searchKey) { BSTNode * result = hasKey(root, searchKey); return result == NULL ? false : true; } The cpp file above. #include <cstddef> #include <iostream> #include <vector> #include <limits> #include "b.h" using namespace std; int main() { cout << "Binary Search Tree" << endl; BST * tree = new BST; cout << "Enter the numbers to be stored (end with a letter): "; int value; int i = 0; vector <int> keys; cin >> value; while (!cin.fail()){ keys.push_back(value); cin >> value; i++; } cin.clear(); // reset failbit cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); for(const int& key : keys){ tree->insertKey(key);} int number; cout << "Which number do you want to look up? " <<endl; cin >> number; bool b = tree->hasKey(number); if(b){ cout << number << " is in the tree: yes";} else{ cout << number << " is in the tree: no"; cout << endl;} cout << "The numbers in sorted order: "; tree->PrintTreeInOrder(); tree->TreePrint(); return 0; } And the main. This program works and it sorts the vector using binary search and has a search-for-key function, however, I want to print the tree in the function PrintTree(); as follows for example; 8 3 10 1 6 14 4 7 13 Can anyone help?
{ "language": "en", "url": "https://stackoverflow.com/questions/64310533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why am i getting error 415 when trying to retrieve database information wiht angular? I am learning Angular right now, and i am trying to make a POST into a API in asp.net core. I went to the startup and made the cors since they were giving me problems. Now, my problem is an error 415, i don´t know why is saying the payload is not supported it's making 0 sense to me. My API function is this: [HttpPost] public IActionResult register([FromBody] RegisterModel registro) { Cristais cristal = new Cristais { ID = "4", Cristal = "Zombie44" }; _context.Cristais.Add(cristal); _context.SaveChanges(); Utilizadores utilizador = new Utilizadores(); utilizador.ID = Guid.NewGuid().ToString(); utilizador.Comida = 100; utilizador.Gold = 1000; utilizador.ID_Cristal = "4"; utilizador.Email = registro.email; utilizador.NickName = registro.nickName; utilizador.Password = registro.password; _context.Utilizadores.Add(utilizador); _context.SaveChanges(); Console.WriteLine(_context.Utilizadores.Where(p=> p.ID_Cristal=="4")); return Ok(_context.Utilizadores.ToList()); } And then i tried my post in angular: registar() { console.log(this.utilizador); console.log(config.Urlsite); this.httpClient.post(config.Urlsite + "Utilizador/register",this.utilizador, {headers: new HttpHeaders({'Content-Type': 'json'})} ).subscribe((resultado)=>{ console.log(resultado); }, (casoErro)=>{ console.log(casoErro); }) } utilizador is a variable that contains information about a user in json form something like: { "nickName": "Ricardo", "password": "Zombie33", "email": "aasd@hotmail.com" } Also, registro in the API function is a model with 3 strings... If i try this in postman it all goes well.. I dont understand why i can´t do it in angular All help is appreciated, thanks! :) [EDIT] I just tried to place [EnableCors("StratGameWebSiteAngular")] on the API function, and than i got error 500.. i am lost right now A: my problem is an error 415, i don´t know why is saying the payload is not supported In your Angular client side code, we can find that you set {headers: new HttpHeaders({'Content-Type': 'json'})}, which cause the issue. You can set Content-Type with application/json, like below. this.httpClient .post( config.Urlsite + "Utilizador/register", this.utilizador, { headers: new HttpHeaders({ "Content-Type": "application/json" }) } ) .subscribe( resultado => { console.log(resultado); }, casoErro => { console.log(casoErro); } ); Test Result
{ "language": "en", "url": "https://stackoverflow.com/questions/64892791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Microsoft Lightswitch establishing a parent child relationship for a document library custom screens I have gotten code from the Internet to create an Editable Data Screen that holds documents, i.e. Word docs, in a document library. I'm able to upload, download and open the files. However, I need the documents to be linked to a parent record called "Resolution". I've created the database relationship of 1 resolution to many documents but can't figure out how to have the custom screen save the child without getting an error. I have a parent-child 1 to many relationship between parent table "Resolutions" and child table "FileInformations". I've created a custom button off the "Resolutions" detail screen to launch the " FileInformations" Editable Data Screen. I'm passing the "resolutions" ID key to the "FileInformations" Editable screen to attempt to create a bond between the parent and future child(ren) records. However, when I try to save an entry into my Editable Data Screen, it fails because it's looking for all the parent data from my "Resolutions" table. I need to know how to build a relationship between parent-child records and be able to save and ultimately retrieve the records associated with the parent. A: Without seeing code, this is gonna be a guess. I'm having a little trouble visualizing what you're describing. If I understand correctly, the first thing I would try is editing the FileInformationsScreen_Saving method (or whatever your screen is called). From the screen designer, click the little arrow next to Write Code, and select the _Saving method. There, you can manually save the fields you need, by using the DataWorkspace object. Private Sub MyScreen_Saving(ByRef handled As Boolean) Dim parent resolution = DataWorkspace.ApplicationData.Resolutions_SingleOrDefault(resolutionID) 'Process the record as needed End Sub Hopefully this is what you're looking for. Although if the relationship between the tables is set up correctly, you should have a field in the FileInformation entity for the ID key of the "parent" Resolution, which would make all of this unnecessary. You can verify that by looking at your tables in the designer, you should see lines connecting the related entities.
{ "language": "en", "url": "https://stackoverflow.com/questions/18707387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Render is not updated? When I want to delete a user, I would like to display a confirmation pop-up. So when I press the delete button, I would like my pop-up to appear. What I do is that I have a pop up that I render according to a poster variable. If it is true then I display if it is false I do not display. Logically when I press the delete button I'm supposed to display my pop up so I modify the variable and put it in true but my pop up is not displayed import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import AuthentificationService from "../../api/AuthentificationService" import IconButton from '@material-ui/core/IconButton'; import DeleteIcon from '@material-ui/icons/Delete'; import Modal from "../Modal/Modal" const useStyles = makeStyles(theme => ({ root: { width: '100%', maxWidth: 360, backgroundColor: theme.palette.background.paper, }, })); export default function CheckboxList(props) { const classes = useStyles(); let deleteIt = false; const [checked, setChecked] = React.useState([0]); const handleToggle = value => () => { const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } setChecked(newChecked); }; const deleteUser = value => () => { AuthentificationService.deleteUser(value.id) .then((data) => { console.log(data); }) .catch((error) => { }) } const confirmationDeleteUser = value => () => { deleteIt = true; } return ( <List className={classes.root}> {props.response.map( test => { if (props.response.length <= 1) { } else { return ( <ListItem key={test} role={undefined} dense button onClick={handleToggle(test)}> <ListItemText primary={`${test.email}`}/> <ListItemSecondaryAction> <IconButton edge="end" aria-label="delete" onClick={confirmationDeleteUser(test)}> <DeleteIcon /> <div> {deleteIt === false ? "" : <Modal title="Confirmation" message="hey"/>} </div> </IconButton> </ListItemSecondaryAction> </ListItem> ); } })} </List> ); } when my deleteIt variable is equal to true so I want to display my popup. Why doesn't it work? What am I not understanding? A: React will only re-render if a value that is a prop or part of the component's state changes. In your case, the deleteIt variable is not a state variable, so even if you change it with confirmationDeleteUser, your component won't re-render to trigger the popup. Try to define your variable with useState instead, like this: const [deleteIt, setDeleteIt] = useState(false); And change your code in confirmationDeleteUser to change deleteIt like this: setDeleteIt(true); That should get things heading in the right direction. A: Right now you are using a stateless component. so, you will never see a change in the front with this type of component. You should use the stateful component instead, and set the values to change in the state property, and change them using the setState() function. see State in react
{ "language": "en", "url": "https://stackoverflow.com/questions/57531155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Using fpurge(stdin); Here is the Part of the program that i am trying to compile using gcc compiler on ubuntu 14.04. #include<stdio.h> #include<string.h> main() { int i; char str[50], pat[3]; char sep; printf("Enter the sting to seperate\n "); scanf("%s", str); fpurge(stdin); printf("Enter the patern in Numbers to seperate Example : 1 2 3\n"); //__fpurge(stdin); scanf("%s", pat); fpurge(stdin); printf("Enter the seperator Example: ; or enter ,space"); scanf("%c", &sep); } this is the Error: /tmp/cc0bHLkO.o: In function `main': str_sepert.c:(.text+0x4d): undefined reference to `fpurge' str_sepert.c:(.text+0x95): undefined reference to `fpurge' collect2: error: ld returned 1 exit status A: fpurge is not in the standard C library. It is nonstandard and not portable. It is a BSD function. http://bytes.com/topic/c/answers/845246-fpurge
{ "language": "en", "url": "https://stackoverflow.com/questions/33066454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the correct place of Prepare() method? Before defining parameters (with their types and sizes) or after? I have found two different descriptions of when Prepare() method for prepared SQL statements should be used. In SqlCommand's documentation (https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.prepare?redirectedfrom=MSDN&view=netframework-4.7.2#System_Data_SqlClient_SqlCommand_Prepare) "Before you call Prepare, specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the Size property to the maximum size needed. Prepare returns an error if these conditions are not met." In MySqlCommand's documentation (https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html): "After entering your statement, call the Prepare method of the MySqlCommand object. After the statement is prepared, add parameters for each of the dynamic elements in the query." Are those two documentations excluding each other? Where exactly should Prepare() be used? It seems to be more logical to use Prepare() after defining parameters' data and type. var conn = new MySql.Data.MySqlClient.MySqlConnection(); var cmd = new MySql.Data.MySqlClient.MySqlCommand(); conn.ConnectionString = strConnection; conn.Open(); cmd.Connection = conn; cmd.CommandText = "INSERT INTO myTable VALUES(NULL, @number, @text)"; cmd.Prepare(); // should it be here? cmd.Parameters.AddWithValue("@number", 1); cmd.Parameters.AddWithValue("@text", "One"); cmd.Prepare(); // or here? for (int i=1; i <= 1000; i++) { cmd.Parameters["@number"].Value = i; cmd.Parameters["@text"].Value = "A string value"; cmd.ExecuteNonQuery(); } Or maybe I should not compare those two documentations and for MySqlCommand use as it according to MySql's dosc and for SqlCommand use it according to Microsoft's docs?
{ "language": "en", "url": "https://stackoverflow.com/questions/54745529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: cordova build ios does not create ipa file I am building cordova project for iOS, build log seems fine however I can't find any ipa file generated: $ npm run cordova platform add ios $ cat Build.json { "ios": { "debug": { "codeSignIdentity": "iPhone Developer", "developmentTeam": "**************", "packageType": "development", "automaticProvisioning": true, "buildFlag": [ "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES", "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO" ] }, "release": { "codeSignIdentity": "iPhone Developer", "developmentTeam": "****************", "packageType": "app-store", "automaticProvisioning": true, "buildFlag": [ "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES", "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO" ] } } } $ npm run cordova build ios --release --device Build log looks fine. However there is no ips files: $ find . type f -name "*.ipa" | wc -l 0 Xcode version is 9.4 cordova-ios@4.5.5 A: The build command should be run as npm run cordova -- build ios --release --device , double dashes are essential or else npm run does not pass build ios --release --device as arguments to cordova scripts. Uph, it's taken awhile for me to find it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/51564372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there an algorithm for encoding two text and the result will be the same even if change their position? May be the question is hard to understand, I mean this Given two sample text Text1 = "abc" and Text2 = "def" Which algorithm can do like encoding(Text1, Text2) == encoding(Text2, Text1) And I wish the result of the function is unique(not duplicate with encoding(Text3, Text1) like in another checksum algorithm too. Actually, the root of this is I want to search in my database for the question is there any rows that "Who is a friends of B" or "B is a friends of whom" by searching only one column like SELECT * FROM relationship WHERE hash = "a039813" not SELECT * FROM relationship WHERE (personColumn1 = "B" and verb = "friend") OR (personColumn2 = "B" and verb = "friend") A: You can adapt any encoding to ensure encoding(Text1, Text2) == encoding(Text2, Text1) by simply enforcing a particular ordering of the arguments. Since you're dealing with text, maybe use a basic lexical order: encoding_adapter(t1, t2) { if (t1 < t2) return encoding(t1, t2) else return encoding(t2, t1) } If you use a simple single-input hash function you're probably tempted to write: encoding(t1, t2) { return hash(t1 + t2) } But this can cause collisions: encoding("AA", "B") == encoding("A", "AB"). There are a couple easy solutions: * *if you have a character or string that never appears in your input strings then use it as a delimiter: return hash(t1 + delimiter + t2) * *hash the hashes: return hash(hash(t1) + hash(t2))
{ "language": "en", "url": "https://stackoverflow.com/questions/19332678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: spark rewrite projection of parquet data without exchange/shuffle I had the task of writing about a TB of data (split in 200+ partitions by day) in compressed parquet files again with changed schema. Basically I used spark sql to adjust the schema to my new format. Some columns were casted, others recomputed or split. I wanted to then save the result with in as few files per day as possible repartition($year,$month,$day).write.partitionBy(year,month,day).parquet(..) The source of the data was a partitioned table by the same y,m,d columns. So in theory it should have worked without any exchange steps, simple taking one day writing it into its new location with changed data/schema. I thought the whole job should be network bound read/write to/from s3. That did not work though. The spark EMR cluster first tried to read all the data, shuffle the data and then write it back out. That was an issue because I did not to set up a massive cluster. Eventually data didn't fit in RAM and then if the disk space filled up with shuffle temp files form the exchange step. I ended up just splitting the work in terrible slow inefficient serial steps. Which took forever. TL;DR; How does one handle such primitive (projection) ETL jobs in spark? It is basically just a projection, no joins, only coalesce of partitions. Read data -> project columns -> write data (partitioned) I want to avoid the exchange step in the DAG, or is this just not possible with spark.
{ "language": "en", "url": "https://stackoverflow.com/questions/51285687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conversion from pairwise matrix to Cytoscape edge table is too slow My code is similar to this. Given a matrix like this: a b c d a 1 NA 3 4 b NA 2 NA 4 c NA NA NA NA d NA NA NA 4 It converts it to this: a a 1 a c 3 a d 4 b b 2 b d 4 d d 4 The relevant code is as below: 2 pears <- read.delim("pears.txt", header = TRUE, sep = "\t", dec = ".") 3 edges <- NULL 4 for (i in 1:nrow(pears)) { 5 for (j in 1:ncol(pears)) { 6 if (!(is.na(pears[i,j]))) { 7 edges <- rbind(edges, c(rownames(pears)[i], colnames(pears)[j], pears[i,j])) 8 } 9 } 10 print(i) 11 } 12 colnames(edges) <- c("gene1", "gene2", "PCC") 13 write.table(edges, "edges.txt", row.names = FALSE, quote = FALSE, sep = "\t") When I run the code from a remote server in the background using screen -S on a 17804x17804 sparse (99% NA) matrix, it initially runs 5 print statements every 13 seconds. However, it has now slowed down to 7 print statements every minute. Why is the algorithm getting slower and slower as it progresses? Is there another way I can convert my matrix into a Cytoscape's format quicker? A: We convert the data.frame to matrix, use melt from reshape2 to get the dimnames as two columns along with the values as third column, then subset while using na.rm to remove the NA rows library(reshape2) melt(as.matrix(df1), na.rm = TRUE) data df1 <- structure(list(a = c(1L, NA, NA, NA), b = c(NA, 2L, NA, NA), c = c(3L, NA, NA, NA), d = c(4L, 4L, NA, 4L)), class = "data.frame", row.names = c("a", "b", "c", "d"))
{ "language": "en", "url": "https://stackoverflow.com/questions/55057150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you Bubble Sort Largest to Smallest Sorry am kind of lame at this. I've looked on here for a way to Bubble sort so that I can get an array to go from largest number to smallest. I've found some error in my current iteration of the sort, I can't seem to get the array to sort once it compares a smaller number to a bigger number. Here what I am using thus far. //bubble sort for(int i=0;i<size;i++) { for(int v=1;i<(size-i);i++) { if(arrInt[v-1]<arrInt[v]) { temp = arrInt[v-1]; arrInt[v-1]=arrInt[v]; arrInt[v]=temp; } } } A: int n = arrInt.length; int temp = 0; for (int i = 0; i < n; i++) { for (int v = 1; v < (n - i); v++) { if (arrInt[v - 1] < arrInt[v]) { temp = arrInt[v - 1]; arrInt[v - 1] = arrInt[v]; arrInt[v] = temp; } } } Try this. Update - Replaced j with v A: The problem is the inner loop should be from 1 to n. Instead your inner loop stops early. Also you are testing i in the inner loop condition, but you should be testing v. Try this: //bubble sort for(int i=0;i<size;i++) { for(int v=1;v<size;v++) { if(arrInt[v-1]<arrInt[v]) { temp = arrInt[v-1]; arrInt[v-1]=arrInt[v]; arrInt[v]=temp; } } } A: Bubble Sort Method for Descending Order public static void BubbleSort( int[ ] arr){ int records=arr.length-1; boolean notSorted= true; // first pass while (notSorted) { notSorted= false; //set flag to false awaiting a possible swap for( int count=0; count < records; count++ ) { if ( arr[count] < arr[count+1] ) { // change to > for ascending sort arr[count]=arr[count]+arr[count+1]; arr[count+1]=arr[count]-arr[count+1]; arr[count]=arr[count]-arr[count+1]; notSorted= true; //Need to further check } } } } In this method when array is sorted then it does not check further. A: Usually I implement Bubble sort like this, for(int i=0;i<size-1;i++) { for(int v=0;v<(size-1-i);v++){ if(arrInt[v]<arrInt[v+1]) { temp = arrInt[v]; arrInt[v]=arrInt[v+1]; arrInt[v+1]=temp; } } } You know what is the problem is, in your code??? Look at the inner loop, you are initializing v but checking and changing i. Must be a copy paste error.. :P Hope it helped... A: Here you go: int x = 0; for(int i = 0; i < array.length; i++) for(int j = 0; j < array.length; j++) if(array[i] > array[j + 1]) x = array[j + 1]; array[j + 1]= array[i]; array[i] = x; x here is a temporary variable you only need for this operation. A: here's a complete running program for you. Hope that keeps you motivated package test; public class BubbleSort { private static int[] arr = new int[] { 1, 45, 65, 89, -98, 2, 75 }; public static void sortBubbleWay() { int size = arr.length-1; int temp = 0; // helps while swapping for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - i; j++) { if (arr[j] < arr[j+1]) { /* For decreasing order use < */ temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } private static void showShortedArray() { for (int elt : arr) { System.out.println(elt); } } public static void main(String args[]) { sortBubbleWay(); showShortedArray(); } }//end of class
{ "language": "en", "url": "https://stackoverflow.com/questions/22853775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are postgres UUID numbers homogeneously random? Looking at UUIDs generated as primary keys by Postgres defined by RFC 4122, ISO/IEC 9834-8:2005 (source http://www.postgresql.org/docs/9.1/static/datatype-uuid.html). Can we consider that these numbers are homogeneously random on all their length ? Given this UUID : a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11 Can we objectively assume that a0eebc99 and bd380a11 are equally as random ? If not, why ? A: UUIDs in general are meant and optimized to be unique. They do not offer a guaranteed randomness. You should not use UUIDs as secrets and/or random number generator. There are several versions how UUIDs are generated, most of them are not random, but rather predictable. See the Wikipedia article on UUIDs and the various versions. If you want to avoid collisions for IDs, use UUIDs, if you want secrets, use strong cryptographic (P)RNGs. Also note, that the variant is encoded in the UUID itself, so at least this part of the UUID is not random at all. EDIT: There is an interesting article by Raymond Chen in his famous blog "Old New Thing" about almost exactly this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/37416499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List All MS Hotfixes / KBs C# Is there a quick way to to list all hotfixes / KBs? I see this but not sure where to find the dll to use it. Is there another way to get this information? var updateSession = new UpdateSession(); var updateSearcher = updateSession.CreateUpdateSearcher(); var count = updateSearcher.GetTotalHistoryCount(); var history = updateSearcher.QueryHistory(0, count); for (int i = 0; i < count; ++i) Console.WriteLine(history[i].Title); A: If you do not have an interop library, you can use dynamic to access it by ProgID: dynamic updateSearcher = Activator.CreateInstance(Type.GetTypeFromProgID("Microsoft.Update.Searcher")); var count = updateSearcher.GetTotalHistoryCount(); var history = updateSearcher.QueryHistory(0, count); for (int i = 0; i < count; ++i) Console.WriteLine(history[i].Title); The interface is listed as being present in WUAPI.idl on the MSDN page, so another option would be to compile it with midl and reference the generated tlb (Add Reference > COM). @HansPassant points out that the tlb is preregistered as "WUAPI 2.0 Type Library", which eliminates the need to manually compile the idl.
{ "language": "en", "url": "https://stackoverflow.com/questions/36068101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PythonShell messages received only at the end of the python script execution in Electron I'm trying to create an Electron app that executes a Python script but I cannot retrieve messages from python before the end of the script. This is the code at the beginning of the file main.js: const { PythonShell } = require('python-shell'); let pyshell = new PythonShell('app.py'); console.log("MAIN: Script started") pyshell.on('message', function (message) { console.log("Message from APP: " + message); }); // end the input stream and allow the process to exit pyshell.end(function (err, code, signal) { if (err) throw err; console.log('The exit code was: ' + code); console.log('The exit signal was: ' + signal); console.log('finished'); }); let seconds = 0 setInterval(function(){ seconds = seconds + 5 console.log("MAIN: " + seconds + " seconds"); }, 5000); This is the python script: import sys import time print("START") time.sleep(10) print("After 10 seconds") This is the shell: MAIN: Script started MAIN: 5 seconds MAIN: 10 seconds Message from APP: START Message from APP: After 10 seconds The exit code was: 0 The exit signal was: null finished MAIN: 15 seconds A: Ok I found this answer on the github forum. "Output is likely being buffered, meaning you did not send enough data to flush the buffer at least once. Closing stdin (by ending the process) forces the buffer to flush, causing your app to receive data. This is very common, you typically don't want to write every single byte as it would be too IO intensive." https://github.com/extrabacon/python-shell/issues/8 So I changed my code app.py code to import sys import time print("START") sys.stdout.flush() time.sleep(10) print("After 10 seconds") and now the output is correct MAIN: Script started Message from APP: START MAIN: 5 seconds MAIN: 10 seconds Message from APP: After 10 seconds The exit code was: 0 The exit signal was: null finished MAIN: 15 seconds I don't know if there are other better solutions, but with this one it works A: Please use flush in the print function of Python print('Python started from NODE.JS', flush=True)
{ "language": "en", "url": "https://stackoverflow.com/questions/60824569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I play radio streaming in iPhone 5 to X versions in my website? I'm working on a project for a client. It is a radio streaming, now it's working on multiple devices, for example: Chrome, Firefox, Edge, Opera, and for Android devices too. But the problem is that I can’t play from iPhone 5 to X versions. Right now is working with HTML5 audio tag. I’ve been testing jPlayer to play for iPhone but not successful results. How can I make it work?Or is there a script I can reproduce the streaming in iPhones? Here is the sample of the radio station: https://codepen.io/fendercat/pen/zyZWBQ <div id="player"> <div id="player-controles"> <audio id="player_html5" autoplay="" src="http://162.210.196.145:37747/;">Nombre de la Estación</audio> <!-- Botones de control de audio --> <div class="areaPlayer"> <a class="btn" onclick="document.getElementById(&#39;player_html5&#39;).play();"> <i class="fa fa-play"></i> </a> <a class="btn" onclick="document.getElementById(&#39;player_html5&#39;).pause();"> <i class="fa fa-pause"></i> </a> <a class="btn" onclick="document.getElementById(&#39;player_html5&#39;).volume += 0.1;"> <i class="fa fa-volume-up"></i> </a> <a class="btn" onclick="document.getElementById(&#39;player_html5&#39;).volume -= 0.1;"> <i class="fa fa-volume-down"></i> </a> </div><!-- /.areaPlayer --> <script> // Volume Inicial player HTML5 document.getElementById("player_html5").volume=1.0; </script> </div><!-- /#player-controles --> </div><!-- /#player --> The codepen shows a little light gray player with 4 controls (play, pause, volume up and volume down).
{ "language": "en", "url": "https://stackoverflow.com/questions/53889238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Ninject DI for both api and "regular" controllers in MVC4 Possible Duplicate: MVC3 + Ninject - How to? In a small mvc 4 project, I'm trying to implement dependency injection using ninject. So far, I have it working with api controllers, but I'm not having any luck with regular controllers. I have A NinjectResolver: public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver { private readonly IKernel _kernel; public NinjectDependencyResolver(IKernel kernel) : base(kernel) { _kernel = kernel; } public IDependencyScope BeginScope() { return new NinjectDependencyScope(_kernel.BeginBlock()); } public override void Dispose() { _kernel.Dispose(); } } And a NinjectScope: public class NinjectDependencyScope : IDependencyScope { protected IResolutionRoot ResolutionRoot; public NinjectDependencyScope(IResolutionRoot kernel) { ResolutionRoot = kernel; } public object GetService(Type serviceType) { var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true); return ResolutionRoot.Resolve(request).SingleOrDefault(); } public IEnumerable<object> GetServices(Type serviceType) { var request = ResolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true); return ResolutionRoot.Resolve(request).ToList(); } public void Dispose() { var disposable = (IDisposable)ResolutionRoot; if (disposable != null) disposable.Dispose(); ResolutionRoot = null; } } Then I set it up in my Global.asax: var kernel = new StandardKernel(); kernel.Bind(typeof(IRepository)).To(typeof(Repository)); GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); Then I inject a repository into an api controller like this: private IRepository _repository; public TestApiController(IRepository repository) { _repository = repository; } This works fine, but doing the same in a regular controller fails with the "No parameterless constructor defined for this object" error. Any ideas? A: ASP.NET MVC uses a different IDependencyResolver than ASP.NET WebAPi namelly Sytem.Web.Mvc.IDependencyResolver. So you need a new NinjectDependencyResolver implementation for the MVC Controllers (luckily the MVC and WepAPi IDependencyResolver almost has the same members with the same signatures, so it's easy to implement) public class NinjectMvcDependencyResolver : NinjectDependencyScope, System.Web.Mvc.IDependencyResolver { private readonly IKernel _kernel; public NinjectDependencyResolver(IKernel kernel) : base(kernel) { _kernel = kernel; } } And then you can register it in the Global.asax with: DependencyResolver.SetResolver(new NinjectMvcDependencyResolver(kernel));
{ "language": "en", "url": "https://stackoverflow.com/questions/12212561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Table is not formed out of multidimensional array This is the jsfiddle I'm referring to: http://jsfiddle.net/utdAm/212/ I just need to show the same table in my web page. But it just shows the headings in html not the content which is processed in JavaScript. My complete code: <!DOCTYPE HTML> <html> <head> <script src="https://code.jquery.com/jquery-1.7.1.min.js"></script> </head> <body> <table> <tr> <th>Day</th> <th>M</th> <th>T</th> <th>W</th> <th>T</th> <th>F</th> </tr> <tbody data-bind="foreach: prayerData"> <tr> <td data-bind="text: index"></td> <!-- Display the current row --> <td data-bind="text: M"></td> <td data-bind="text: T"></td> <td data-bind="text: W"></td> <td data-bind="text: T"></td> <td data-bind="text: F"></td> </tr> </tbody> </table> <script> var dataFromServer = { "Morn.": { "M": "M,1", "T": "T,1", "W": "W,1", "T": "T,1", "F": "F,1" }, "Noon": { "M": "M,2", "T": "T,2", "W": "W,2", "T": "T,2", "F": "F,2" }, "Even.": { "M": "M,3", "T": "T,3", "W": "W,3", "T": "T,3", "F": "F,3" }, }; var ViewModel = function(data) { //map data to an array var mappedToArray = []; $.each(data, function(index, item) { mappedToArray.push(item); item.index = index; }); this.prayerData = ko.observableArray(mappedToArray); }; ko.applyBindings(new ViewModel(dataFromServer)); </script> </body> </html> Result is: A: While using code in jsfiddle you can also look for external sources towards your left. <script src="https://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://knockoutjs.com/downloads/knockout-2.0.0.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/31956841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert frequency vector to logical matrix I would like to convert a frequency vector (i.e. the colSums() of a matrix) to one of the possible versions of the original logical matrix in R. Something like: s <- c(1,2,3) # Some function of s # Example output: [,1] [,2] [,3] [1,] 0 0 1 [2,] 1 0 0 [3,] 0 1 0 [4,] 0 0 1 [5,] 0 0 1 [6,] 0 1 0 The order of rows is not important. Could someone give me a hint on how to do this? Edit: Rowsums are always 1. The output can be considered a multinomial dataset where each row reflects an observation. A: s <- c(1,2,3) result = matrix(0, nrow = max(s), ncol = length(s)) for (i in seq_along(s)) result[1:s[i], i] = 1 result # [,1] [,2] [,3] # [1,] 1 1 1 # [2,] 0 1 1 # [3,] 0 0 1 Keeping rowsums as 1 s <- c(1,2,3) result = matrix(0, nrow = sum(s), ncol = length(s)) result[cbind(1:sum(s), rep(seq_along(s), times = s))] = 1 result # [,1] [,2] [,3] # [1,] 1 0 0 # [2,] 0 1 0 # [3,] 0 1 0 # [4,] 0 0 1 # [5,] 0 0 1 # [6,] 0 0 1 A: set.seed(523) s <- c(1, 2, 3) n <- 6 sapply(s, function(i) sample(c(rep(1, i), rep(0, n - i)))) # [,1] [,2] [,3] # [1,] 0 1 1 # [2,] 1 0 0 # [3,] 0 1 0 # [4,] 0 0 1 # [5,] 0 0 0 # [6,] 0 0 1 A: # Input: s <- c(1,2,3) # ... set.seed(1) # For reproducibility nr <- sum(s) nc <- length(s) mat <- matrix(0L, nrow = nr, ncol = nc) mat[cbind(seq_len(nr), sample(rep(seq_len(nc), s)))] <- 1L # Output: [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 0 1 [3,] 0 1 0 [4,] 0 0 1 [5,] 0 1 0 [6,] 0 0 1
{ "language": "en", "url": "https://stackoverflow.com/questions/58626344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Crontab Launches Python Script but SystemD Does Not? I can log into my AWS EC2 server via ssh and type: cd /opt/myWebApp sudo python3 /opt/myWebApp/manage.py myCronJob ...and it runs. I can also launch the same script via crontab: 0 */6 * * * sudo python3 /opt/myWebApp/manage.py myCronJob --settings=server.settings.production But when I try to run it in SystemD, with .service file: ExecStart='/usr/bin/python3.7' /opt/myWebApp/manage.py myCronJob --settings=server.settings.production ...I get: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? $PYTHONPATH and $VIRTUAL_ENV are empty. /opt/myWebApp/server_venv is empty as well. There's a python at /usr/bin/python3.7, but I'm referencing that in the SystemD .service file as noted above, and it's throwing that error. What am I missing? A: Solved it! ExecStart='/etc/alternatives/python3' ./manage.py myCronJob --settings=server.settings.production WorkingDirectory=/opt/myWebapp User=myUser The user ('myUser' in the above code) has access to Django.
{ "language": "en", "url": "https://stackoverflow.com/questions/59587091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Calculating field to input into MySQL table based on form input and variable from second MySQL table PHP I am stuck on a query/calculation based on two different tables (joined by a third table). A form collects information to input into tbl2, tbl1 is linked to tbl2 via foreign key. I need to calculate and insert a value into tbl2 based on form data and a value from tbl1. My Query + Calculation looks like this: $res = $user->runQuery("SELECT binWeight FROM jobBins jb JOIN butchJobOpen bjo ON bjo.jobBins_binID = jb.binID JOIN butchJobClose bjc ON bjc.butchJobOpen_butchJobNum = bjo.butchJobNum WHERE bjo.butchJobNum = '$butchJobOpen_butchJobNum'"); $res->execute(); $row = $res->fetch(PDO::FETCH_ASSOC); //Calculate $trimYield $trimYield = $row['binWeight'] / $trimWeight; The query should use a form value $butchJobOpen_butchJobNum, verify the bin exists on the join conditions, and return the weight of the bin....this works fine as a standalone query, however, I cannot get any results from my calculation...I am sure I am just missing something stupid...but I am stuck, so I lob this up to the merciless SO community, in hopes that while getting downvoted, someone will point me in the right direction while ridiculing my obvious mistake. A: Okay, here is what you have to do * *Get rid of all the home-brewed stuff. Instead of whatever $user->runQuery use vanilla PDO. *Verify the input. See whether your variable contain anything useful. *Use PDO properly, utilizing prepared statements. *Make your code to give at least any outcome. *Do realize that above instruction is not a ready to use solution on a golden plate but just steps you have to make yourself to investigate the problem. So ini_set('display_errors',1); error_reporting(E_ALL); $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]; $pdo = new PDO($dsn, $user, $pass, $opt); var_dump("that argle-bargle var name I can't type it:",$butchJobOpen_butchJobNum); $sql = "SELECT binWeight FROM jobBins jb JOIN butchJobOpen bjo ON bjo.jobBins_binID = jb.binID JOIN butchJobClose bjc ON bjc.butchJobOpen_butchJobNum = bjo.butchJobNum WHERE bjo.butchJobNum = ?"; $res = $pdo->prepare($sql); $res->execute([$butchJobOpen_butchJobNum]); $binWeight = $res->fetchColumn(); var_dump("bin weight:", $binWeight); var_dump("trim weight:", $trimWeight); $trimYield = $binWeight / $trimWeight; var_dump("finally", $trimYield); The var_dump part is most essential, giving you a clue what's going on in your program. A 10000 times more fruitful than a hour of staring at the code or a whine on SO. The point here is to verify every bloody variable's state. And yo see whether it contains anything expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/40289361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What's the best way of implementing a buffer of fixed size when using fread in C++? Suppose that you have a file of integers and you want to read them one by one. You have two options for buffering. * *Declare an array buffer of size N and use setvbuf to tell fread which buffer to use. Then when calling the function fread to read an integer you write fread(&myInt, sizeof(myInt), 1, inputFile); *Declare the same array buffer but this time don't use the function setvbuf. Instead work on the buffering by yourself. So call fread(buffer, bufferSize*sizeof(int), 1, inputFile) From my understanding setvbuf exists to make your life easier, but does it come at a cost? Which method would you use in terms of performance? A: I would use neither of your examples. I don't think that part of the I/O is the performance bottleneck. The vbuf is an area for the input routine to place data before putting it into your destination. It could be used as a cache or as a preformatting buffer. Most of the time, I/O bottlenecks are related to the quantity of data fetched and the number of fetches. For example, reading one byte at a time is less efficient than reading a block of bytes. Another I/O related bottleneck is the duration between input requests. I/O devices prefer to keep streaming data, non-stop. Some input devices, like hard drives, have an overhead time between when the request is received and when the data starts transmitting. For hard drives, this would be the disk speed up time. Your best performance is not to waste development time messing with the C or C++ libraries. You need to use hardware assist. Some platforms have a device called a Direct Memory Access controller (DMA). This device can take data from an input source and deliver it to memory without using the CPU. The CPU can be executing instructions while the DMA is transferring data. In order to use hardware assistance, you need to write code at the OS driver level, or access the OS drivers directly. The C and C++ I/O libraries are designed for a platform independent concept called streams. There may be execution overhead associated with this (such as extra buffering). If you don't care about different platforms, then access the OS drivers directly. Don't waste your time messing with the C and C++ libraries. Not much performance gain there. More performance lies in accessing the OS drivers directly (or using your own). How and when you access the I/O will show bigger performance gains than tweaking the C and C++ libraries. Lastly, using the processors data cache effectively will gain you performance too.
{ "language": "en", "url": "https://stackoverflow.com/questions/26369110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJS CORS error while making post request to the local nodeJS server I'm trying to send json data over post request but getting errors, I've tried many answers of stackoverflow but not getting answer I've also tried jsonp method but not getting any thing. XMLHttpRequest cannot load http://localhost:3000/lvl/2/data. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. angular.js:14516 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:3000/lvl/2/data","headers":{"Authorization":"Basic dGVzdDp0ZXN0","Content-Type":"application/x-www-form-urlencoded","Accept":"application/json, text/plain, /"},"data":{"Code":"test data"}},"statusText":""} http post request: $http({ url:'http://localhost:3000/lvl/2/data', method:"POST", headers: { 'Authorization': 'Basic dGVzdDp0ZXN0', 'Content-Type': 'application/x-www-form-urlencoded' }, data: { 'Code': 'test data' } }).then(function() { console.log('submitted') }); NodeJs Post request: router.post('/lvl/2/data', function (req, res){ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); res.header("Access-Control-Max-Age", "3600"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); console.log(req.body); res.send('submitted'); }); A: You can temporary disable checking CORS with extension for browser: Chrome: Allow-Control-Allow-Origin: * For Opera you should install: 1)Extension allows you to install extensions from Chrome Web Store 2)Allow-Control-Allow-Origin: *
{ "language": "en", "url": "https://stackoverflow.com/questions/42963814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android values.xml inner element must either be a resource reference or empty This is my code for my values.xml file. I am running into difficulty getting my project to run because apparently there is an error with this file on line 2 column 4 according to this error: C:\Users\16094\.gradle\caches\transforms-2\files-2.1\2163979b6567cda52ae0ebf1a205491d\fragment-1.3.4\res\values\values.xml:2:4: <item> inner element must either be a resource reference or empty. This is the code for my XML file: <?xml version="1.0" encoding="utf-8"?> <resources> <item name="fragment_container_view_tag" type="id"/> <item name="special_effects_controller_view_tag" type="id"/> <item name="visible_removing_fragment_view_tag" type="id"/> <declare-styleable name="Fragment"> <attr name="android:name"/> <attr name="android:id"/> <attr name="android:tag"/> </declare-styleable> <declare-styleable name="FragmentContainerView"> <attr name="android:name"/> <attr name="android:tag"/> </declare-styleable> </resources> I already read through this but I could not find anything wrong with my file: https://developer.android.com/guide/topics/resources/more-resources A: Seems like there are no errors in XML fragment you shared. I know the sample you're playing with, the error caused by wrong ID resource definition in ids.xml <item name="button" type="id">Button</item> But according to documentaion ID definition takes no value. So the fix is: <item name="button" type="id" />
{ "language": "en", "url": "https://stackoverflow.com/questions/68432617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any of java type or classes is recognized by Eclipse I installed ubuntu 12.04 then I install java and I set my environment variable as usually but eclipse can't recognize any java variable type or any class java -version java version "1.7.0_45" Java(TM) SE Runtime Environment (build 1.7.0_45-b18) Java HotSpot(TM) Server VM (build 24.45-b08, mixed mode) bashrc export JAVA_HOME=/usr/lib/jvm/java-7-oracle export MAVEN_HOME=/usr/share/maven export PATH=${PATH}:${JAVA_HOME}/bin:${MAVEN_HOME}/bin How can I fix this problem ? A: Check eclipse settings there is a "installed JRE" preference: (linux, juno) Also, make sure you have a "JRE System Library" in your project classpath:
{ "language": "en", "url": "https://stackoverflow.com/questions/19960807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Center the PopupView? (vaadin) See http://demo.vaadin.com/sampler/#ui/structure/popup-view I can create a popup as seen in the vaadin sampler but how can I center to the middle of the window? I thought I could do .center() like you can do with a vaadin window. Any ideas? A: The position of the popup of a PopupView is always relative to the PopupView component. So the only way to center the popup to the middle of the Window is to but the PopupView component itself to the middle of the Window.
{ "language": "en", "url": "https://stackoverflow.com/questions/27421350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to login in Magento Admin I just installed magento 2.0.3 on mac . The installation is done with success. My admin address is Magento Admin Address: http://127.0.0.1/magento3/admin/ On click of this link , I am getting The requested URL /magento3/admin/ was not found on this server. error. I have copied pub/.htacess file to magento folder but no luck. Even the home page i.e. http://127.0.0.1/magento3 is coming with broken js & css
{ "language": "en", "url": "https://stackoverflow.com/questions/43761421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Yum dependency I'm trying to install doesn't have a provider One of the dependencies of the rlwrap package I'm trying to install doesn't have a provider. Is there a command line option I can pass to the install to let it forget about the perl(File::Slurp) dependency? package: rlwrap-0.45.2-2.el8.x86_64 dependency: /usr/bin/perl provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: /usr/bin/python3 provider: python36-3.6.8-38.module+el8.5.0+12207+5c5719bc.x86_64 provider: python38-3.8.13-1.module+el8.7.0+15641+2ece4388.x86_64 provider: python39-3.9.13-2.module+el8.7.0+17195+44752b34.x86_64 dependency: libc.so.6(GLIBC_2.15)(64bit) provider: glibc-2.28-211.el8.x86_64 dependency: libreadline.so.7()(64bit) provider: readline-7.0-10.el8.x86_64 dependency: libtinfo.so.6()(64bit) provider: ncurses-libs-6.1-9.20180224.el8.x86_64 dependency: libutil.so.1()(64bit) provider: glibc-2.28-211.el8.x86_64 dependency: libutil.so.1(GLIBC_2.2.5)(64bit) provider: glibc-2.28-211.el8.x86_64 dependency: perl(:VERSION) >= 5.6.0 provider: perl-libs-4:5.26.3-421.el8.i686 provider: perl-libs-4:5.26.3-421.el8.x86_64 dependency: perl(AutoLoader) provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: perl(Carp) provider: perl-Carp-1.42-396.el8.noarch dependency: perl(Config) provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: perl(Data::Dumper) provider: perl-Data-Dumper-2.167-399.el8.x86_64 dependency: perl(Exporter) provider: perl-Exporter-5.72-396.el8.noarch dependency: perl(File::Slurp) dependency: perl(Getopt::Std) provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: perl(POSIX) provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: perl(RlwrapFilter) provider: rlwrap-0.45.2-2.el8.x86_64 dependency: perl(constant) provider: perl-constant-1.33-396.el8.noarch dependency: perl(lib) provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: perl(strict) provider: perl-libs-4:5.26.3-421.el8.i686 provider: perl-libs-4:5.26.3-421.el8.x86_64 dependency: perl(vars) provider: perl-interpreter-4:5.26.3-421.el8.x86_64 dependency: rtld(GNU_HASH) provider: glibc-2.28-211.el8.i686 provider: glibc-2.28-211.el8.x86_64 I have installed the perl(File::Slurp) dependency separately. For reference, this is the command I am using to install the rlwrap package and error: yum install rlwrap Last metadata expiration check: 0:41:10 ago on Thu Dec 22 16:38:35 2022. Error: Problem: cannot install the best candidate for the job - nothing provides perl(File::Slurp) needed by rlwrap-0.45.2-2.el8.x86_64 (try to add '--skip-broken' to skip uninstallable packages or '--nobest' to use not only best candidate packages) I have tried the suggestions from the yum output. A: I was wrong about EPEL having all the dependencies. It looks like perl-File-Slurp lives in the "AppStream" repository. You can add the the CentOS 8 version of that repository to your ubi8 image: * *Install dnf if you haven't already: microdnf install dnf *Add the repository configuration (note that I have this disabled by default): cat > /etc/yum.repos.d/centos-appstream.repo <<'EOF' [appstream] name=CentOS Stream $releasever - AppStream mirrorlist=http://mirrorlist.centos.org/?release=$releasever-stream&arch=$basearch&repo=AppStream&infra=$infra gpgcheck=1 enabled=0 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial EOF *Install the CentOS 8 GPG key: rpm --import https://www.centos.org/keys/RPM-GPG-KEY-CentOS-Official *Enable the EPEL repository if you haven't already: dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm *Install rlwrap: dnf --enablerepo=appstream install rlwrap Alternately, instead of installing rlwrap and it's myriad dependencies, just install socat: microdnf install socat And then use the readline and exec connectors: socat readline exec:"/path/to/some/program --arg foo",pty
{ "language": "en", "url": "https://stackoverflow.com/questions/74891869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery plugin not allowing me to insert Bootstrap badge inside tag I've followed the html example of a jQuery sliding menu from the following website: http://github.danielcardoso.net/sliding-menu/ I'm able to add icons inside the <a> tags, however I would also like to insert a bootstrap Badge element inside as well. Currently the jQuery plugin used seems to simply ignore or hide the Bootstrap badge element completely. Is there a way to add a badge element inside the <a> tag? <div id="menuHTML"> <ul> <li> <a href="#">Catalogue</a> <ul> <li> <a href="#">Bathroom <i class="sm-set-icon fa fa-play"></i> Play </a> </li> <li> <a href="#">Bedroom</a> </li> <li> <a href="#">Kitchen</a> </li> <li> <a href="#">Living Room</a> </li> </ul> </li> <li> <a href="#">Orders</a> <ul> <li> <a href="#">Pending</a> </li> <li> <a href="#">Completed</a> </li> <li> <a href="#">Other</a> </li> </ul> </li> </ul> </div> A: As you mentioned you are using font-awesome icons so i think you are missing the font-awesome reference link add the below link inside your head it will work fine <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css"> also see the below code snippet i added Badges ,font-awesome icons and glyphicon for your help. you can Use whatever you like <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css"> <style> </style> </head> <body> <div id="menuHTML"> <ul> <li> <a href="#">Catalogue</a> <ul> <li> <a href="#">Bathroom <span class="glyphicon glyphicon-search" aria-hidden="true"> </span></a> </li> <li> <a href="#">Bedroom <span class="badge">42</span></a> </li> <li> <a href="#">Kitchen <i class="sm-set-icon fa fa-play"></i> Play</a> </li> <li> <a href="#">Living Room</a> </li> </ul> </li> <li> <a href="#">Orders</a> <ul> <li> <a href="#">Pending</a> </li> <li> <a href="#">Completed</a> </li> <li> <a href="#">Other</a> </li> </ul> </li> </ul> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/39944654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Date.now() returns a value in microseconds and not in milliseconds Date.now(), as per the documentation is supposed to return a Unix timestamp or the Epoch Time, that is, the number of milliseconds that have lapsed since 1st January 1970. The current unix timestamp as per this website (or any other valid means of computation) is approximately 1554637184. Note that there are 10 digits in this value. This value is actually in milliseconds. However, the value returned by Date.now() in all the three browsers -- Chrome 73, Firefox 66.0.2 and Edge 17.17134 -- is 1554637694364, which is observed to be of 13 digits, and therefore, I infer it is the number of microseconds that have elapsed since 1st January 1970. What's going on? I just realized this after years of using it because just now I was debugging some code that made a check like so that failed: let endTime = ...; // a time later than now expressed as a unix timestamp let now = Date.now(); if (endTime <= now) { // And it always came here, and that led me to this discovery ... } A: The current epoch time (AKA unix timestamp), 1554637856 is the number of seconds since 01-01-1970, not milliseconds. Date.now() returns the epoch time in milliseconds, so you'd want seconds: if (endTime <= now / 1000) { ... A: As of this writing the time in seconds since the UNIX epoch is about 1 554 637 931. So, the time in milliseconds—the JavaScript time—is about 1 554 637 931 654. It’s been about 1.55 gigaseconds since the epoch. Your JavaScript timestamps are, in fact, milliseconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/55558695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to present json files and directories? I have the following json file , how could I represent the the list of files and the documents, and when i press on a document it will show the files inside ? { "d_type":"directory", "name":".", "size":1020, "subdirectory":[ { "d_type":"file", "name":".DS_Store", "size":15364 }, { "d_type":"directory", "name":"simplejson-3.6.5", "size":578, "subdirectory":[ { "d_type":"file", "name":".DS_Store", "size":12292 }, { "d_type":"directory", "name":"build", "size":170, "subdirectory":[ { "d_type":"directory", "name":"bdist.macosx-10.9-intel", "size":68, "subdirectory":[ ] }, { "d_type":"directory", "name":"lib.macosx-10.9-intel-2.7", "size":102, "subdirectory":[ { "d_type":"directory", "name":"simplejson", "size":374, "subdirectory":[ { "d_type":"file", "name":"init.py", "size":23137 }, { "d_type":"directory", "name":"tests", "size":986, "subdirectory":[ { "d_type":"file", "name":"test_unicode.py", "size":6996 } ] } ] } ] }, { "d_type":"directory", "name":"temp.macosx-10.9-intel-2.7", "size":102, "subdirectory":[ { "d_type":"directory", "name":"simplejson", "size":102, "subdirectory":[ { "d_type":"file", "name":"_speedups.o", "size":268464 } ] } ] } ] } ] } ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/29399543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert a directory at the start of a URL in Apache Config Apologies if this question has already been asked before. I couldn't find an example that handled my exact situation. I have an Apache Server and have access to the httpd.conf file. I have a domain (say www.example.com) and I want to insert a directory (say test) after the domain. So for example I want www.example.com to be mapped to www.example.com/test and www.example.com/folder to be mapped to www.example.com/test/folder and so on. I have achieved this using the a RedirectMatch directive like this:- <VirtualHost *:80> ServerName www.example.com RedirectMatch ^/$ test/ </VirtualHost> However this changes the URL in the browser to include the test folder and I would like to keep this hidden from the end user. I have tried using a rewrite rule but my lack of regex knowledge has let me down here! This is what I have tried (within the virtual host element):- RewriteEngine On RewriteCond %{REQUEST_URI} !^/test/ RewriteRule ^(.*)$ /test/$1 I have tried various combinations with this but nothing seems to work! Any help would be much appreciated. A: Ok, I found the problem here. This was working ok but my browser cache (Firefox) was remembering the old values. I turned of caching in the browser (by going to about:config and setting browser.cache.disk.enable = FALSE Then everything started working correctly. Hopefully this will help others who have the same issue!
{ "language": "en", "url": "https://stackoverflow.com/questions/24757724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: explanation of the syntax <%= %> I am using the <%= %> syntax for passing the html control textarea id in the JavaScript function. I have a problem that after saving the my aspx page when I run the page it runs successfully but after some it automatically disappears from the html code. sombody can explain the above syntax and why it disapear from the source code after a given time here is the code before execute i write code and save. <textarea id="txtmsgchar" cols="20" name="txtmsgchar" onkeyup="return taCount(this,'<%= lblcharcount.ClientID %>','<%= lbltotalmsg.ClientID %>')" rows="10" style="width: 477px; height: 111px"> </textarea> After some time or when I open the project next time then I find the below code <textarea id="txtmsgchar" cols="20" name="txtmsgchar" onkeyup="return taCount(this,'','')" rows="10" style="width: 477px; height: 111px"> </textarea> Please tell me why the given output comes A: It is server code that is executed. The expression is replaced by the value of lbltotalmsg.ClientID. The result that is sent to the client is therefor something like this: ','some-client-id')" rows="10" style="width: 477px; height: 111px"> A: After some time or when i open the project next time then i find the below code That doesn't seem to be possible unless you don't save, or unless you look at the code-view from a browser (i.e., after the page is rendered). Another thought might be that you're inside a version control system connected to an auto-build environment, which may rollback your changes if they contain compile errors (but I doubt that any build environment does so automatically). Regardless, your issue has nothing to do with the <%= > itself, which simply interprets the expression on server side and outputs its value. Update: perhaps your issue is the following: if the controls lbltotalmsg or lblcharcount are invisible (server-side Visible="False"), they are not rendered to the client side and hence will have an empty ClientId. A: It runs a C# or VB.NET expression. Like DateTime.Now
{ "language": "en", "url": "https://stackoverflow.com/questions/3492855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: extension method with type specific List I want to create an extention method to bind a List, but getting this error. menuItem.Children.Bind(); public static class Extensions { public static void Bind(this IList list) { //some stuff } } class MenuItemMap : Mapper<MenuItem> { public MenuItemMap() { Id(x => x.MenuItemId); Map(x => x.Text); HasMany(x => x.Children).KeyColumn("ParentId"); References(x => x.Parent); } } public class MenuItem : BaseClass<MenuItem> { public virtual int MenuItemId { get; set; } public virtual string Text { get; set; } public virtual IList<MenuItem> Children { get; set; } public virtual MenuItem Parent { get; set; } public MenuItem() { Children = new List<MenuItem>(); } } A: Your extension method is written for IList not IList<T> and because IList<T> does not inherit IList, you need to specify type argument in the extension method: public static class Extensions { public static void Bind<T>(this IList<T> list) { //some stuff } }
{ "language": "en", "url": "https://stackoverflow.com/questions/30015822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SonarQube analysis via Maven fails with database access denied to MySQL I have instances of MySQL, SonarQube, and TeamCity all running on the same Linux host. All are very vanilla installations (out of the box / insecure / local / behind company firewall). These are my Maven settings ... where ${fullyQualifiedDomainName} is something like build.company.com <profile> <id>env-dev</id> <properties> <downloadSources>true</downloadSources> <downloadJavadocs>false</downloadJavadocs> <sonar.jdbc.url>jdbc:mysql://${fullyQualifiedDomainName}:3306/sonar?useUnicode=true&amp;characterEncoding=utf8</sonar.jdbc.url> <sonar.jdbc.username>sonar</sonar.jdbc.username> <sonar.jdbc.password>sonar</sonar.jdbc.password> <sonar.host.url>http://${fullyQualifiedDomainName}:9000</sonar.host.url> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> I run the command mvn sonar:sonar to perform and upload SonarQube analysis. The Maven settings above work OK from my Windows PC. However, if I run from the Linux server via TeamCity, I see this error: (giant Java stacktrace + ...): [ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.5:sonar (default-cli) on project IMQuant: Fail to connect to database: Cannot create PoolableConnectionFactory (Access denied for user 'sonar'@'${fullyQualifiedDomainName}' (using password: YES)) -> [Help 1] If I switch to use localhost in the Maven settings it runs OK on the Linux server. I am guessing this is one of the following issues: * *MySQL config (I am a MySQL newbie) *Linux server config (network config / admin stuff beyond my control) *MySQL JDBC driver bug (localhost != fqdn from localhost) For now I am using a second Maven profile in my settings for TeamCity / Linux with localhost. Is there a solution for this issue? Has anyone seen this issue? Update Here are the commands to create my MySQL database for SonarQube. As noted by @Mithfindel, it may be the root cause. CREATE DATABASE sonar CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE USER 'sonar' IDENTIFIED BY 'sonar'; GRANT ALL ON sonar.* TO 'sonar'@'%' IDENTIFIED BY 'sonar'; GRANT ALL ON sonar.* TO 'sonar'@'localhost' IDENTIFIED BY 'sonar'; FLUSH PRIVILEGES; Ref: https://github.com/SonarSource/sonar-examples/blob/master/scripts/database/mysql/create_database.sql A: It looks like a MySQL configuration issue: for MySQL, a GRANT on localhost is different from a GRANT on localhost's FQDN. You might want to check which permissions are granted to users 'sonar'@'localhost' and 'sonar'@'fqdn-of-localhost' or 'sonar'@'%'.
{ "language": "en", "url": "https://stackoverflow.com/questions/28782900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }