input
stringlengths
51
42.3k
output
stringlengths
18
55k
R boolean statement <p>So, I'm doing an R code project for school, and there are 36 columns (9 related to column supercategory Exams, 8 related to Writing, 4 related to Collaboration, and 15 related to Other) of categorical variables each with the levels "1 time", "2-4 times", and ">4 times". I want to write a Boolean statement that finds any row that has at least "1 time" for any of these columns, and I have this:</p> <pre><code> SurveyDataSP16$SerOff &lt;- factor(ifelse(((SurveyDataSP16$Exams_A=="1 time"|SurveyDataSP16$Exams_A=="2-4 times"|SurveyDataSP16$Exams_A=="&gt;4 times")|(SurveyDataSP16$Exams_B=="1 time"|SurveyDataSP16$Exams_B=="2-4 times"|SurveyDataSP16$Exams_B=="&gt;4 times")|(SurveyDataSP16$Exams_C=="1 time"|SurveyDataSP16$Exams_C=="2-4 times"|SurveyDataSP16$Exams_C=="&gt;4 times")|(SurveyDataSP16$Exams_D=="1 time"|SurveyDataSP16$Exams_D=="2-4 times"|SurveyDataSP16$Exams_D=="&gt;4 times")|(SurveyDataSP16$Exams_E=="1 time"|SurveyDataSP16$Exams_E=="2-4 times"|SurveyDataSP16$Exams_E=="&gt;4 times")|(SurveyDataSP16$Exams_F=="1 time"|SurveyDataSP16$Exams_F=="2-4 times"|SurveyDataSP16$Exams_F=="&gt;4 times")|(SurveyDataSP16$Exams_G=="1 time"|SurveyDataSP16$Exams_G=="2-4 times"|SurveyDataSP16$Exams_G=="&gt;4 times")| (SurveyDataSP16$Exams_H=="1 time"|SurveyDataSP16$Exams_H=="2-4 times"|SurveyDataSP16$Exams_H=="&gt;4 times")|(SurveyDataSP16$Exams_I=="1 time"|SurveyDataSP16$Exams_I=="2-4 times"|SurveyDataSP16$Exams_I=="&gt;4 times"))|((SurveyDataSP16$Writing_A=="1 time"|SurveyDataSP16$Writing_A=="2-4 times"|SurveyDataSP16$Writing_A=="&gt;4 times")| (SurveyDataSP16$Writing_B=="1 time"|SurveyDataSP16$Writing_B=="2-4 times"|SurveyDataSP16$Writing_B=="&gt;4 times")|(SurveyDataSP16$Writing_C=="1 time"|SurveyDataSP16$Writing_C=="2-4 times"|SurveyDataSP16$Writing_C=="&gt;4 times")|(SurveyDataSP16$Writing_D=="1 time"|SurveyDataSP16$Writing_D=="2-4 times"|SurveyDataSP16$Writing_D=="&gt;4 times")|(SurveyDataSP16$Writing_E=="1 time"|SurveyDataSP16$Writing_E=="2-4 times"|SurveyDataSP16$Writing_E=="&gt;4 times")| (SurveyDataSP16$Writing_F=="1 time"|SurveyDataSP16$Writing_F=="2-4 times"|SurveyDataSP16$Writing_F=="&gt;4 times")|(SurveyDataSP16$Writing_G=="1 time"|SurveyDataSP16$Writing_G=="2-4 times"|SurveyDataSP16$Writing_G=="&gt;4 times")) |((SurveyDataSP16$Collaboration_A=="1 time"|SurveyDataSP16$Collaboration_A=="2-4 times"|SurveyDataSP16$Collaboration_A=="&gt;4 times")|(SurveyDataSP16$Collaboration_B=="1 time"|SurveyDataSP16$Collaboration_B=="2-4 times"|SurveyDataSP16$Collaboration_B=="&gt;4 times")|(SurveyDataSP16$Collaboration_C=="1 time"|SurveyDataSP16$Collaboration_C=="2-4 times"|SurveyDataSP16$Collaboration_C=="&gt;4 times")|(SurveyDataSP16$Collaboration_D=="1 time"|SurveyDataSP16$Collaboration_D=="2-4 times"|SurveyDataSP16$Collaboration_D=="&gt;4 times"))|((SurveyDataSP16$Other_A=="1 time"|SurveyDataSP16$Other_A=="2-4 times"|SurveyDataSP16$Other_A=="&gt;4 times")|(SurveyDataSP16$Other_B=="1 time"|SurveyDataSP16$Other_B=="2-4 times"|SurveyDataSP16$Other_B=="&gt;4 times")|(SurveyDataSP16$Other_C=="1 time"|SurveyDataSP16$Other_C=="2-4 times"|SurveyDataSP16$Other_C=="&gt;4 times")|(SurveyDataSP16$Other_D=="1 time"|SurveyDataSP16$Other_D=="2-4 times"|SurveyDataSP16$Other_D=="&gt;4 times")|(SurveyDataSP16$Other_E=="1 time"|SurveyDataSP16$Other_E=="2-4 times"|SurveyDataSP16$Other_E=="&gt;4 times")|(SurveyDataSP16$Other_F=="1 time"|SurveyDataSP16$Other_F=="2-4 times"|SurveyDataSP16$Other_F=="&gt;4 times")|(SurveyDataSP16$Other_G=="1 time"|SurveyDataSP16$Other_G=="2-4 times"|SurveyDataSP16$Other_G=="&gt;4 times")| (SurveyDataSP16$Other_H=="1 time"|SurveyDataSP16$Other_H=="2-4 times"|SurveyDataSP16$Other_H=="&gt;4 times")|(SurveyDataSP16$Other_I=="1 time"|SurveyDataSP16$Other_I=="2-4 times"|SurveyDataSP16$Other_I=="&gt;4 times")|(SurveyDataSP16$Other_J=="1 time"|SurveyDataSP16$Other_J=="2-4 times"|SurveyDataSP16$Other_J=="&gt;4 times")|(SurveyDataSP16$Other_K=="1 time"|SurveyDataSP16$Other_K=="2-4 times"|SurveyDataSP16$Other_K=="&gt;4 times")|(SurveyDataSP16$Other_L=="1 time"|SurveyDataSP16$Other_L=="2-4 times"|SurveyDataSP16$Other_L=="&gt;4 times")|(SurveyDataSP16$Other_M=="1 time"|SurveyDataSP16$Other_M=="2-4 times"|SurveyDataSP16$Other_M=="&gt;4 times")|(SurveyDataSP16$Other_N=="1 time"|SurveyDataSP16$Other_N=="2-4 times"|SurveyDataSP16$Other_N=="&gt;4 times")|(SurveyDataSP16$Other_O=="1 time"|SurveyDataSP16$Other_O=="2-4 times"|SurveyDataSP16$Other_O=="&gt;4 times")), "yes", "no")) </code></pre> <p>Is there a shorter way to do this?</p>
<p>first I created some dummy data and add "0 times" in the possible levels:</p> <pre><code>nam &lt;- " factor(ifelse(((SurveyDataSP16$Exams_A==1 time|SurveyDataSP16$Exams_A==2-4 times|SurveyDataSP16$Exams_A==&gt;4 times)|(SurveyDataSP16$Exams_B==1 time|SurveyDataSP16$Exams_B==2-4 times|SurveyDataSP16$Exams_B==&gt;4 times)|(SurveyDataSP16$Exams_C==1 time|SurveyDataSP16$Exams_C==2-4 times|SurveyDataSP16$Exams_C==&gt;4 times)|(SurveyDataSP16$Exams_D==1 time|SurveyDataSP16$Exams_D==2-4 times|SurveyDataSP16$Exams_D==&gt;4 times)|(SurveyDataSP16$Exams_E==1 time|SurveyDataSP16$Exams_E==2-4 times|SurveyDataSP16$Exams_E==&gt;4 times)|(SurveyDataSP16$Exams_F==1 time|SurveyDataSP16$Exams_F==2-4 times|SurveyDataSP16$Exams_F==&gt;4 times)|(SurveyDataSP16$Exams_G==1 time|SurveyDataSP16$Exams_G==2-4 times|SurveyDataSP16$Exams_G==&gt;4 times)| (SurveyDataSP16$Exams_H==1 time|SurveyDataSP16$Exams_H==2-4 times|SurveyDataSP16$Exams_H==&gt;4 times)|(SurveyDataSP16$Exams_I==1 time|SurveyDataSP16$Exams_I==2-4 times|SurveyDataSP16$Exams_I==&gt;4 times))|((SurveyDataSP16$Writing_A==1 time|SurveyDataSP16$Writing_A==2-4 times|SurveyDataSP16$Writing_A==&gt;4 times)| (SurveyDataSP16$Writing_B==1 time|SurveyDataSP16$Writing_B==2-4 times|SurveyDataSP16$Writing_B==&gt;4 times)|(SurveyDataSP16$Writing_C==1 time|SurveyDataSP16$Writing_C==2-4 times|SurveyDataSP16$Writing_C==&gt;4 times)|(SurveyDataSP16$Writing_D==1 time|SurveyDataSP16$Writing_D==2-4 times|SurveyDataSP16$Writing_D==&gt;4 times)|(SurveyDataSP16$Writing_E==1 time|SurveyDataSP16$Writing_E==2-4 times|SurveyDataSP16$Writing_E==&gt;4 times)| (SurveyDataSP16$Writing_F==1 time|SurveyDataSP16$Writing_F==2-4 times|SurveyDataSP16$Writing_F==&gt;4 times)|(SurveyDataSP16$Writing_G==1 time|SurveyDataSP16$Writing_G==2-4 times|SurveyDataSP16$Writing_G==&gt;4 times)) |((SurveyDataSP16$Collaboration_A==1 time|SurveyDataSP16$Collaboration_A==2-4 times|SurveyDataSP16$Collaboration_A==&gt;4 times)|(SurveyDataSP16$Collaboration_B==1 time|SurveyDataSP16$Collaboration_B==2-4 times|SurveyDataSP16$Collaboration_B==&gt;4 times)|(SurveyDataSP16$Collaboration_C==1 time|SurveyDataSP16$Collaboration_C==2-4 times|SurveyDataSP16$Collaboration_C==&gt;4 times)|(SurveyDataSP16$Collaboration_D==1 time|SurveyDataSP16$Collaboration_D==2-4 times|SurveyDataSP16$Collaboration_D==&gt;4 times))|((SurveyDataSP16$Other_A==1 time|SurveyDataSP16$Other_A==2-4 times|SurveyDataSP16$Other_A==&gt;4 times)|(SurveyDataSP16$Other_B==1 time|SurveyDataSP16$Other_B==2-4 times|SurveyDataSP16$Other_B==&gt;4 times)|(SurveyDataSP16$Other_C==1 time|SurveyDataSP16$Other_C==2-4 times|SurveyDataSP16$Other_C==&gt;4 times)|(SurveyDataSP16$Other_D==1 time|SurveyDataSP16$Other_D==2-4 times|SurveyDataSP16$Other_D==&gt;4 times)|(SurveyDataSP16$Other_E==1 time|SurveyDataSP16$Other_E==2-4 times|SurveyDataSP16$Other_E==&gt;4 times)|(SurveyDataSP16$Other_F==1 time|SurveyDataSP16$Other_F==2-4 times|SurveyDataSP16$Other_F==&gt;4 times)|(SurveyDataSP16$Other_G==1 time|SurveyDataSP16$Other_G==2-4 times|SurveyDataSP16$Other_G==&gt;4 times)| (SurveyDataSP16$Other_H==1 time|SurveyDataSP16$Other_H==2-4 times|SurveyDataSP16$Other_H==&gt;4 times)|(SurveyDataSP16$Other_I==1 time|SurveyDataSP16$Other_I==2-4 times|SurveyDataSP16$Other_I==&gt;4 times)|(SurveyDataSP16$Other_J==1 time|SurveyDataSP16$Other_J==2-4 times|SurveyDataSP16$Other_J==&gt;4 times)|(SurveyDataSP16$Other_K==1 time|SurveyDataSP16$Other_K==2-4 times|SurveyDataSP16$Other_K==&gt;4 times)|(SurveyDataSP16$Other_L==1 time|SurveyDataSP16$Other_L==2-4 times|SurveyDataSP16$Other_L==&gt;4 times)|(SurveyDataSP16$Other_M==1 time|SurveyDataSP16$Other_M==2-4 times|SurveyDataSP16$Other_M==&gt;4 times)|(SurveyDataSP16$Other_N==1 time|SurveyDataSP16$Other_N==2-4 times|SurveyDataSP16$Other_N==&gt;4 times)|(SurveyDataSP16$Other_O==1 time|SurveyDataSP16$Other_O==2-4 times|SurveyDataSP16$Other_O==&gt;4 times)), yes, no))" nam &lt;- unlist(strsplit(nam, split = "SP16")) nam &lt;- strsplit(nam, split = "==") nam &lt;- unlist(lapply(nam, `[[`, 1))[-1] nam &lt;- nam[!duplicated(nam)] nam &lt;- substr(nam, 2, 999) tmp &lt;- c(rep("0 time", 100), "1 time", "2-4 times", "&gt;4 times") SurveyDataSP16 &lt;- matrix(sample(tmp, 35*10, replace=T), ncol=35) colnames(SurveyDataSP16) &lt;- nam SurveyDataSP16 &lt;- as.data.frame(SurveyDataSP16) </code></pre> <p>this is my solution</p> <pre><code>tmp &lt;- apply(SurveyDataSP16, 2, is.element, set=c("1 time", "2-4 times", "&gt;4 times")) apply(tmp, 1, any) </code></pre>
$http.post not woking in AngularJS <p>I'm trying to make a $http.post request but I have the following error:</p> <blockquote> <p>XMLHttpRequest cannot load <a href="https://mipage.com/examplephp" rel="nofollow">https://mipage.com/examplephp</a>. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.</p> </blockquote> <p>If I change <strong>$http.post</strong> to <strong>$http.get</strong> request the server response with the JSON, so.. I think is not problem the CORS. Also I put a proxy in the ionic project.</p> <p>This is my function:</p> <pre><code>function obtenerSesion() { debugger; return $http.post(iniciarSesionUrl, {params: {username: 'prueba123',password: 'prueba123'}}).then(function(response) { canchas = response.data; return canchas; }) .catch(generarError); } </code></pre> <p>Also the server return the JSON with or without parameters, because I thought that maybe the problem was $_POST["username"]; $_POST["password"];</p> <p>But not. I hardcoded the data in the server so... the problem is in Angular JS</p> <p>Can you help me to solve my problem? Thanks!</p>
<p>The server to which the POST request is sent needs to include the <strong>Access-Control-Allow-Headers in its response</strong>.Putting them into you client has no effect.</p> <p>It is up to the server to specify if it accepts the cross origin requests so the client cannot decide for itself if it permits the CORS.</p> <p>Here explained in this <a href="http://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr">thread</a> </p>
Invalid procedure call or argument in excel vba <p>I am using a filter on column1 of sheet1 with a unique no, get filtered values from column Z into an array (arr) object and paste those values as a string in one cell in "Dashboard" sheet. Repeat this process for all unique values on column 1 of sheet1. I am getting multiple errors 1. "Invalid Procedure call or argument" at Join() method. 2. Getting values into rng object and array. Can I get your help on where am I going wrong with this. Many Thanks.</p> <pre><code>Dim d As Object, c As Range, k, tmp As String Dim TestRg As Range Dim arr() As Variant Dim i As Integer Dim myCell As Range Dim rng As Range i = 2 Set d = CreateObject("scripting.dictionary") Columns(1).Select For Each c In Selection tmp = Trim(c.Value) If Len(tmp) &gt; 0 Then d(tmp) = d(tmp) + 1 Next c For Each k In d.Keys If IsNumeric(k) Then Set TestRg = Range("A1:AQ" &amp; LastRow(ActiveSheet)) TestRg.AutoFilter Field:=1, Criteria1:=k, Operator:=xlFilterValues LasRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row Set rng = ActiveSheet.Range("Z1" &amp; ":" &amp; "Z" &amp; LasRow).SpecialCells(xlCellTypeVisible) rng.Activate arr = rng.Value Worksheets("Dashboard").Range("A" &amp; i) = k Worksheets("Dashboard").Range("E" &amp; i).Resize(UBound(arr, 1)).Value = Join(arr, " ") i = i + 1 Erase arr End If Next k </code></pre>
<p>Possible cause of this is the range length that you specified exceeds to the length of data you are calling on your code. </p>
Training loss and validation loss in convolutional auto encoder is not decreasing much <p>Why the training loss and validation loss in convolutional auto encoder is not decreasing. The training data is of dimension <code>10496x1024</code> and <code>CAE</code> is trained with <code>32x32</code> size image patches in <code>keras</code>. I have already tried <code>l2regularization</code> but did not help much. I am trainig for 20 epochs. What could be the other alternatives ?</p> <p>The output :</p> <blockquote> <p>Epoch 1/20 10496/10496 [========] - 52s - loss: 0.4029 - val_loss: 0.3821</p> <p>Epoch 2/20 10496/10496 [========] - 52s - loss: 0.3825 - val_loss: 0.3784</p> <p>Epoch 3/20 10496/10496 [=======] - 52s - loss: 0.3802 - val_loss: 0.3772</p> <p>Epoch 4/20 10496/10496 [=======] - 51s - loss: 0.3789 - val_loss: 0.3757</p> <p>Epoch 5/20 10496/10496 [=======] - 52s - loss: 0.3778 - val_loss: 0.3752</p> <p>Epoch 6/20 10496/10496 [=======] - 51s - loss: 0.3770 - val_loss: 0.3743</p> <p>Epoch 7/20 10496/10496 [=======] - 54s - loss: 0.3763 - val_loss: 0.3744</p> <p>Epoch 8/20 10496/10496 [=======] - 51s - loss: 0.3758 - val_loss: 0.3735</p> <p>Epoch 9/20 10496/10496 [=======] - 51s - loss: 0.3754 - val_loss: 0.3731</p> <p>Epoch 10/20 10496/10496 [=======] - 51s - loss: 0.3748 - val_loss: 0.3739</p> <p>Epoch 11/20 10496/10496 [=======] - 51s - loss: 0.3745 - val_loss: 0.3729</p> <p>Epoch 12/20 10496/10496 [=======] - 54s - loss: 0.3741 - val_loss: 0.3723</p> <p>Epoch 13/20 10496/10496 [=======] - 51s - loss: 0.3736 - val_loss: 0.3718</p> <p>Epoch 14/20 10496/10496 [=======] - 52s - loss: 0.3733 - val_loss: 0.3716</p> <p>Epoch 15/20 10496/10496 [=======] - 52s - loss: 0.3731 - val_loss: 0.3717</p> <p>Epoch 16/20 10496/10496 [=======] - 51s - loss: 0.3728 - val_loss: 0.3712</p> <p>Epoch 17/20 10496/10496 [=======] - 49s - loss: 0.3725 - val_loss: 0.3709</p> <p>Epoch 18/20 10496/10496 [=======] - 36s - loss: 0.3723 - val_loss: 0.3710</p> <p>Epoch 19/20 10496/10496 [=======] - 37s - loss: 0.3721 - val_loss: 0.3708</p> <p>Epoch 20/20 10496/10496 ========] - 37s - loss: 0.3720 - val_loss: 0.3704</p> </blockquote>
<p>Your network is still learning, and is not slowing down so much at epoch 20. You can try a higher learning rate, and more epochs with an early stopping method if you have enough data. This approach can be applied also with regularization methods and k-fold cross validation.</p>
Wordpress PHP variables in get_results() <p>I have a function that works fine when I say</p> <pre><code>$results = $wpdb-&gt;get_results( "SELECT meta_value FROM wp_woocommerce_order_itemmeta WHERE order_item_id = '21' AND meta_key = '_qty" ); </code></pre> <p>This function returns 4, which is the correct number I would be looking for in my database. </p> <p>Unfortunately, this code is returning an empty array to get_results(). There is something wrong in my code with passing a variable to $wpdb, does anyone have an idea?</p> <pre><code>$results = $wpdb-&gt;get_results( "SELECT meta_value FROM wp_woocommerce_order_itemmeta WHERE order_item_id =" .$order_item_id. "AND meta_key = '_qty'" ); </code></pre>
<p>In this specific case I think it is a simple issue of missing white-space in your string concatenation. However there may be a more suitable way to prepare your statement that would have prevented this by making it easier to spot, and follows other good query building practices</p> <p><strong>Wordpress Prepared Statments</strong><br> By using <code>$wpdb-&gt;prepare()</code> you can use (most of) the <code>sprintf ()</code> syntax to help you build your query. </p> <pre><code>$query = $wpdb-&gt;prepare("SELECT meta_value FROM wp_woocommerce_order_itemmeta WHERE order_item_id = %d AND meta_key = '_qty'", $order_item_id); $results = $wpdb-&gt;get_results($query); </code></pre> <p>More info available at the <a href="https://developer.wordpress.org/reference/classes/wpdb/prepare/" rel="nofollow">wordpress codex</a> and on <a href="http://php.net/manual/en/mysqli.quickstart.prepared-statements.php" rel="nofollow">prepared statements in general</a></p>
storing a game score <p>I have this code in my playGame() which I call from <code>main</code>. The code below increments when either player, X / O, either wins or ties, but when I play my full game a second time, I loose my previous score.</p> <p>Can someone suggest a more efficient way to store the scores? </p> <p>Desired result: when game is played again, previous score should be kept and incremented if same player with a previous score wins or both ties.</p> <p>retain previous score, increment if req, --- </p> <pre><code> //score start at zero. int Xwins = 0; int Owins = 0; int tie = 0; if(wins == 'X') { Xwins++; //increments Xwins if player X wins } else if(wins == 'O') { Owins++; //increments Owins if player O wins } else if(NOWIN) { tie++; //increments tie if no player wins } </code></pre> <p>result when Xwins</p> <h2>X | O | tie</h2> <p>1 | 0 | 0</p> <p>play again; result when Xwins again --- should be 2 not 1 ---- my issue</p> <h2>X | O | tie</h2> <p>1 | 0 | 0</p>
<p>Probably you should store the score value to temporary variable. Then after a new score, you should sum it up on the last score on your temporary variable.</p>
How to solve for the mean in an array without the max and min? <pre><code>public class FunWithArrays { public static void main(String[] args) { int[] myFunArray = {7, 10, 3, 0, 615, -1000}; int i; //minimum int min; min = myFunArray[0]; for (i=0; i &lt; myFunArray. length; i++) { if (myFunArray[i] &lt; min) { min = myFunArray[i]; } } //maximum int max; max= myFunArray[0]; for (i=1; i &lt; myFunArray. length; i++) { if (myFunArray[i] &gt; max) { max = myFunArray[i]; } } System.out.println("minimum = " + min + " maximum = " + max); //mean without outliers double noOutliersMean = 0; for (i=0; i &lt; myFunArray.length; i++){ noOutliersMean = ((sum - (max + min)) /myFunArray.length ); if ( myFunArray.length &lt; 3){ System.out.println("not enough numbers"); } } System.out.println("Mean without Outliers: " +noOutliersMean); //Array reversed int[] reversed = myFunArray; for(int i1 = reversed.length - 1; i1 &gt;= 0 ; i1--) { System.out.println( "Reversed " + reversed[i1]); } } } </code></pre> <p>For the mean without the outliers (max and min) the answer should be 5 my line of code gives me 1.333. What am i doing wrong?</p> <p>2nd question regarding the array reversed, when printed out it gives me the right answer but each number on a separate line. How do i get it to be on 1 line in the format of ; reversed: [-1000,615,0,3,10,7]</p>
<p>the answer to your second question is don't print using </p> <pre><code>println </code></pre> <p>, just use <code>print</code></p> <p>The code should be:</p> <pre><code>System.our.print("Reversed: [") for(int i1 = reversed.length - 1; i1 &gt;= 0 ; i1--) { System.out.print(reversed[i1]); if(i1&gt;0){ System.our.print(","); } } System.out.print("]"); </code></pre> <p>To answer your first question you need to provide the following:</p> <p>How you are calculating sum, max and min. Even though you have mentioned without max and min.. you still are using it in your code</p>
Get HTML tag name from React element? <p>Is it possible to get an HTML tag name from a React element (return from a component)? For example:</p> <pre><code>function Foo() { return &lt;span&gt;Hello&lt;/span&gt;; } </code></pre> <p>The HTML tag name would be <code>span</code>. I know you can look into the <code>type</code> property of the React element, but it gets really difficult between SFC and normal components, and even harder when the component depth is rather large. For example:</p> <pre><code>function Bar() { return &lt;Foo /&gt;; } </code></pre> <p>Should still return <code>span</code>.</p>
<p>No.</p> <p>React Elements are a virtual construct, and they don't directly represent DOM elements. There are two types of React Elements - "regular" HTML DOM elements, and instantiations of a React Class. The first one has a "type" because it is extremely simple, stateless, and immutable, and is created only to render its corresponding DOM element (but don't confuse it with the DOM element itself!) An example of this would be <code>&lt;div&gt;Foo&lt;/div&gt;</code> in JSX or <code>React.createElement("div", null, "Foo")</code> in JS.</p> <p>However instantiations of a React Class don't have a "type" because they don't represent a typical DOM element. When we instantiate a React Class we call it a "Component" to identify it as a single instance of the Class, having a <code>render</code> method, encapsulated state, etc. It's impossible to retrieve the "type" of a Component because the actual DOM elements that it will render are completely dependent on its internal state and what the <code>render</code> method decides to return. An example of this would be a React Class defined somewhere and then instantiated with <code>&lt;Foo /&gt;</code> or <code>React.createElement(Foo)</code>.</p> <p>The only way to know what DOM elements a Component is actually rendering is to, well, mount and render it and see what it does. There is no "type" inherent to the component itself. You could conceivably mount a Component, use <code>ref</code> to capture the DOM element as it's rendered, and then use a callback function to pass this information back to parent(s).</p> <pre><code>var Child = React.createClass({ render: function() { return &lt;div ref={function(el){this.props.whatElementAmI(el)}.bind(this)} &gt;Oh My!&lt;/div&gt; } }); var Parent = React.createClass({ whatElementAmI: function(el) { console.log(el.nodeName); // "DIV" }, render: function() { return &lt;div&gt;&lt;Child whatElementAmI={this.whatElementAmI.bind(this)} /&gt;&lt;/div&gt; } }); </code></pre> <p><a href="https://facebook.github.io/react/docs/glossary.html#react-elements" rel="nofollow">https://facebook.github.io/react/docs/glossary.html#react-elements</a></p>
I added an area called home, moved my controller and view to it and now I can't connect to the index view <p>I already have controllers and views in folders under the project name. I added an Area folder and then an area inside it and called it Home and then moved my controller and index view into it. But when I connect to the index I get an error and it looks like the path where it's looking for the index is the old path, how do I change this to the new path?</p> <p>Here is what I created</p> <p><a href="https://i.stack.imgur.com/i5Z0j.png" rel="nofollow"><img src="https://i.stack.imgur.com/i5Z0j.png" alt="enter image description here"></a></p> <p>In 'HomeAreaRegistration' I see this under RegstrationArea</p> <pre><code>public class HomeAreaRegistration : AreaRegistration { public override string AreaName { get { return "Home"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Home_default", "Home/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } </code></pre> <p>But when I run the application in IE, here is what I see in the browser! It looks like it's looking for the index.cshtml in the old path location, not the new path location in the new area 'Home'</p> <p><a href="https://i.stack.imgur.com/uyGa7.png" rel="nofollow"><img src="https://i.stack.imgur.com/uyGa7.png" alt="enter image description here"></a></p> <p>It looks like the route engine is looking in the wrong location. So here is what my RouteConfig.cs file looks like.</p> <pre><code>routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); </code></pre> <p>Even when I try '<a href="https://localhost:44301/Home/Index.cshtml" rel="nofollow">https://localhost:44301/Home/Index.cshtml</a>' it throws a HTTP 404 error.</p>
<p>The 404 error shows the main problem itself: default routing and view engine search cannot found default <code>Index.cshtml</code> view file in <code>Views</code> directory on your project (i.e. <code>ProjectName/Views/Index.cshtml</code> pointed by route <code>~/Views/Home/Index</code>).</p> <p>First, create a class to include view location search for your custom area like this example:</p> <pre><code>public class CustomView : RazorViewEngine { public CustomView() { MasterLocationFormats: new[] { "~/Areas/Home/Views/{0}.cshtml", "~/Areas/Home/Views/{1}/{0}.cshtml" } ViewLocationFormats: new[] { "~/Areas/Home/Views/{0}.cshtml", "~/Areas/Home/Views/{1}/{0}.cshtml" } PartialViewLocationFormats = ViewLocationFormats; FileExtensions = new[] { "cshtml" }; } } </code></pre> <p>Then, include all areas and your custom view engine into <code>Global.asax</code>:</p> <pre><code>protected void Application_Start() { // register all area locations AreaRegistration.RegisterAllAreas(); // clear default view engine ViewEngines.Engines.Clear(); // add your custom view engine here // the custom view engine should loaded before default view engine (e.g. Razor) ViewEngines.Engines.Add(new CustomView()); ViewEngines.Engines.Add(new RazorViewEngine()); } </code></pre> <p>If you have <code>RouteConfig</code> class on <code>App_Start</code> directory, make sure <code>RegisterAllAreas</code> has included before default route:</p> <pre><code>public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); AreaRegistration.RegisterAllAreas(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } </code></pre> <p>Additionally, add namespace of the controller name when required or the above solution still doesn't work:</p> <pre><code>public class HomeAreaRegistration : AreaRegistration { public override string AreaName { get { return "Home"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Home_default", "Home/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "ProjectName.Areas.Home.Controllers" } ); } } </code></pre> <p>NB: Create <code>Home</code> directory under <code>Views</code> if you want to follow route convension <code>~/Areas/Views/Home/Index</code>, and put <code>Index.cshtml</code> file into it.</p> <p>References:</p> <p><a href="http://stackoverflow.com/questions/2140208/how-to-set-a-default-route-to-an-area-in-mvc">How to set a Default Route (To an Area) in MVC</a></p> <p><a href="http://stackoverflow.com/questions/13454699/how-to-register-areas-for-routing">How to register areas for routing</a></p>
Unit Testing Java Script - Fake XRM with QUnit <p>I have a <code>js</code> function which I want to unit test using <code>QUnit</code>. It is a simple function where I pass the field name that I want to hide from the form. I am also using a Mocking framework from here: [link] <a href="https://github.com/ambek/XrmPage-Mock" rel="nofollow">https://github.com/ambek/XrmPage-Mock</a> </p> <pre><code>function HideField(field) { Xrm.Page.getControl(field).setVisible(false); }; </code></pre> <p>My Tests.js file looks like this: </p> <pre><code>var Xrm; QUnit.test("Testing Hide Field Function", function (assert) { var PageControls = new Array(); PageControls.push(CreateSimpleControlWithAttribute("NewField", "M", "Type of Residence")); var page = new XrmPageMock("{607C16D1-7C53-4023-B20B-13E4F1C6A9D3}", PageControls, 1); Xrm = new XrmPageMock(page); HideField('NewField'); assert.equal(XRM.page.getControl('NewField').getVisible(),false, 'Passsed'); }); </code></pre> <p>On executing my tests, I get this error: </p> <blockquote> <p>Unable to get property 'getControl' of undefined or null reference</p> </blockquote> <p>Does anyone know why my mocking/faking is going wrong? </p>
<p>It was just a typo in the following statement: </p> <p><code>assert.equal(XRM.page.getControl('NewField').getVisible(),false, 'Passsed');</code></p> <p>The new statement is (Correction on the word "page")</p> <p><code>assert.equal(XRM.Page.getControl('NewField').getVisible(),false, 'Passsed');</code></p>
The app crashes due to this reason <blockquote> <p>Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array</p> </blockquote>
<p>You are accessing Empty array about to access object at index.</p> <p>replace all places like in your code below:</p> <pre><code>[arrMydata objectAtIndex:indexPath.row]; </code></pre> <p>with</p> <pre><code>//1. Positive index ([anArray objectAtIndex:-NUMBERS]) will crash //2. within the array boundary if([arrMydata count] &gt; 0 &amp;&amp; [arrMydata count] &gt; indexPath.row){ shrObj=[arrMydata objectAtIndex:indexPath.row]; } else { //Array is empty,handle as you needed } </code></pre> <p>A good example for reference can be found <a href="http://stackoverflow.com/questions/24407146/terminating-app-due-to-uncaught-exception-nsrangeexception-reason-n/24407937#24407937">here</a></p>
How can I get the line-number of an error in a dynamically added <script> tag? <p>When dynamically creating a script element and adding it to the page, my errors are not giving me line numbers of the script, but instead the line number where I append the script. </p> <p>The code below when in a .js file will give you a line number error of whichever line <code>document.appendChild(script)</code> is on. The code snippet, if ran, will return the correct line number. How do they do this?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var script = document.createElement("script"); script.innerHTML = "\n\n\n\n\n\n\nfoo.bar"; //error should be on line 8 document.head.appendChild(script)</code></pre> </div> </div> </p>
<p>Got it. Adding a try catch around the code works great </p> <pre><code>catchableScript = function(scriptText) { var scriptText = "try {\n"+scriptText+"\n} \n catch(ex){console.log(ex.lineNumber-1)}"; var script = document.createElement("script"); script.innerHTML = scriptText; document.head.appendChild(script) } catchableScript("\n\n\n\n\n\n\nfoo.bar"); </code></pre> <p>Output: <code>8</code></p> <p>Also, the exception has more information which is useful, but this is the answer to the question.</p> <p>EDIT:</p> <p>For those who want it, adding this code:</p> <pre><code>window.CURRENTLY_EVALED_SCRIPT = scriptText; var scriptText = "try {\n"+scriptText +"\n} catch(ex){\n" +"var lineNumber = ex.lineNumber-1;\n" +"var errorOut = {};\n" +"errorOut.exception = ex;\n" +"errorOut.lines = window.CURRENTLY_EVALED_SCRIPT.split('\\n');\n" +"var line = errorOut.lines[lineNumber-1];\n" +"console.log(ex.message+' on line\\n'+line+' :: '+lineNumber, window.CURRENTLY_EVALED_SCRIPT_ELEMENT, errorOut);\n" +"}"; ... window.CURRENTLY_EVALED_SCRIPT_ELEMENT = script </code></pre> <p>Will result in this output in console:</p> <pre><code>foo is not defined on line foo.bar :: 8, &lt;script&gt;, Object { exception: ReferenceError, lines: Array[8] } </code></pre> <p>And you can click <code>&lt;script&gt;</code> to go to appended element, or <code>lines</code> to just see an array of all the lines.</p> <p>Works like a charm.</p>
Error reading table into R <p>I am trying to read this <a href="https://d396qusza40orc.cloudfront.net/eureconometrics-assets/Dataset%20Files%20for%20On-Demand%20Course/Exercises%20and%20datasets/Module%203/TrainExer%203-1-corrected.txt" rel="nofollow">file</a> into an R dataframe but keep getting errors.</p> <p>This is the command I am using</p> <pre><code>data &lt;- read.csv("TrainExer 3-1-corrected.txt", sep='\t', colClasses = "numeric") </code></pre> <p>I get the following error</p> <blockquote> <p>Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : scan() expected 'a real', got '1229.2316.200'</p> </blockquote> <p>If I don't specify <code>colClasses</code>, I don't get any error, but the table merges some entries from different columns. For example, 1229.23 is one entry in one column and 16.200 is another entry in the adjacent column. Somehow R is trying to read them as one.</p>
<p>You probably should be using <code>read.table</code> instead, since you're not loading in a csv. This might work: <code>data &lt;- read.table("TrainExer 3-1-corrected.txt", header = TRUE)</code></p>
Python SQLite TypeError <pre><code>from sqlite3 import * def insert_record(Who, Invented): connection = connect(database = "activity.db") internet = connection.cursor() list = "INSERT INTO Information VALUES((Alexander_Graham, Phone))" internet.execute(list) rows_inserted = internet.rowcount connection.commit() internet.close() connection.close() #GUI interface from Tkinter import * window = Tk() the_button3 = Button(window, text='Record', command = insert_record).grid(row=1, sticky=W, padx=100,pady=5) window.mainloop() </code></pre> <p>Alright, so what I'm trying to do is when I press the Record button, the values for Information (it have 2 fields called Who and Invented, respectively) in activity.db will add a record Alexander_Graham and Phone.</p> <p>*activity.db is already premade in the same folder as the code</p> <p>But instead I get this error: TypeError: insert_record() takes exactly 2 arguments (0 given)</p> <p>How do I fix it? </p>
<p>insert record is a function that takes two required arguments, which you didn't pass values in for.</p> <pre><code>command = insert_record </code></pre> <p>A good example of this in action is the following test sequence:</p> <pre><code>In [1]: def func(one,two): ...: return one+two ...: In [2]: func() ------------------------------------------------------------------------- -- TypeError Traceback (most recent call last) &lt;ipython-input-2-08a2da4138f6&gt; in &lt;module&gt;() ----&gt; 1 func() TypeError: func() takes exactly 2 arguments (0 given) In [3]: func(1,3) Out[3]: 4 </code></pre> <p>In this function, it fails in the same was as your tk app. You need to provide a function that has default values, or handle it a different way.</p>
mysqli_select_db() expects parameter 1 to be mysqli, string given & mysqli_error() expects exactly 1 parameter, 0 given in DATABASE_CONNECT_ERROR <p>Ive searched on here and various other places and I just cannot find the answer to solve this problem. I just bought new hosting and am trying to move my sites. I am getting the error below.</p> <pre><code>Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given in /home4/purefic/public_html/demo/mytcg/settings.php on line 230 Warning: mysqli_error() expects exactly 1 parameter, 0 given in /home4/purefic/public_html/demo/mytcg/settings.php on line 231 DATABASE_CONNECT_ERROR </code></pre> <p>And this is the coding I have on my settings page (originally working just fine on my old host I had everything as mysql and not mysqli like my research seemed to tell me to change to but as you can see it didnt work)</p> <pre><code>$users = array($user =&gt; md5($pass)); $salt = substr(md5(date("F")), 8); $connect = mysqli_connect("$db_server", "$db_user", "$db_password") or die( DATABASE_CONNECT_ERROR . mysqli_error() ); mysqli_select_db("$db_database" , $connect) or die( DATABASE_CONNECT_ERROR . mysqli_error() ); function CleanUp($data) { $data = trim(htmlentities(strip_tags($data))); return $data; } function escape_sql($sql) { if (get_magic_quotes_gpc()) $sql = stripslashes($sql); return mysqli_real_escape_string($sql); } ?&gt; </code></pre>
<p>First you no need to have "" for your DB connection as you pass it as variable and second is In MYSQLI always Pass <code>$connection</code> First.</p> <p>And for a mysqli_error pass $connection to let server know you are looking for error in Database Connection.</p> <p>Try this.</p> <pre><code>$connect = mysqli_connect($db_server, $db_user, $db_password) or die( DATABASE_CONNECT_ERROR . mysqli_error($connect) ); mysqli_select_db($connect, $db_database) or die( DATABASE_CONNECT_ERROR . mysqli_error($connect) ); </code></pre> <p><strong>Edit</strong></p> <p>either way you can try connect your DB As follow</p> <pre><code>$connect = mysqli_connect($db_server, $db_user, $db_password, $db_database); // If no connection than Print error if (mysqli_connect_errno()) { echo "No Active DB Connection Please check: " . mysqli_connect_error(); } </code></pre>
How to find the running time of these two functions? <p>I'm familiar with the big O notation and the running time and most of the time I can recognize the running time of an algorithm but I'm not sure with this one. I'm dealing with a tree here.</p> <p><strong>First method:</strong></p> <pre><code>static boolean containsData(TreeNode treeRoot, String data) { if(treeRoot == null) return false; if(data.equals(treeRoot.data)) return (true); else if((data.compareTo(treeRoot.data))&lt;0) return(containsData(treeRoot.left, data)); else return(containsData(treeRoot.right, data)); } </code></pre> <p><strong>Second method:</strong></p> <pre><code>static boolean containsData2(TreeNode treeRoot,String data){ if (treeRoot != null) { if (treeRoot.data.contains(data)) { return true; } else { return containsData2(treeRoot.left,data) || containsData2(treeRoot.right,data); } } return false; } </code></pre> <p>I would say that both methods are <strong>O(n)</strong> I can not see how one of them would be <strong>O(log(n))</strong>.</p>
<p>Both methods have a worst case running time of O(n) if the tree is not balanced.</p> <p>The first would run in O(log n) if the tree is balanced.</p> <p>The second method would still need O(n) even for balanced tree since it traverses both subtrees if the record is found in the right half. It actually does a full scan of all records in sorting order until the record is found. The actual run time depends on the size of the record. A small record will be found faster, a large record will need O(n). The average is O(n).</p>
Saving/Serializing OkHttp/Retrofit Requests <p>I want to be able to recover from crash/closing the app or just device being disconnected.</p> <p>Currently when I detect that the network is out for my Android device I save the Call created with RetroFit2 in a stack (to process later). If the user were to close the app or restart the device I lose the possibility to save these calls anywhere...</p> <p>My question is the following, how can I save a RetroFit Call or an OkHttp3 Request? None of them is serializable or nor can I convert them to strings from what I could see looking at the code.</p>
<p>Use <a href="https://github.com/yigit/android-priority-jobqueue" rel="nofollow">android priority jobqueue</a> by Yigit Boyar (one of the google android guys). It'll serailize your jobs, detect network changes (and respond accordingly) and persist even through device reboots (let alone app crashes). Plus a ton of other features. Just take a look. It is not exactly what you requested but it's a better solution. It's Magic.</p> <blockquote> <p>Starting with v2, Job Queue can be integrated with JobScheduler or GCMNetworkManager. This integration allows Job Queue to wake up the aplication based on the criterias of the Jobs it has. You can see the deatails on the related wiki page. The Scheduler API is flexible such that you can implement a custom version of it if your target market does not have Google Play Services.</p> </blockquote> <p>Try it and you'll be glad you did, as I've been. It filled the huge gap in my code that I spent weeks hacking together with spit, ducktape and faith.</p>
Ruby trying to store array elements when reiterating through functions <p>I am attempting to make a tic tac toe game. I have a good idea of where to go, and I know what the problem is, but I am not sure how to fix it. When I create a function, I establish variables for that function. i = 0, row1 = [], but when I am reiterating through the functions, every time the function gets called again, row1 is back to empty because of the initial row1 = [], and the counter I want to use, i = 0, goes back to 0 every time because the beginning of the function I am setting my variables. I think the solution may be to make the variable global, and set it out of the function, but I am not sure how to do that. But if anyone has any suggestions it would be greatly appreciated. Here is the problem code.</p> <pre><code>def row1(player) row1 = [] row1[player - 1] = "X" puts "#{row1}" end def choosespot_x puts "X -- Choose a spot" move = gets.chomp.to_i if move &lt;= 3 row1(move) end choosespot_x end </code></pre>
<p>Global variables are prefixed by <code>$</code> and are generally a bad idea in Ruby.</p> <p>Instance variables, prefixed by <code>@</code>, can also do what you want; on top-level, they behave pretty much the same as globals, but in classes or modules they are nicely isolated.</p> <p>So the best way would be to make a class; create your variable (say, <code>@row1</code>) in the <code>initialize</code> method, and then you will be able to just use it in <code>choosespot_x</code> method.</p>
printout sequence in python2.7 <pre><code>def foo(num,base): if(num&gt;= base): foo(num/base,base) print num%base,num numA =126 numB = 2 foo(numA,numB) </code></pre> <p>In my mind,<a href="https://i.stack.imgur.com/RFIXw.jpg" rel="nofollow">enter image description here</a>results should be same as picture 1. However, when I run the code, it comes out<a href="https://i.stack.imgur.com/GgLu0.jpg" rel="nofollow">enter image description here</a>. First line is 1,1. why? the condition fulfill the loop, and it should print 1,63 in the first line and 1,31 in the second line.Meanwhile, why 0, 126 prints at last?</p>
<p>i think what you intended was something like below, 1st iteration will taking input 126, subsequence will be num/base</p> <pre><code>def foo(num,base): print num%base,num if(num&gt;= base): foo(num/base,base) </code></pre>
Getting error while Convert string to json object <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var result = ""; result += "["; for(i=0;i&lt;=10;i++) { result += "{ 'key': 'keyvalue" + i + "', 'values': ["; for(j=0;j&lt;=10;j++) { result += "{ 'key': 'subkeyvalue"+j+"', 'value':"+j+"}, "; } result += "]}, "; } result += "]"; console.log(result); console.log(JSON.stringify(result)); console.log(JSON.parse(result));</code></pre> </div> </div> </p> <p>If i try to convert String to JSON.parse. I am getting below error.</p> <p>JSON.parse: expected property name or '}' at line 1 column 4 of the JSON data</p> <p>can you please any one resolve this problem.</p>
<p>In this snippet <code>( result += "]}, ";) , ","</code> (comma) is getting appended at the last, so the json will be like <code>"},]"</code> where you will be expecting like <code>"}]"</code></p>
CSS slide in from left animation <p>I'm working on a slideshow and it works, except for the animations. The animation for sliding out works fine but the animation for sliding in from the left does not. The left margin gets set to 0% but there is no animation, even though it is set to -100% at first.</p> <p>Javascript:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var images = [ 'http://i.imgur.com/ByyUANz.png', 'http://i.imgur.com/S5FfOOB.png', 'http://i.imgur.com/EuefPdv.png', 'http://i.imgur.com/Ucvm4pJ.png', 'http://i.imgur.com/pK5WBHN.png', 'http://i.imgur.com/nuOLVpy.png' ] function slideShow(startAt){ var holder = document.getElementById("currentImage"); var img = document.createElement("img"); img.src = images[startAt]; holder.appendChild(img); nextPicture(startAt, img); } function nextPicture(current, currentElement){ var holder = document.getElementById("currentImage"); setTimeout(function(){ currentElement.className = "translateLeft"; current += 1; var img = document.createElement("img"); img.src = images[current]; img.style.marginLeft = "-100%"; holder.appendChild(img); img.className = "translateIn"; if (current == 5){ current = -1; nextPicture(current, img); } else { nextPicture(current, img); } }, 5000) } slideShow(0);</code></pre> </div> </div> </p> <p>CSS:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.translateLeft { transition: 3s; margin-left: 100% !important; } .translateIn { transition: 3s; margin-left: 0% !important; }</code></pre> </div> </div> </p>
<p>To create a nice slideshow I suggest to use css <code>transform</code> property rather than the <code>margin</code>. The idea is to create the placeholder element <code>currentImage</code> with <code>relative</code> position, and then create all images inside it with position set to <code>absolute</code>. Then by default all images are translated out of the placeholder element, and adding/removing classes <code>show</code> and <code>hide</code> you can place them inside the view and then outside of it, like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var images = [ 'http://i.imgur.com/ByyUANz.png', 'http://i.imgur.com/S5FfOOB.png', 'http://i.imgur.com/EuefPdv.png', 'http://i.imgur.com/Ucvm4pJ.png', 'http://i.imgur.com/pK5WBHN.png', 'http://i.imgur.com/nuOLVpy.png' ]; // Get the holder var holder = document.getElementById("currentImage"); // Create the images images.forEach(function(url) { var img = document.createElement("img"); img.src = url; holder.appendChild(img); }); // Image counter var counter = 0; // Slide show interval var slideshow = setInterval(function() { // When we reach the end of images we shut down the slide show // or you can reset the counter to start over if(counter === images.length) { clearInterval(slideshow); return; } // Get all images var nodes = holder.getElementsByTagName("img"); // Hide previous image if(nodes[counter - 1]) { nodes[counter - 1].className = "hide"; } // Show next image nodes[counter].className = "show"; counter++; }, 2500);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#currentImage { background: gray; width: 300px; height: 300px; margin: 0 auto; position: relative; overflow: hidden; } #currentImage img { width: 100%; position: absolute; transform: translateX(-110%); -webkit-transition: -webkit-transform 1.0s ease 0s; -moz-transition: -moz-transform 1.0s ease 0s; -o-transition: -o-transform 1.0s ease 0s; transition: transform 1.0s ease 0s; } #currentImage img.show { transform: translateX(0%); } #currentImage img.hide { transform: translateX(110%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="currentImage"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
View from a Join of two tables in SQL Server <p><a href="https://i.stack.imgur.com/0QsgA.jpg" rel="nofollow">Tables to Join</a></p> <p>I attached an image explaining issues that I currently face at the moment. I was looking for a way to join two tables. Where first table has a relationship to the previous table that its foreign key in first table. The second table also have foreign key of the first table. </p> <p>What I want is to output the information is a list of the records of the second table that has the foreign key of the first table as well as the foreign key of the previous table that only linked to first table only.</p> <p>Thank you very much for your support and I am looking forward to hear from you all soon</p>
<p>If you are using SQL Server, try creating a view function. You can easily add tables and view the sql results after you connect all of them. It also has a built in function that will automatically creates the sql queries corresponding to your created view function.</p>
nixOS: how to recover from collision between two instances of same package, same version <p>Here is my <code>nixos</code> version:</p> <pre><code>$ nixos-version 16.09pre85931.125ffff (Flounder) </code></pre> <p>Here is my shell script:</p> <pre><code>$ cat test.nix { nixpkgs ? import &lt;nixpkgs&gt; { }, compiler ? "ghc801" }: let inherit (nixpkgs) pkgs; ghc = pkgs.haskell.packages.${compiler}.ghcWithPackages (ps: with ps; [ diagrams diagrams-pgf ]); in pkgs.stdenv.mkDerivation { name = "test"; buildInputs = with pkgs; [ ghc ]; shellHook = '' eval $(egrep ^export ${ghc}/bin/ghc) ''; } </code></pre> <p>Here is the problem. Note that there is a collision between two instances of the same version of the same package:</p> <pre><code>$ nix-shell --pure test.nix these derivations will be built: /nix/store/r6080kvlvdb16c1frz8alnm14xjizkf5-ghc-8.0.1.drv building path(s) ‘/nix/store/1129nds6xhq6hqawdd2s9z9n6va57jgl-ghc-8.0.1’ collision between `/nix/store/amdnmbd8p52d49bqmphv9f7ly7lf7pkk-active-0.2.0.10/share/doc/x86_64-linux-ghc-8.0.1/active-0.2.0.10/html/Data-Active.html' and `/nix/store/yniw6akz2ldimdlj9yq968ldaf4j18h1-active-0.2.0.10/share/doc/x86_64-linux-ghc-8.0.1/active-0.2.0.10/html/Data-Active.html' builder for ‘/nix/store/r6080kvlvdb16c1frz8alnm14xjizkf5-ghc-8.0.1.drv’ failed with exit code 255 error: build of ‘/nix/store/r6080kvlvdb16c1frz8alnm14xjizkf5-ghc-8.0.1.drv’ failed /run/current-system/sw/bin/nix-shell: failed to build all dependencies </code></pre> <p>I know that if the packages had different versions then I could do something like this:</p> <pre><code>$ nix-env --set-flag priority 15 &lt;package&gt;-&lt;version&gt; </code></pre> <p>But since the package names and versions are the same, I don't know what to do.</p> <p>How can I recover from this?</p>
<p><code>ghcWithPackages</code> effectively creates a brand new distribution of GHC, customised to include the packages you've listed. That is a different thing from <code>pkgs.ghc</code>, not just a thing that depends on it; it doesn't make sense to install both into the same environment. I think you've accidentally referred to both, and that's what's causing the collision.</p> <p>First you make your personal GHC and bring it into scope as the name <code>ghc</code>, using <code>let</code>.</p> <p>Inside the scope of the <code>let</code> you say:</p> <pre><code>buildInputs = with pkgs; [ ghc ]; </code></pre> <p>The <code>with</code> brings every attribute of <code>pkgs</code> into scope for the following expression. <code>pkgs</code> has a <code>ghc</code> attribute, and the <code>with</code> scope is the innermost scope containing a <code>ghc</code> binding, so that takes precedence over the <code>ghc</code> from the <code>let</code>.</p> <p>Your <code>shellHook</code> on the other hand is outside the scope of the <code>with</code>. So the <code>${ghc}</code> is a reference to your let-bound <code>ghc</code>. This makes your derivation depend on that, too.</p> <p>If that's correct, the solution would be either:</p> <ol> <li>Remove the <code>with</code>, so the build inputs list sees the same <code>ghc</code> as the rest of your code (using qualified references for anything else from <code>pkgs</code> you haven't included here)</li> <li>Move the <code>with</code> outside the <code>let</code>, so your version of <code>ghc</code> is the innermost binding (but then you pollute the namespace of your whole file with everything from <code>pkgs</code>, which gets confusing when it gets more complicated)</li> <li>In your <code>let</code> use a different variable name (<code>myghc</code> or something) and refer to that everywhere</li> </ol>
AutoValue not finding generated constructor in Android project <p>I am struggling to get <a href="https://github.com/google/auto/tree/master/value" rel="nofollow">AutoValue</a> working in an Android project. It seems to be working for others, so I must just be missing something. I've tried enabling the jack compiler, that didn't seem to help.</p> <p><a href="https://github.com/srsudar/GithubHotness" rel="nofollow">Here</a> is a demo project that fails when I build it locally. The complaint is in <a href="https://github.com/srsudar/GithubHotness/blob/master/app/src/main/java/org/cse390/githubhotness/models/Repo.java#L21" rel="nofollow">this class</a>, where it can't find the <code>AutoValue_Repo</code> constructor.</p> <p>Here is my project level <code>build.gradle</code>:</p> <pre><code>buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.1' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } </code></pre> <p>And there is my module level <code>build.gradle</code>:</p> <pre><code>apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' android { compileSdkVersion 24 buildToolsVersion "24.0.2" defaultConfig { applicationId "org.cse390.githubhotness" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) provided 'com.google.auto.value:auto-value:1.2-rc1' compile "com.google.auto.value:auto-value:1.2-rc1" apt "com.google.auto.value:auto-value:1.2-rc1" compile 'com.jakewharton:butterknife:8.4.0' apt 'com.jakewharton:butterknife-compiler:8.4.0' compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:design:24.2.1' testCompile 'junit:junit:4.12' } </code></pre> <p>Here is the class that isn't being auto-valued:</p> <pre><code>@AutoValue public abstract class Repo { public abstract int id(); public abstract String name(); public abstract String fullName(); public abstract String description(); public abstract int numStars(); public abstract String language(); public abstract String htmlUrl(); static Repo create(int id, String name, String fullName, String description, int numStars, String language, String htmlUrl) { // See "How do I...?" below for nested classes. return new AutoValue_Repo(id, name, fullName, description, numStars, language, htmlUrl); } } </code></pre> <p>Any obvious mistakes here?</p>
<p>Because we are generating a class here access to the method needs to be public so autovalue can work.</p> <pre><code> public static Repo create(int id, String name, String fullName, String description, int numStars, String language, String htmlUrl) { // See "How do I...?" below for nested classes. return new AutoValue_Repo(id, name, fullName, description, numStars, language, htmlUrl); } </code></pre>
Video gallery in GridView <p>I want to make Video Gallery in Grid View in Xamarin Android. When I click on any video, it should play on same page.</p> <p>I have googled a lot but I could not find any example there.</p>
<p>You can use a <code>RecyclerView</code> to display videos and use a custom video player to play videos.</p> <p>Please refer this post <a href="http://stackoverflow.com/a/31902683/85606">http://stackoverflow.com/a/31902683/85606</a>, the code is in Java but you can port it to C#</p>
SQL Server : find Instance of values that deviate <p>Scenario: I have bills on various accounts, stored in a SQL Server database, over a series of months.</p> <p>i.e.</p> <pre><code>AccountNum BillNum BillMonth BillTotal --------------------------------------------------- 123456 123456-1 201601 $100000.00 123456 123456-2 201602 $100000.00 123456 123456-3 201603 $100000.00 123456 123456-4 201604 $130000.00 456789 456789-1 201601 $250000.00 456789 456789-2 201602 $250000.00 456789 456789-3 201603 $250000.00 456789 456789-4 201604 $200000.00 </code></pre> <p>I am trying to write a query that will show outliers/deviations that differ by > xx% for a given time period. So in the above dataset, row 4 and 8 differ substantially from what I would consider the "normal" amount of $100,000 p/month, potentially indicating an issue.</p> <p>I need a way to average the bills by account (as each account has a different bill/charges etc) and find where the deviation is more than say 10% for a given month. </p> <p>I have tried using STDEV but can't quite work it out.</p>
<p>You can try using the following query:</p> <pre><code>SELECT AccountNum, BillNum, BillMonth, BillTotal, CASE WHEN ABS(BillTotal - AVG(BillTotal) OVER (PARTITION BY AccountNum)) &gt; STDEV(BillTotal) OVER (PARTITION BY AccountNum) THEN 1 ELSE 0 END AS deviates FROM mytable </code></pre> <p>The above query returns a <code>1</code> for those records having a <code>BillTotal</code> amount that deviates more than the standard deviation from the average value of the field for the specific <code>AccountNum</code>.</p>
Yii2 make an input field appear only in create <p>I would like to make an input field appear only in the 'create' form and not in the 'update' form. How can I achieve this?</p>
<p>You can do that by following way</p> <pre><code>if ($model-&gt;isNewRecord){ echo $form-&gt;field($model, 'password')-&gt;passwordInput(['maxlength' =&gt; true, 'placeholder' =&gt; "Enter password"]); } </code></pre>
Make horizontal line spanning to width of container using pseudo css elment <p>I want to make a a horizontal line spanning to the width of the container in which it is placed. The lined element should look like this:</p> <pre><code>////////////////////////////////////////////////////////////////// </code></pre> <p>Very much like a horizontal rule. I have tried it but 100% width is taken only when I put enough slashes in the content property of pseudo element. Here is my HTML code:</p> <pre><code>&lt;div style='width: 100%;&gt; &lt;p class='horizontal-line'&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Here is my CSS code: </p> <pre><code>.horizontal-line:before { content: '///////////////////////////////////////////////////////////////////////////////////'; margin: 0; padding: 0; color: purple; width: 100%; font-size: 10px; } </code></pre> <p>The result is: </p> <pre><code>/////////////////////////////////////////// </code></pre> <p>But it does not span to 100% width of outer div. In order to do so I have to put more slashes in content property. I know there is some alternate and better way to achieve this.</p> <p>P.S: I am not very good at working with pseudo element and might be doing something wrong. Can anyone point out?</p> <p>Edit: And if I place many slashes in content property then the horizontal line goes to two lines when placed in smaller container. <a href="https://jsfiddle.net/Ln428h6n/" rel="nofollow">Here is fiddle link</a></p>
<p>I think you should try linear-gradient. Please find the below code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.horizontal-line:before { content: ''; margin: 0; padding: 0; color: purple; width: 100%; height: 10px; font-size: 10px; display:block; background: repeating-linear-gradient(135deg,purple,purple .25em,transparent 0,transparent .75em ); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style='width: 100%;'&gt; &lt;p class='horizontal-line'&gt;&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Microsoft Graph .NET SDK: Getting items from mycompany.sharepoint.com/Shared%20Documents <p>Debugging the code, I see the request is like: <a href="https://graph.microsoft.com:443/v1.0/drives/the-shared-docs-id/items/the-root-id/children" rel="nofollow">https://graph.microsoft.com:443/v1.0/drives/the-shared-docs-id/items/the-root-id/children</a></p> <p>I know for sure that <strong>the-shared-docs-id</strong> and <strong>the-root-id</strong> are right. Furthermore, this same request returns the expected results when issued from the <a href="https://graph.microsoft.io/en-us/graph-explorer" rel="nofollow">Graph explorer</a>.</p> <p>However, the .NET SDK returns nothing. No items at all. The same user (me) created the files and folders, and authorized the app to access OneDrive. This user is even the admin of everything.</p>
<p>I was testing with two different apps, one with <strong>Files.ReadWrite</strong> scope only, and other with <strong>Files.ReadWrite.All</strong>.</p> <p>I thought <strong>Files.ReadWrite.All</strong> was needed to access other user's files. It turns out, it is also needed to access the shared folder, even being the same (admin) user who created the shared items (files and folders), and even having full permissions to access them. </p> <p>I think this is weird... but it looks like this is the way it is.</p> <p>Using the app with <strong>Files.ReadWrite.All</strong> scope, I was able to see the items in the shared folder. </p> <p>Using the <strong>Files.ReadWrite</strong> scope, I get an empty list of items.</p>
When value in dropdownlist have ever been selected will not display <p>I have two tables that relate to each other one to one that is Husband and Wife. I've made my value dropdownlist and to get the data from the table Husband. I want when its value had been chosen will not appear on his dropdownlist. Perhaps there are other references or can be helped. For the code can be seen in the image below.</p> <pre><code>&lt;?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\helpers\ArrayHelper; use app\models\Husband; /* @var $this yii\web\View */ /* @var $model app\models\Wife */ /* @var $form yii\widgets\ActiveForm */ ?&gt; &lt;div class="wife-form"&gt; &lt;?php $form = ActiveForm::begin(); ?&gt; &lt;?= $form-&gt;field($model, 'id_husband')-&gt;dropDownList( ArrayHelper::map(Husband::find()-&gt;where('status' =&gt; 0)-&gt;all(), 'id_husband', 'name'), ['prompt' =&gt; 'Pilih'] ) ?&gt; &lt;?= $form-&gt;field($model, 'name')-&gt;textInput(['maxlength' =&gt; true]) ?&gt; &lt;?= $form-&gt;field($model, 'status')-&gt;dropDownList(['0' =&gt; 'Tidak Aktif', '1' =&gt; 'Aktif'], ['prompt'=&gt;'--Pilih--', 'style' =&gt; 'width:380px']) ?&gt; &lt;div class="form-group"&gt; &lt;?= Html::submitButton($model-&gt;isNewRecord ? 'Create' : 'Update', ['class' =&gt; $model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt; &lt;/div&gt; &lt;?php ActiveForm::end(); ?&gt; &lt;/div&gt; </code></pre>
<p>mungkin kau harus memakai javascript ini adalah contoh view saya dan controller</p> <p>view</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php use yii\helpers\Html; use yii\widgets\ActiveForm; use yii\helpers\ArrayHelper; use backend\models\TahunAjaran; use backend\models\Mahasiswa; use backend\models\Matakuliah; /* @var $this yii\web\View */ /* @var $model backend\models\Dhs */ /* @var $form yii\widgets\ActiveForm */ ?&gt; &lt;div class="dhs-form"&gt; &lt;?php $form = ActiveForm::begin(); ?&gt; &lt;?= $form-&gt;field($model, 'id_tahun_ajaran')-&gt;dropDownList(ArrayHelper::map(TahunAjaran::find()-&gt;all(),'id','tahun_ajaran')) ?&gt; &lt;?= $form-&gt;field($model, 'npm_mahasiswa')-&gt;dropDownList(ArrayHelper::map(Mahasiswa::find()-&gt;all(),'id','nama'), ['prompt'=&gt;'Pilih Mahasiswa', 'onchange'=&gt;' $.post("index.php?r=mahasiswa/lists&amp;id='.'"+$(this).val(),function(data) { $("select#dhs-user_id" ).html(data), $("select#nilai-1-nilai" ).html(data); });' ] ); ?&gt; &lt;?= $form-&gt;field($model, 'user_id')-&gt;dropDownList(ArrayHelper::map(Mahasiswa::find()-&gt;all(),'id','user_id'), ['prompt'=&gt;'Pilih User Id', ] ); ?&gt; &lt;?= $form-&gt;field ($model,'semester')-&gt;dropDownList(ArrayHelper::map(Matakuliah::find()-&gt;all(),'id','semester'), ['prompt'=&gt;'Pilih Semester', 'onchange'=&gt;' $.post("index.php?r=matakuliah/lists&amp;id='.'"+$(this).val(),function(data) { $("select#dhs-id_matakuliah").html(data); });' ] ); ?&gt; &lt;?= $form-&gt;field($model, 'id_matakuliah')-&gt;dropDownList(ArrayHelper::map(Matakuliah::find()-&gt;all(),'id','id')) ?&gt; &lt;?= $form-&gt;field($model, 'nilai')-&gt;dropDownList(['A' =&gt; 'A','B'=&gt;'B','C' =&gt; 'C','D'=&gt;'D','E' =&gt; 'E',]) ?&gt; &lt;div class="form-group"&gt; &lt;?= Html::submitButton($model-&gt;isNewRecord ? 'Create' : 'Update', ['class' =&gt; $model-&gt;isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?&gt; &lt;/div&gt; &lt;?php ActiveForm::end(); ?&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>controlller</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> public function actionLists($id){ $countBranches = Mahasiswa::find() -&gt;where(['id'=&gt;$id]) -&gt;count(); $branches = Mahasiswa::find() -&gt;where(['id'=&gt;$id]) -&gt;all(); if($countBranches &gt; 0) { foreach ($branches as $branch) { echo "&lt;option value'" .$branch-&gt;id. "'&gt;".$branch-&gt;user_id."&lt;/option&gt;"; } } else { echo "&lt;option&gt;-&lt;/option&gt;"; } } }</code></pre> </div> </div> </p>
Push files to gitlab-ci via CI runner <p>I am using gitlab CI runner to test my code and generating some files. I just want to push the generated files to gitlab repository via CI runner. Is there any way to do that ?</p>
<p>The Feature you are looking for is called Artifacts. Artifacts are files which are attached to a build when they are successful.</p> <p>To enable an Artifact put this in your .gitlab-ci.yml:</p> <pre><code>artifacts: paths: - dir/ - singlefile </code></pre> <p>This will upload the <code>dir</code> directory and the file <code>singlefile</code> back to GitLab.</p>
Angular 2 how to define lazy loaded child routes of a parent route that's also lazy loaded <p>I'm trying to get lazy loading to work for my app but it's one issue after another. I've gotten the main route to lazy load which is <code>/admin</code>, now I want to add another route which is <code>/admin/login</code>. </p> <p>So I did this:</p> <p><strong>admin-router.module.ts</strong></p> <pre><code>@NgModule({ imports: [ ComponentsModule, SharedModule, RouterModule.forChild([ { path: '', component: AdminAreaComponent, children: [ { path: 'login', loadChildren: 'app/+admin-area/pages/login/login.module#LoginModule' } ] } ]) ], exports: [ RouterModule ], declarations: [ AdminAreaComponent ] }) export class AdminAreaRouterModule {} </code></pre> <p><strong>login-router.module.ts</strong> import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router';</p> <pre><code>// Global modules import {ComponentsModule, SharedModule} from '../../shared'; // Components import {LoginComponent} from '../login.component'; @NgModule({ imports: [ ComponentsModule, SharedModule, RouterModule.forChild([ { path: '', component: LoginComponent } ]) ], exports: [ RouterModule ], declarations: [ LoginComponent ] }) export class LoginRouterModule {} </code></pre> <p><strong>login.module.ts</strong></p> <pre><code>import {NgModule} from '@angular/core'; import {ComponentsModule, SharedModule} from '../../../shared'; import {LoginComponent} from './login.component'; import {LoginRouterModule} from './router'; @NgModule({ imports: [ ComponentsModule, SharedModule, LoginRouterModule ], exports: [ ComponentsModule, SharedModule, LoginRouterModule ] }) export class LoginModule {} </code></pre> <p>The problem though is that as soon as I add the <code>children</code> part, <code>/admin</code> stops working all together, throwing the error <code>Cannot match any routes. URL Segment: 'admin'</code>.</p> <p>Is this not how you define child routes of a lazy loaded route? How can I fix it?</p>
<p>You need to define an empty route within your LoginModule.</p> <p><strong>login.module.ts</strong></p> <pre><code>@NgModule({ imports: [ RouterModule.forChild({ path: '', component: LoginComponent }) ComponentsModule, SharedModule ], exports: [ ComponentsModule, SharedModule ], declarations: [ LoginComponent ] }) export class LoginModule {} </code></pre>
What is the limit of holding the data in viewstate? <p>What is the limit of data we hold in ViewState? And are the limitations of Viewstate?</p> <pre><code>ViewState["allDataOfCandidates"]=dt; </code></pre>
<p>Viewstate does not have any size limitations. But nothing comes for free, and view state is no exception. It certainly imposes performance hits whenever an Asp.net webpage is requested.</p> <ol> <li><p>On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __VIEWSTATE form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.</p></li> <li><p>The __VIEWSTATE hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __VIEWSTATE form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.</p></li> </ol> <p>If you are designing a Web site that is commonly accessed by users coming over a modem connection, you should be particularly concerned with the bloat the view state might add to a page. Fortunately, there are a number of techniques that can be employed to reduce view state size. You just have to turn off the view state tracking for that control.</p> <p>For additional information you can go through - <a href="https://msdn.microsoft.com/en-us/library/ms972976.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/ms972976.aspx</a></p>
Better approach for login implementation without internet connection and matching password from local db <p>I am integrating log in in my app. There is a requirement for log in without internet connection. Means first time when user gets login there will be a web service call for log in authentication but next time the web service call should not be needed it should authenticate from local db of device. First time on log in response I am saving user credentials in local db (means device db using sqlite) and for rest of the attempts I am matching credentials from local db for authentication. For authentication, password is a plan text in local db and I am matching plan passwords. It this good idea/approach to match password as a plan text or I am supposed to be using any encryption? If encryption is required so why is it needed so. I mean when db file is stored internally no one can fetch password.So why encryption is needed?</p>
<p>Never ever store passwords in plain text anywhere. Event when it's local and nobody has access to it.<br> The better approach is storing it using a hashing algorithm along with salt so the if password is leaked somewhere, no harm should come of it. You can then hash the input password with the same algorithm and verify it with one you have previously stored.</p> <p>Here are some links to get you started on hashing:</p> <ol> <li><a href="https://crackstation.net/hashing-security.htm" rel="nofollow">https://crackstation.net/hashing-security.htm</a></li> <li><a href="http://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/" rel="nofollow">http://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/</a></li> </ol>
Microsoft.Office.Interop.Excel missing in the Component Name list <p>Microsoft.Office.Interop.Excel in the Component Name list is missing on the Assemblies page.</p> <p>I need to include that:</p> <pre><code>using Microsoft.Office.Interop.Excel; </code></pre> <p>But it throws error: <em>The type or namespace name 'Office' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)</em> </p> <p>And I can't find it in References either.</p>
<p>Try installing interop package from microsoft depending on your version of excel. </p> <p>Then check if the microsoft excel 12.0 library will be on your reference.</p> <p>See if it helps.</p>
Thread safe of operation in one entry <p>I want to do operations like </p> <pre><code>class A { } ConcurrentHashMap&lt;A, Integer&gt; map = new ConcurrentHashMap&lt;&gt;(); public void fun() { Integer count = map.get(Object); if (count != null) { map.put(Object, count+1); } } public void add() { // increase Object count by 1 } public void remove() { // deduct Object count by 1 } </code></pre> <p>How can I make fun() thread safe ?</p> <p>I know a way to do this is to add synchronized block</p> <pre><code>public void fun() { synchronized("") { Integer count = map.get(Object); if (count != null) { map.put(Object, count+1); } } } </code></pre> <p>But are there any other ways to do it ? Or are there any libraries to do it ?</p> <p>like thread safe entry processor ?</p> <hr> <p>I also want to implement something like </p> <pre><code>public void remove() { int count = map.get(Object); count -= 5; if (count &lt;= 0) { map.remove(Object); } else { map.put(Object, count + 2); } } Any ways to do this ? Thank you </code></pre>
<p>Use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html" rel="nofollow">AtomicInteger</a> and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#putIfAbsent-K-V-" rel="nofollow">ConcurrentHashMap.putIfAbsent()</a></p> <p>Also look at the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#remove-java.lang.Object-java.lang.Object-" rel="nofollow">ConcurrentHashMap.remove(key, value)</a> -- removes the key only if it is mapped to the given value.</p> <p>I am not sure, if it is possible to implement the exact logic (which is not very well defined in the question above), but those methods could be very useful in doing something similar.</p> <p>More hints (that could be useful or may be not too much):</p> <p>You (probably!) can use methods: computeIfAbsent, computeIfPresent (or replace), and remove(key, value). ConcurrentHashMap could be defined on values are Integers.</p> <p>It will be very dirty solution, and I do not recommend you to use it, but as something to think about, it could be very challenging.</p> <p>Let me know if you need more hints.</p>
Identify duplicate customer id's in a list of customers <p>A complete newbie here so I apologize if my question is stupid. I honestly tried before posting. I have a list of some customers, with their customer Id's as one column and customer name as the other, and age as the third column. </p> <p>I want to go through this list and identify whether the same customerId is in the list more than once. In that case, I need to delete that whole customer (even if his name or age is different). </p> <p>Can you please advise what to use to do this logic? </p> <p>I tried adding the customers to a set (because set would not add duplicates), but how do I state that it is the customerId, not the customer, that cannot be duplicated in this list?</p> <p>So far I got this below, but in my logic nothing says that customer is considered a duplicate when his customerId is a duplicate. (I don't necessarily need to use a list. Customer is an object).</p> <pre><code> //Customer is a class that contains a private variable customerId, so I can do customer.getCustomerId(); List&lt;Customer&gt; notDuplicatedCustomers = new ArrayList&lt;Customer&gt;(); //list of customers final Set&lt;Customer&gt; setToReturn = new HashSet&lt;Customer&gt;(); final Set&lt;Customer&gt; initialSet = new HashSet&lt;Customer&gt;(); for (Customer customer: notDuplicatedCustomers ) { if (!initialSet.add(customer)) { setToReturn.add(customer); } } </code></pre>
<blockquote> <p>I tried adding the customers to a set (because set would not add duplicates), but how do I state that it is the customerId, not the customer, that cannot be duplicated in this list?</p> </blockquote> <p>This is possible if you override the <code>equals()</code> method based on the ID field, thereby telling the set that two customers are logically equal if they have the same ID. Here is an example implementation generated by my IDE (assuming id is of type <code>String</code>; if the type is some primitive type use its wrapper):</p> <pre><code>@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Student other = (Student) obj; if (id == null) { if (other.id!= null) { return false; } } else if (!id.equals(other.id)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = (prime * result) + ((id == null) ? 0 : id.hashCode()); return result; } final Set&lt;Customer&gt; myCustomerSet = new HashSet&lt;Customer&gt;(); myCustomerSet.add(customer1); ... </code></pre> <p>Then when you add customers to the set you should have only one entry with the same ID in the set. The <code>hashCode()</code> is not necessary for your case, but normally if you override <code>equals()</code>, you should also override the <code>hashCode()</code>.</p>
jQuery autocomplete keeps giving TypeError <p>been trying to figure out this one for hours, no luck. The exact error according to firebug is: TypeError: items[0] is null <a href="http://localhost:81/tab/resources/jquery-ui.js" rel="nofollow">http://localhost:81/tab/resources/jquery-ui.js</a> Line 8488</p> <p>and the code is:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="resources/jquery-ui.css"&gt; &lt;script src="resources/jquery-3.1.1.js"&gt;&lt;/script&gt; &lt;script src="resources/jquery-ui.js"&gt;&lt;/script&gt; &lt;script&gt; $(function() { $( "#skills" ).autocomplete({ source: 'search.php', minLength: 3 }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="ui-widget"&gt; &lt;label for="skills"&gt;Skills: &lt;/label&gt; &lt;input id="skills"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>search.php:</p> <pre><code>&lt;?php require("db.php"); $connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME); $key = $_GET['term']; $query = mysqli_query($connection, "SELECT * FROM sz55 WHERE name LIKE '%{$key}%' AND ejszakak BETWEEN 1 AND 100"); while($row = mysqli_fetch_assoc($query)) { $data[] = $row['name']; } echo json_encode($data); mysqli_close($connection); ?&gt; </code></pre> <p>Help please :D</p>
<p>Turns out, the problem was that I had special characters in my array wich came from the query. Simply adding mysqli_set_charset($connection, "utf8"); to the search.php solved the problem.</p>
Enable DataGrid sorting for first column in xaml <p>I have a DataGrid in WPF with autogenerated columns.</p> <p>How can I disable sorting functionality of all the rows except the first one which corresponds time in my Source.</p> <p>I am following MVVM pattern and I know that CanUserSortColumns is disabling sorting for all the columns. I want to disable all but the first column.</p> <p>Should I write trigger or interaction or something else? All the help is appreciated.</p> <pre><code>&lt;DataGrid AutoGenerateColumns="True" ItemsSource="{Binding MyDataTable}" CanUserSortColumns="False"&gt; &lt;/DataGrid&gt; </code></pre>
<p>I found this code <a href="http://stackoverflow.com/questions/1296532/making-a-datagrid-column-header-sortable-in-wpf-using-c-sharp">snippet</a> for you:</p> <pre><code>&lt;my:DataGridTemplateColumn SortMemberPath="CompleteDate" Header="Complete Date" CanUserSort="true"&gt; &lt;my:DataGridTemplateColumn.CellTemplate &gt; &lt;DataTemplate&gt; &lt;TextBlock&gt; &lt;TextBlock.Text&gt; &lt;Binding Path="CompleteDate" ConverterCulture="en-GB" StringFormat="{}{0:MM/dd/yyyy}"/&gt; &lt;/TextBlock.Text&gt; &lt;/TextBlock&gt; &lt;/DataTemplate&gt; &lt;/my:DataGridTemplateColumn.CellTemplate&gt; &lt;/my:DataGridTemplateColumn&gt; </code></pre> <p>Use the CanUserSort Property to define it's sortable-state column explicit. The SortMemberPath defines the Property you use for sorting. Hope this helps.</p> <p><strong>UPDATE:</strong> If you are using autogenerated columns you can't access them via xaml. So you need to access them in code File.</p> <p>I'm not familiar with the xaml Grid but would expect something like:</p> <pre><code>//Bound Data here so that the Grid generate the columns int i = 0; foreach (DataColumn column in myGrid.ColumnCollection) { if (i == 0) column.CanSortUser = true; else column.CanSortUser = false; i++; } </code></pre> <p>The original Typenames can differ but something this way should be possible.</p> <p><strong>UPDATE-2</strong></p> <p>If you don't want to hurt the MVVM you can use <a href="http://stackoverflow.com/questions/14236222/how-can-i-access-a-control-in-mvvm-model-in-viewmodel">this</a>. There is described how to use Interfaces to access the code and stay independet with your view and viewmodel.</p>
Date Difference between consecutive rows <p>I have a table with following structure</p> <pre><code>RetailerCode Orderdate 1001 01-JUL-16 1001 04-JUL-16 1001 06-JUL-16 </code></pre> <p>I want this output</p> <pre><code>1001 10/9/2011 - 12/9/2011 2 days 1001 12/9/2011 - 20/9/2011 8 days 1001 20/9/2011 NA </code></pre>
<p>It s look like simple analitic functions </p> <pre><code>select RetailerCode, tO_char(Orderdate,'DD/mm/YYYY')||nvl2(next_Orderdate,' - '||tO_char(next_Orderdate,'DD/mm/YYYY'),'') Orderdate_diff, nvl(to_char(next_Orderdate - Orderdate),'NA') count_days from (select RetailerCode, Orderdate, lead(Orderdate) over (partition by RetailerCode order by Orderdate) next_Orderdate from YOUR_TABLE ) </code></pre>
Keras - input shape of large 2-dimensional Array <p>I want to build an array which contains a very large number of elements number of sequences (batch size) * size of dictionary (unique words in file) 474683 * 22995</p> <p>each sequence will have some number X of bits turned on which represents a word in the dictionary</p> <p>the sentence is: "I am the best king" lets say the dictionary is:</p> <p>[I, am, king, the, best, animal, toast, ...]</p> <p>the sequence will look like:</p> <p>[1,1,1,1,1,0,0,...]</p> <p>I try to import this to keras and I get an error:</p> <p>Exception: Error when checking model input: expected lstm_input_9 to have 3 dimensions, but got array with shape (93371, 22995)</p> <p>From <a href="http://stackoverflow.com/questions/38105999/dimension-mismatch-in-lstm-keras">here</a> we can see that keras expects: (batch_size, sequence_length, input_dimension)</p> <p>What can I do about this?</p> <p>If I try to build an nunpy array which has a sequence length, say 20, I will get a memory error (its something like 26gb), should I just split the array and train on each one separately?</p>
<p>Okay, I decided to split the array and train on each of the split instead of pushing everything to memory:</p> <pre><code>data_cut = 3 X = np.zeros((len(inputs)/data_cut, max_len, len(words)), dtype=np.bool) y = np.zeros((len(inputs)/data_cut, len(words)), dtype=np.bool) # set the appropriate indices to 1 in each one-hot vector ins = [] for cuts in range(0,data_cut):#number of cuts cutLocation = len(inputs)/data_cut*cuts#location of cut start = (cutLocation) end = (len(inputs)/data_cut) * (cuts + 1) ins.append(inputs[start:end])#first half for i, example in enumerate(ins[cuts]): for t, word in enumerate(example): X[i, t, word_labels[word]] = 1 y[i, word_labels[outputs[i]]] = 1 model.fit(X, y, batch_size=64, nb_epoch=epochs) </code></pre> <p>Of course you want to split then train over the number of splits.</p> <p>If anyone want to take a stab at making this more efficient please write below.</p>
How can I determine the register bit widths correctly? <p>This is the simple code I wrote.From 'outt' I get 122116. But if I change 'outt' width to be 33 bits ([32:0]) then code seems to work and give the correct answer -140028. What is the reason for this behaviour?? </p> <pre><code>`timescale 1ns / 1ps module valu_parser(clk,outt); input clk; reg signed [31:0] r_1; reg signed [31:0] r_2; output reg signed [31:0] outt; initial begin r_1 = -47938; r_2 = -150096; end always @ (posedge clk) begin outt &lt;= ((r_1 + r_2)* 11585 + 8192)&gt;&gt;&gt;14; end endmodule </code></pre>
<p>You are performing an operation that needs at least 33 bits (the temporary result before the right shift uses 33 bits) and theoretically it could need 32+"the size of the multiplicand constant" assuming that r_1 and r_2 are not constants.</p> <p>If you think of the hardware your code will generate, these bits needs to be stored somewhere temporarily to allow the hardware to first perform multiplication, then addition followed by the right shift. </p> <p>This will do the trick, but will also generate more registers than you wanted initially. If you are using this module to generate a constant, I would recommend hard-coding the constant.</p> <pre><code>module valu_parser(clk,outt); input clk; reg signed [31:0] r_1; reg signed [31:0] r_2; reg signed [32:0] temp; output reg signed [31:0] outt; initial begin r_1 = -47938; r_2 = -150096; end always @ (posedge clk) begin temp &lt;= ((r_1 + r_2)* 11585 + 8192); end assign outt = temp&gt;&gt;&gt;14; endmodule </code></pre> <p>The concept can be seen here: <a href="https://www.edaplayground.com/x/3BXy" rel="nofollow">https://www.edaplayground.com/x/3BXy</a>.</p>
Multiple booleans if condition in C# <p>In plain language - if this portion of the script detects that the direction is "right" and the two booleans "Wallright" and "WallsLeftOrRight" are false then play the standard walking animation and move the sprite...</p> <p>This portion works okay, it is the next portion I am having trouble with.</p> <p>In my mind the logic sounds workable - IF the direction is right and either of the booleans are true than play the idle animation.</p> <p>In practice the game is requiring BOTH booleans to be true meaning that the | operator is requiring them both to be true. I've tried switching to the logical || operator since | appears to not be for conditions of this nature but that did nothing. I also tried removing the two OR values from within their own bracket encapsulation but that did not work either. </p> <pre><code> if ((direction == "right") &amp;&amp; ((WallRight == false) | (WallsLeftOrRight == false))) { var newanim = character.GetComponent&lt;Animator&gt;(); newanim.Play("right_walking"); character.transform.position += Vector3.right * 0.6f * Time.deltaTime; charDirection = PlayerFacing.Right; } else if ((direction == "right") &amp;&amp; ((WallRight == true) | (WallsLeftOrRight == true))) { var newanim = character.GetComponent&lt;Animator&gt;(); newanim.Play("right_idle"); charDirection = PlayerFacing.Right; } </code></pre>
<p>First of all, simplify your code.</p> <p><code>if(WallRight == false)</code> is the-same as <code>if(!WallRight)</code></p> <p><code>if(WallRight == true)</code> is the-same as <code>if(WallRight)</code></p> <p>To answer your question:</p> <blockquote> <p>If this portion of the script detects that the direction is "right" and the two booleans "Wallright" and "WallsLeftOrRight" are false then play the standard walking animation</p> </blockquote> <pre><code>if (direction == "right" &amp;&amp; !WallRight &amp;&amp; !WallsLeftOrRight) </code></pre> <blockquote> <p>IF the direction is right and either of the booleans are true than play the idle animation.</p> </blockquote> <pre><code>if ((direction == "right") &amp;&amp; (WallRight || WallsLeftOrRight)) </code></pre> <p>First, direction is checked, then <code>||</code> is used to check if either <code>WallRight</code> or <code>WallsLeftOrRight</code> is true. As you can see, <code>WallRight</code> and <code>WallsLeftOrRight</code> are put int the-same parenthesis. The check will be done once for them.</p> <pre><code>if (direction == "right" &amp;&amp; !WallRight &amp;&amp; !WallsLeftOrRight) { var newanim = character.GetComponent&lt;Animator&gt;(); newanim.Play("right_walking"); character.transform.position += Vector3.right * 0.6f * Time.deltaTime; charDirection = PlayerFacing.Right; } else if ((direction == "right") &amp;&amp; (WallRight || WallsLeftOrRight)) { var newanim = character.GetComponent&lt;Animator&gt;(); newanim.Play("right_idle"); charDirection = PlayerFacing.Right; } </code></pre>
How to connect Aws S3 to Wowza Streaming Engine? <p>We have finished our project.we have using many Web Server in our project and also we have used AWS S3 server to save the media files.we have run app in web &amp; Android &amp; IOS deceives. That time videos are taking long time to play in our application. we are planning to use Wowza Streaming Engine for video streaming. But We don't no how to connect the Wowza Streaming Engine to AWS S3 server</p>
<p>After you've created your S3 bucket, you mount it as a local file system. If you are using the pre-built AMI provided by Wowza, then you can use the built-in application named <strong>vods3</strong>. This application is already configured to use Media Cache so that after the first playback, the files are cached on the local instance therefore providing better performance for subsequent requests. </p> <p>Also, if you are recording live streams from Wowza Streaming Engine, there is a <strong>wse-plugin-s3upload</strong> module that you can use to automatically copy the recorded files to a S3 bucket. Available on GitHub, <a href="https://github.com/WowzaMediaSystems/wse-plugin-s3upload" rel="nofollow">https://github.com/WowzaMediaSystems/wse-plugin-s3upload</a></p> <p>Playback URL would look like this, using an HLS playback as an example with a video name <strong>myStream.mp4</strong> located in your S3 bucket named <strong>mybucket</strong> in a folder named <strong>myvideos</strong>.</p> <pre><code>http://[instance-public-dns]/vods3/_definst_/mp4:amazon3:mybucket/myvideos/myStream.mp4/playlist.m3u8 </code></pre>
How to add foreign key in Laravel 5.1 Integrity constraint violation: 1452? <p>I am adding a foreign key to <strong>Tickets</strong> Table. The other table is <strong>ticket_statuses</strong>.</p> <p>In artisan, i executed this command: <strong>php artisan make:migration add_ticket_status_to_tickets_table</strong></p> <p>This is the code inside the migration file:</p> <pre><code> class AddTicketStatusToTicketsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('tickets', function ($table) { $table-&gt;integer('ticket_status_id')-&gt;unsigned(); $table-&gt;foreign('ticket_status_id')-&gt;references('id')-&gt;on('ticket_statuses')-&gt;onDelete('cascade'); }); } } </code></pre> <p>After that, i try to implement a relationship. This is my code inside <strong>Tickets Model</strong>:</p> <pre><code>class Ticket extends Model { // Ticket __belongs_to__ Ticket Status public function ticket_status() { return $this-&gt;belongsTo('App\TicketStatus'); } } </code></pre> <p>In artisan, i executed <strong>php artisan migrate</strong> But I <strong>encountered an error</strong></p> <pre><code>[Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`idealcrmalphadb`.`#sql-4ea_1ce`, CONSTRAINT `tickets_ticket_status_id_foreign` FOREIGN KEY (`ticket_status_id`) REFERENCES `tickets` (`id`) ON DELETE CASCADE) (SQL: alter table `tickets` add constraint tickets_ticket_status_id_foreign foreignkey (`ticket_status_id`) references `tickets` (`id`) on delete cascade) [PDOException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`idealcrmalphadb`.`#sql-4ea_1ce`, CONSTRAINT `tickets_ticket_status_id_foreign` FOREIGN KEY (`ticket_status_id`) REFERENCES `tickets` (`id`) ON DELETE CASCADE) </code></pre> <p>Have i made mistake in the model part? Please help</p>
<p>Check your migration table name and reference table name. You have mistake here.</p> <p>UPD:</p> <p>It looks like you already have data in tickets table. If so, you can try now</p> <pre><code>$table-&gt;integer('ticket_status_id')-&gt;unsigned()-&gt;nullable(); </code></pre>
Sublime text 3 plugin development for custom autocomplete like emmet? <p>I would like to create my custom plugin like emmet for auto completion and tag expansion for html tags like <code>h2&gt;span</code> .myclass should result in <code>&lt;div class="myclass"&gt;&lt;/div&gt;</code>.</p> <p>I started with but didn't find any documentation for tracking the user type event and how to define scope for plugin to be only applied for html files.</p> <p>When i tried to use print statement inside my class it throws syntax error</p> <pre><code>def run(self, edit): print "i am in run" self.view.insert(edit, 0, "Hello, World!") </code></pre> <p>How can i debug my plugin code without print statement or is there any alternative for sublime plugin ?</p>
<p>Typically, one doesn't program a plugin to track what the user types in Sublime Text, but instead binds a command to a keybinding. Then, when the user presses that certain key, under certain conditions, defined in the context of the keybinding, the command executes and looks at the text near the selection caret.</p> <p>Sublime Text plugins are developed in Python 3, where <code>print</code> is not a statement, but a function. Therefore, you need to use <code>print('I am in "run"')</code> to output debug messages to the ST console.</p> <p>For example, if this was your plugin code:</p> <pre><code>import sublime import sublime_plugin class ThisIsAnExampleCommand(sublime_plugin.TextCommand): def run(self, edit): print('I am in the "run" method of "ThisIsAnExampleCommand"') self.view.insert(edit, 0, "Hello, World!") </code></pre> <p>then you might define a keybinding like:</p> <pre><code>{ "keys": ["tab"], "command": "this_is_an_example", "context": [ { "key": "selector", "operator": "equal", "operand": "text.html", "match_all": true }, { "key": "selection_empty", "operator": "equal", "operand": true, "match_all": true }, ] }, </code></pre> <p>which would operate when the user presses <kbd>Tab</kbd>, but only if all selections are empty, and the syntax of the current file being edited is HTML.</p> <p>Your plugin could look at <code>self.view.sel()</code> to get the selection/caret position(s).</p>
How to create a database with collation value from other database <p>I am taking a backup of database and restoring it on other system which have other collation. Want to know how can I get the collation from database of target system and use it to create new database with this collation instead of collation set in backup.</p>
<p>You can't specify collation while restoring..Only options are</p> <p>1.Alter collation once restore is done<br> 2.IF you have scripted out the database,then you can alter the scripts</p> <p>to get collation : </p> <pre><code>select name, collation_name from sys.databases </code></pre> <p>To alter collation: </p> <pre><code>USE master; GO ALTER DATABASE dbname COLLATE collationneeded ; GO </code></pre>
What kind of type have the range in for loop? <p>When we write the following:</p> <pre><code>for i in 1...10 { //do stuff } </code></pre> <p>I want know what type have the range <code>1...10</code> to use it in function call for example:</p> <pre><code>myFunc(1...10) </code></pre>
<p>If you put a breakpoint after defining <code>let range = 1..&lt;10</code>, you will see that it's actually not a <code>Range</code> structure, but rater a <code>CountableRange</code> (or <code>CountableClosedRange</code> for 0...10)</p> <p>Docs: <a href="https://developer.apple.com/reference/swift/countablerange" rel="nofollow">CountableRange</a>, <a href="https://developer.apple.com/reference/swift/countableclosedrange" rel="nofollow">CountableClosedRange</a></p> <p>Functions:</p> <pre><code>func printRange(range: CountableRange&lt;Int&gt;) { for i in range { print ("\(i)") } } func printRange(range: CountableClosedRange&lt;Int&gt;) { for i in range { print ("\(i)") } } </code></pre> <p>Usage:</p> <pre><code>let range = 1..&lt;10 printRange(range: range) let closedRange = 1...10 printRange(range: closedRange) </code></pre> <p><strong>Generic function:</strong></p> <p>Since both structs conform to <code>RandomAccessCollection</code> protocol, you can implement only one function like this:</p> <pre><code>func printRange&lt;R&gt;(range: R) where R: RandomAccessCollection { for i in range { print ("\(i)") } } </code></pre> <p><a href="https://oleb.net/blog/2016/09/swift-3-ranges/" rel="nofollow">This article</a> about ranges in Swift 3 may also be useful.</p>
Is it possible to move files or file changes between branches? <p><strong>Summary</strong>: I forgot to switch branches when developing and would like to move the files/changes to the appropriate branch.</p> <p><strong>Details</strong>: I have two files <code>A</code> and <code>B</code> which are initially in <code>master</code>. I then created a branch <code>branch1</code> to make some breaking changes in file <code>A</code>.</p> <p>While developing these changes I also modified <code>B</code> and created a file <code>C</code>. The problem is that I now realize I made a mistake with branching and that </p> <ul> <li>the file <code>B</code> should be in its own <code>branch2</code> (which does not exist), </li> <li>file <code>C</code> belongs in <code>master</code>. </li> </ul> <p>All of them are now commited in <code>branch1</code>.</p> <p>The commits were pushed to a remote repository but it does not matter that much, I can have the other developer clone the repo (as opposed to fetch).</p> <p><strong>What is the general methodology to recover in such a case, ie. to move files or changes between branches?</strong></p>
<p>A simple solution is, from where you are on <code>branch1</code>:</p> <ul> <li>create branch2 (<code>git checkout -b branch2</code>), and remove <code>C</code>. Add, commit, and push</li> <li>get back to master (git checkout master), and <a href="http://stackoverflow.com/a/7099164/6309">copy <code>C</code> from <code>branch1</code></a> (<code>git show branch1:path/to/C &gt;path/to/C</code>). Add, commit and push.</li> <li>finally, get back on <code>branch1</code>, remove the extra files, add, commit and push.</li> </ul> <p>That way, no merge, no history rewrite, not even a revert, just some additional commits pushed to remote to cleanup the current situation.</p>
Android converting color string to resource int <p>I am trying to set color from a json color array to my custom menu background.</p> <p><code>addMenuItem(int bgColor);</code></p> <p>json color array =></p> <pre><code>[ [ "B71C1C", "C62828"],[ "B71C1C", "C62828"] ] </code></pre> <p>Color String is getting correctly from json</p> <p><code>String colorString = "#" + mColors.getJSONArray(i%2).getString(i%2);</code> gives #B71C1C;</p> <p>While convert it to integer <code>int parseColor = Color.parseColor(colorString);</code> and passing to above menu background;</p> <p><code>ie;addMenuItem(parseColor);</code></p> <p>I'm getting </p> <blockquote> <p>android.content.res.Resources$NotFoundException: Resource ID #0xffb71c1c</p> </blockquote> <p>I think addMenuItem will accept int only from resource. How can I set color from my JSON color file.</p>
<p>That's because you are throwing in a number and the Android framework tries to find a resource for that (R.color) which doesn't exist. You should convert that number to a <code>Color</code> object, using <code>Color.argb(int,int,int,int)</code> for example</p>
Closure confusion with keyword 'this' <p>Below is my module. I want to namespace 'Module' with self. So inside the module I assign this to self. With this, inside closures I can call Module as 'self' instead of this, that's my idea. But it gives error;</p> <p>How can I use self or any other variable name instead of the module name?</p> <pre><code>jQuery(document).ready(function($) { var Module = (function(sendTo){ var self = this; return { init: function() { console.log('start'); this.login(); //ok Module.login() //ok self.login() //TypeError: self.login is not a function }, login: function() { console.log('login'); } } })(interface); Module.init(); }); </code></pre>
<p>In your code, <code>self</code> has the value <code>this</code> had when you created your object; it doesn't refer to your object. When you call <code>Module.init</code>, the usual mechanism of setting <code>this</code> to the object that the <code>init</code> property came from during the call sets in.</p> <p>If you want to always refer to your object via <code>self</code>, assign the object you're creating to it, and then return that:</p> <pre><code>jQuery(document).ready(function($) { var Module = (function(sendTo){ var self = { // *** init: function() { console.log('start'); this.login(); Module.login(); self.login(); }, login: function() { console.log('login'); } }; return self; // *** })(interface); Module.init(); }); </code></pre> <p>Note, though, that nothing outside your code can change either <code>self</code> or <code>Module</code>, so it's a bit redundant to have both identifiers for the same object. Also note that <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/self" rel="nofollow"><code>self</code></a> is a built-in global that you're shadowing (it's another way to refer to <code>window</code>, with slight differences), so <code>self</code> may be confusing to other people working in the code.</p>
adding storyboard element run time issue <p>I have this situation :</p> <p><a href="https://i.stack.imgur.com/Wv5IA.png" rel="nofollow"><img src="https://i.stack.imgur.com/Wv5IA.png" alt="enter image description here"></a></p> <p>This pink view in the scrollview and I want is:</p> <p>when I tap on 'add' button, I want that to create another pink view object (this is no problem) and set it below the first pink view object setting auto layout for it(vertical space between it and previous pink view object, trailing space .....) but I don't be able to do this part.</p> <p>Can you help me? </p>
<p>I am not sure where you have problem adding view to scrollview. Here is example for adding button into scrollview at runtime. You can use same code for adding your pink view.</p> <pre><code>import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { var pickerviewObj : UIPickerView!=UIPickerView() var scrlview: UIScrollView = UIScrollView(); var cotentView : UIView = UIView(); var arrdata :NSMutableArray=["1","2","3","4","5","6","7","8","9","10"] var dctButtons : NSMutableDictionary!=NSMutableDictionary() var ContentViewconstraintheight : NSLayoutConstraint = NSLayoutConstraint() var xPos,ypos: NSInteger! var SelctedTag : NSInteger! var width: Double! // var colors = ["Red","Yellow","Green","Blue"] func getCalculatedHeightForScren(height : CGFloat) -&gt; CGFloat { return (height * self.view.frame.size.height/568 ); } func disableAutoResizingMasks() { self.pickerviewObj.translatesAutoresizingMaskIntoConstraints = false self.scrlview.translatesAutoresizingMaskIntoConstraints = false self.cotentView.translatesAutoresizingMaskIntoConstraints = false; } override func viewDidLoad() { super.viewDidLoad() let pickerHeight = getCalculatedHeightForScren(height: 50) self.pickerviewObj = UIPickerView(frame: CGRect(x: 0, y: self.view.frame.size.height-pickerHeight, width: self.view.frame.size.width, height: pickerHeight) ) self.view.addSubview(self.pickerviewObj); pickerviewObj.backgroundColor = UIColor.white; pickerviewObj.showsSelectionIndicator = true; let toolBar = UIToolbar() toolBar.barStyle = UIBarStyle.default; toolBar.isTranslucent = true toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1) toolBar.sizeToFit() self.view.addSubview(self.scrlview) self.scrlview.addSubview(self.cotentView); let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(ViewController.DonePicker)) toolBar.setItems([ spaceButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true toolBar.frame = CGRect(x: 0, y: self.view.frame.size.height-pickerHeight-44, width: self.view.frame.size.width, height: 44); self.view.addSubview(toolBar); pickerviewObj.dataSource = self; pickerviewObj.delegate = self; //add constraints to PickerView let constraintCenterX = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0); let constraintBottom = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.bottom, multiplier: 1, constant:0); let constraintWidth = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0); let constraintHeight = NSLayoutConstraint(item: pickerviewObj, attribute: NSLayoutAttribute.height , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.height, multiplier: (200/568), constant:0); //add constraints to ScrollView let scrollconstraintCenterX = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0); let scrollconstraintBottom = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: toolBar , attribute: NSLayoutAttribute.top, multiplier: 1, constant:0); let scrollconstraintWidth = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0); let scrollconstraintTop = NSLayoutConstraint(item: self.scrlview, attribute: NSLayoutAttribute.top , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.top, multiplier:1, constant:0); //add constraints to ScrollView's contentView let ContentViewconstrainttop = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.topMargin, multiplier: 1, constant:0); let ContentViewconstraintBottom = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.bottomMargin, multiplier: 1, constant:0); let ContentViewconstraintleft = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.trailing , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.trailing, multiplier: 1, constant:0); let ContentViewconstraintright = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.leading , relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.leading, multiplier: (200/568), constant:0); let ContentViewconstraintWidth = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0); self.ContentViewconstraintheight = NSLayoutConstraint(item: self.cotentView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil , attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant:100); //add constraints to toolBar let toolconstraintCenterX = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0); let toolconstraintBottom = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.bottom , relatedBy: NSLayoutRelation.equal, toItem: self.pickerviewObj , attribute: NSLayoutAttribute.top, multiplier: 1, constant:0); let toolconstraintWidth = NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: self.view , attribute: NSLayoutAttribute.width, multiplier: 1, constant:0); //activare all constraints NSLayoutConstraint.activate([constraintWidth,constraintHeight,constraintCenterX,constraintBottom,toolconstraintWidth,toolconstraintBottom,toolconstraintCenterX,scrollconstraintTop,scrollconstraintWidth,scrollconstraintCenterX,scrollconstraintBottom,ContentViewconstrainttop,ContentViewconstraintBottom,ContentViewconstraintleft,ContentViewconstraintright,ContentViewconstraintWidth,self.ContentViewconstraintheight]); self.view.layoutSubviews() self.disableAutoResizingMasks(); toolBar.translatesAutoresizingMaskIntoConstraints = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func getSorted(s1 : Any , s2 : Any) -&gt; Bool{ let str1 : String = s1 as! String let str2 : String = s2 as! String return Int(str1)! &lt; Int(str2)!; } //custom Logics to Update UI func addConstarintsToButton(btn : UIButton , yPos : CGFloat) { NSLayoutConstraint.deactivate(btn.constraints); btn.removeConstraints(btn.constraints); let width = ((self.view.frame.size.width-20)/2) - 30; let height = self.getCalculatedHeightForScren(height: 40); let constraintCenterX = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.scrlview , attribute: NSLayoutAttribute.centerX, multiplier: 1, constant:0); let constrainttop = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.top , relatedBy: NSLayoutRelation.equal, toItem: self.cotentView , attribute: NSLayoutAttribute.top, multiplier: 1, constant:yPos); let constraintWidth = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.width , relatedBy: NSLayoutRelation.equal, toItem: nil , attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: width); let constraintHeight = NSLayoutConstraint(item: btn, attribute: NSLayoutAttribute.height , relatedBy: NSLayoutRelation.equal, toItem: nil , attribute: NSLayoutAttribute.notAnAttribute, multiplier: height, constant:height); NSLayoutConstraint.activate([constraintCenterX, constrainttop,constraintWidth,constraintHeight]) btn.translatesAutoresizingMaskIntoConstraints = false } func updateUIElements(tag : Int) { let arrKeys : NSMutableArray = NSMutableArray(array: dctButtons.allKeys, copyItems: true) let SortedKeys = arrKeys.sorted(by: getSorted) var xPos :CGFloat = 10.0; var yPos :CGFloat = 50.0; let width = ((self.view.frame.size.width-20)/2) - 30; let height = self.getCalculatedHeightForScren(height: 40); xPos = (self.view.frame.size.width - width)/2; UIView.animate(withDuration: 0.5, animations: { if(tag &gt; 0) { let vw = self.cotentView.viewWithTag(tag) vw?.removeFromSuperview() let vw1 = self.cotentView.viewWithTag(tag + 100) vw1?.removeFromSuperview() } for key in SortedKeys { let btn1 = self.dctButtons.object(forKey: key) as! UIButton btn1.frame = CGRect( x:xPos, y:yPos,width:width,height:height); if let testBtn = self.cotentView.viewWithTag(btn1.tag+100) as? UIButton { let btnCross = testBtn ; btnCross.frame = CGRect(x: xPos + btn1.frame.size.width + 5, y: yPos, width: 20, height: height); } self.ContentViewconstraintheight.constant = btn1.frame.size.height + 100; if let vw = self.cotentView.viewWithTag(btn1.tag) as? UIButton { vw.removeFromSuperview(); self.cotentView.addSubview(btn1); self.addConstarintsToButton(btn: btn1, yPos: yPos); } else{ self.cotentView.addSubview(btn1); self.addConstarintsToButton(btn: btn1, yPos: yPos); } yPos += height + 10 } self.view.layoutSubviews() self.ContentViewconstraintheight.constant = yPos ; }) } // Control event Methods.... func btnClick(sender: UIButton!) { SelctedTag=sender.tag; print(SelctedTag) if sender.isSelected { return; } sender.isSelected = true; let ButtonClose = UIButton(frame: CGRect(x: sender.frame.origin.x + sender.frame.size.width + 5, y: sender.frame.origin.y, width: 20, height: sender.frame.size.height) ) ButtonClose.tag = sender.tag + 100; ButtonClose.setTitle("X", for: UIControlState.normal) ButtonClose.backgroundColor = UIColor.gray ButtonClose.setTitleColor(UIColor.red, for: UIControlState.normal); ButtonClose.isUserInteractionEnabled = true; ButtonClose.addTarget(self, action: #selector(ViewController.btnClose(sender:)), for: UIControlEvents.touchUpInside); self.cotentView.addSubview(ButtonClose); let strVal = String(sender.tag) self.arrdata.remove(strVal) self.pickerviewObj.reloadComponent(0); } func DonePicker() { let selectedIndex = self.pickerviewObj.selectedRow(inComponent: 0); if (arrdata.count == 0 || selectedIndex &lt; 0 || selectedIndex &gt; arrdata.count ) { return; } let x : String = arrdata[selectedIndex] as! String let tag = Int(x)! if let vw = self.cotentView.viewWithTag(tag) as? UIButton { return; } let btn = UIButton(type: UIButtonType.system); btn.isSelected = false; btn.tag = tag btn.backgroundColor = UIColor.black; btn.setTitleColor(UIColor.white, for: UIControlState.normal) btn.addTarget(self, action:#selector(ViewController.btnClick(sender:)), for: UIControlEvents.touchUpInside) btn.setTitle("Field " + String(x), for: UIControlState.normal) btn.setTitleColor(UIColor.white, for: UIControlState.normal) btn.isUserInteractionEnabled = true; btn.center = self.pickerviewObj.center; dctButtons.setObject(btn, forKey: String(x) as NSCopying) self.pickerviewObj.reloadComponent(0); self.updateUIElements(tag: 0); } func btnClose(sender: UIButton!) { print((SelctedTag)) let key = String(sender.tag - 100); dctButtons.removeObject(forKey: key); arrdata.add( key) let tmpArray = arrdata.sorted(by: getSorted) arrdata.removeAllObjects(); arrdata.addObjects(from: tmpArray) self.pickerviewObj.reloadComponent(0); self.updateUIElements(tag: sender.tag - 100); } // Picker view Methods.... func numberOfComponents(in pickerView: UIPickerView) -&gt; Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int { return arrdata.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -&gt; String? { let x : String = arrdata[row] as! String return "Field " + x } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // let x : Int = arrdata[row] as! Int // arrButton.add(x) // print(arrButton) // self .numberOfButton(number: arrdata[row] as! Int) // arrdata.removeObject(at: row) // pickerView.reloadAllComponents() } </code></pre> <p>}</p>
Getting HTTP POST Error : {"reason":null,"error":"Request JSON object for insert cannot be null."} <p>I am getting HTTP POST error when I am trying to connect to a Service Now Instance for Change Request Automation using Python. Here is the script I am using with Python 3.4.4</p> <pre><code># SNOW CR AUTOMATION SCRIPT import requests import json # put the ip address or dns of your SNOW API in this url url = 'http://&lt;&gt;/change_request.do?JSONv2&amp;sysparm_action=insert' data= { 'short_description': '&lt;value&gt;', 'priority': '&lt;value&gt;', 'reason': '&lt;value&gt;', 'u_reason_for_change': '&lt;value&gt;', 'u_business_driver': '&lt;value&gt;', 'u_plan_of_record_id': '&lt;value&gt;' } print ("Data Inserted :") print (data) #Content type must be included in the header header = {"Authorization":"Basic V1NfRVRPX1ROOkBiY2RlNTQzMjE=","Content- Type":"application/json"} #Performs a POST on the specified url. response = requests.request('POST', url, auth=("&lt;value&gt;","&lt;value&gt;"), json=data, headers=header) print ( " Header is : ") print (response.headers) print (" ") print ( "HTTP Response is :" ) print (response) print (" ") print ("***********************") print (" Output : ") print ( response.text) </code></pre> <p>I am getting an error as below while running the above script.</p> <pre><code>Output : {"reason":null,"error":"Request JSON object for insert cannot be null."} </code></pre> <p>I am not sure why this error is thrown. Can anybody please help on this ?</p>
<p>This is a working example I tested on my instance. I am using REST Table API to insert a change request. It's not true that it can not be http. It's whatever protocol your instance allows to connect, say from browser. </p> <pre><code>#Need to install requests package for python #easy_install requests import requests # Set the request parameters url = '&lt;yourinstance base url&gt;/api/now/table/change_request' user = &lt;username&gt; pwd = &lt;password&gt; # Set proper headers headers = {"Content-Type":"application/json","Accept":"application/json"} # Do the HTTP request response = requests.post(url, auth=(user, pwd), headers=headers ,data="{\"short_description\":\"test in python\"}") # Check for HTTP codes other than 201 if response.status_code != 201: print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json()) exit() # Decode the JSON response into a dictionary and use the data data = response.json() print(data) </code></pre>
Error in inserting python variable in mysql table <p>I am working on a raspberry pi project, in which I'm fetching data from plc and storing it into mysql database.</p> <p>Here is my code:</p> <pre><code>import minimalmodbus import serial import mysql.connector instrument = minimalmodbus.Instrument('/dev/ttyAMA0',3,mode='rtu') instrument.serial.baudrate=115200 instrument.serial.parity = serial.PARITY_NONE instrument.serial.bytesize = 8 instrument.serial.stopbits = 1 instrument.serial.timeout = 0.05 con = mysql.connector.connect(user='root',password='raspberry',host='localhost', database='Fujiplc') cursor = con.cursor() try: reg_value=instrument.read_register(102) print reg_value cursor.execute("insert into Register_Values values(%s)",(reg_value)) print ('One row inserted successfully.') except IOError: print("Failed to read from PLC.") print (cursor.rowcount) con.commit() cursor.close() con.close() </code></pre> <p>After running this code, I get next error:</p> <pre><code>Traceback (most recent call last): File "/home/pi/rpi_to_plc_read.py", line 22, in &lt;module&gt; cursor.execute("insert into Register_Values values(%d)",(reg_value)) File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 477, in execute stmt = operation % self._process_params(params) File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 355, in _process_params "Failed processing format-parameters; %s" % err) ProgrammingError: Failed processing format-parameters; argument 2 to map() must support iteration </code></pre> <p>I have gone through so many solutions but problem couldn't solve. Please help me. </p>
<p>i think should be.</p> <pre><code>cursor.execute("insert into Register_Values values(%s)",(reg_value)) con.commit() </code></pre>
The table customer is successfully created with a primary key cust_id,Why is this still showing errors? <pre><code>mysql&gt; create table order(order_no int primary key,cust_no int,foreign key(cust_no) references customer(cust_no),order_date date,ship_date date,tocity varchar(20),tostate varchar(20),zip int); </code></pre> <blockquote> <p>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order(order_no int primary key,cust_no int,tocity varchar(20),tostate varchar(20' at line 1</p> </blockquote>
<p>NOTE: since <code>order</code> is a keyword, you can only access it as:</p> <pre><code> select * from `order` create table `order`(order_no int,cust_no int,foreign key(cust_no) references customer(cust_no),order_date date,ship_date date,tocity varchar(20),tostate varchar(20),zip int, primary key (order_no)); </code></pre>
Call another service function from a service function <p>Is there anyway to call another service form current service ?</p> <p>/<em>FACTORIES</em>/</p> <pre><code>app.service('p3call',function($http,$rootScope){ return { getRepairCategory:function(url){ $http.post(url) .success(function (response){ generatePaginationData(response); }); }, deleteRepairCategory:function(request,url){ $http.post(url,request) .success(function (response){ generatePaginationData(response) }); }, generatePaginationData:function(response){ var pages = []; $rootScope.categories = response.data; $rootScope.currentPage = response.current_page; $rootScope.totalPages = response.last_page; for(var i=1;i&lt;=response.last_page;i++) { pages.push(i); } $rootScope.range = pages; } }; }); </code></pre> <p>/<em>FACTORIES</em>/</p>
<p>yes it's totally possible:</p> <pre><code>app.service('p3call',function($http,$rootScope, myOtherService){ return { getRepairCategory:function(url){ ... }, deleteRepairCategory:function(request,url){ ... }, generatePaginationData:function(response){ ... } myFunction(){ myOtherService.newFunction(); } }; }); </code></pre> <p>Just inject your service and use it.</p>
Disabled audio on Visual Studio <p>I want to play .wav sound in my application. I know how to do it. For example with a SoundPlayer class:</p> <pre><code>SoundPlayer player = new SoundPlayer(); player.SoundLocation = @"C:\path\sample.wav"; player.Load(); player.Play(); </code></pre> <p>At home I have multiple Applications which can play sounds. However at job, I can't do it. Normally the computer can make sounds (youtube, Windows Media Player, etc.). </p> <p>I investigated that my application does not appear in Volume Mixer.</p>
<p>In the end it was faulty wav file. I converted it to mp3 and then back to wav and now it works.</p>
understanding marshmallow nested schema with list data <p>Am new to python and am usign <a href="https://marshmallow.readthedocs.io/en/latest/" rel="nofollow">marshmallow</a> serialization. unable to use the nested scehma. , my code </p> <pre><code>from sqlalchemy import Column, Float, Integer, String, Text, text,ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() metadata = Base.metadata class CompanyDemo(Base): __tablename__ = 'company_demo' company_id = Column(Integer, primary_key=True, server_default=text("nextval('company_demo_company_id_seq'::regclass)")) name = Column(Text, nullable=False) address = Column(String(50)) location = Column(String(50)) class UsersDemo(Base): __tablename__ = 'users_demo' id = Column(Integer, primary_key=True, server_default=text("nextval('users_demo_id_seq'::regclass)")) company_id = Column(Integer,ForeignKey('company_demo.company_id'), nullable=False) email = Column(String) company = relationship('CompanyDemo') </code></pre> <p>schema </p> <pre><code> from marshmallow import Schema, fields, pprint class CompanySchema(Schema): company_id = fields.Int(dump_only=True) name = fields.Str() address = fields.Str() location = fields.Str() class UserSchema(Schema): email = fields.Str() company = fields.Nested(CompanySchema) user = UserSchema() user = UserSchema(many=True) company = CompanySchema() company = CompanySchema(many=True) </code></pre> <p>and my flask app </p> <pre><code> from flask import Flask, jsonify, url_for, render_template from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from flask_sqlalchemy import SQLAlchemy from model import CompanyDemo, UsersDemo from schemas.userschema import user, company app = Flask(__name__) app.secret_key = "shiva" def db_connect(): engine = create_engine('postgresql://ss@127.0.0.1:5432/test') Session = sessionmaker(autocommit=False, autoflush=False, bind=engine) # create a Session session = Session() session._model_changes = {} return session @app.route('/company', methods=["GET", "POST"]) def get_all_company(): db = db_connect() allcompany = db.query(CompanyDemo).join(UsersDemo).all() return jsonify(company.dump(allcompany, many=True).data) # company is marshmallow schema if __name__ == '__main__': app.run(host='0.0.0.0', port=15418, debug=True) </code></pre> <p>anything wrong in my code? and am facing problem with nested schema and unable to get the nested data in output.</p> <p>the output below </p> <blockquote> <p>[ { "address": "qqq ", "company_id": 1, "location": "www ", "name": "eee" }, { "address": "www ", "company_id": 2, "location": "qqq ", "name": "aaa" } ]</p> </blockquote>
<p>Self contained example using in-memory SQLite:</p> <pre><code>from flask import Flask, jsonify from flask.ext.sqlalchemy import SQLAlchemy from marshmallow import Schema, fields, pprint app = Flask(__name__) app.config['DEBUG'] = True app.config['SECRET_KEY'] = 'super-secret' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) class CompanyDemo(db.Model): __tablename__ = 'company_demo' company_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False) address = db.Column(db.String(50)) location = db.Column(db.String(50)) def __unicode__(self): return u"{name} ({address})".format(name=self.name, address=self.address) class UsersDemo(db.Model): __tablename__ = 'users_demo' id = db.Column(db.Integer, primary_key=True,) company_id = db.Column(db.Integer, db.ForeignKey('company_demo.company_id'), nullable=False) company = db.relationship('CompanyDemo') email = db.Column(db.String) def __unicode__(self): return u"{email}".format(email=self.email) class CompanySchema(Schema): company_id = fields.Int(dump_only=True) name = fields.Str() address = fields.Str() location = fields.Str() class UserSchema(Schema): email = fields.Str() company = fields.Nested(CompanySchema) user_schema = UserSchema() company_schema = CompanySchema() @app.route('/') def index(): return "&lt;a href='/dump_company'&gt;Dump Company&lt;/a&gt;&lt;br&gt;&lt;a href='/dump_user'&gt;Dump User&lt;/a&gt;" @app.route('/dump_user') def dump_user(): user = UsersDemo.query.first() return jsonify(user_schema.dump(user).data) @app.route('/dump_company') def dump_company(): company = CompanyDemo.query.first() return jsonify(company_schema.dump(company).data) def build_db(): db.drop_all() db.create_all() company = CompanyDemo(name='Test 1', address='10 Downing Street', location='wherever') db.session.add(company) user = UsersDemo(email='fred@example.com', company=company) db.session.add(user) db.session.commit() @app.before_first_request def first_request(): build_db() if __name__ == '__main__': app.run(debug=True, port=7777) </code></pre>
Upload new iOS 10 application built by older Xcode 7 <p>I've a simple question.<br> What are requirements for new app upload to latest AppStore?<br>I mean is it required to use latest Xcode 8 and also latest swift or is it possible to upload the new application running on swift 2.2 version using Xcode 8 or maybe with Xcode 7?<br> I'm curios if apple states informations like that somewhere.</p>
<p>Apple recommends you to build and submit to App store with latest SDK. However, it doesn't mean that it forces you to do that. In other words, you can use older SDK to compile you source code. For example, you can compile you app with XCode8 with Swift 3, but if you do with XCode7 and Swift 2.2, it's also fine. Have a look at this: <a href="https://developer.apple.com/library/content/qa/qa1806/_index.html" rel="nofollow">https://developer.apple.com/library/content/qa/qa1806/_index.html</a></p>
Add two values to AutocompleteTextview Adapter <p>I am trying to display contact list in autoCompleteTextView so far I have successfully achieved that but I need to use the <code>contact_id</code> related to name how Should I bind <code>id</code> with name?</p> <p>I have used hashmap to store the contact list.</p> <p>here is my code to get contact and add them to <code>hashmap</code></p> <pre><code> Cursor cursor_number=getActivity().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null); if(cursor_number!=null){ if (cursor_number.moveToFirst()){ do{ contact_id=cursor_number.getString(cursor_number.getColumnIndex(ContactsContract.Data._ID)); if(Integer.parseInt(cursor_number.getString(cursor_number.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))&gt;0) { Cursor cursor_number1 = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + " = ? ", new String[]{contact_id}, null); if (cursor_number1 != null) { while (cursor_number1.moveToNext()) { String name=cursor_number1.getString(cursor_number1.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); String id=contact_id; HashMap&lt;String, String&gt; contact_data=new HashMap&lt;String, String&gt;(); contact_data.put(id,name); } cursor_number1.close(); } } } while (cursor_number.moveToNext()); cursor_number.close(); } } </code></pre> <p>and this is how i'm adding adapter to autoComplete textView</p> <pre><code> autoCompleteTextView =(AutoCompleteTextView) this.getActivity().findViewById(R.id.act_network_auto_search); autoCompleteTextView.setThreshold(2); checkContacts(); Collection&lt;String&gt; collection=contact_data.values(); String[] array= collection.toArray(new String[collection.size()]); adapter = new ArrayAdapter&lt;String&gt;(getContext(), android.R.layout.simple_dropdown_item_1line,array); autoCompleteTextView.setAdapter(adapter); </code></pre> <p>How should I get the <code>id</code> associated with <code>name</code></p> <p>any help would be great!</p> <p>Update :</p> <pre><code>LinkedHashMap&lt;String, String&gt; contact_data=new LinkedHashMap&lt;String, String&gt;(); contact_data.put(id,name); </code></pre>
<p>Check this example <a href="http://www.tutorialsbuzz.com/2015/03/Android-Custom-AutoCompleteTextView-Filter.html" rel="nofollow">AutocompleteTextView</a></p>
AngularJS - how to get the parameter from URL <p>I'm trying to pass the parameters to the AngularJS controller.</p> <p><strong>AngularJs Routes</strong> </p> <pre><code>$routeProvider.when('/post-ads/', { templateUrl: "ui/view/post-ads.php", controller: "adPostController", controllerAs: 'vm' }) $routeProvider.when('/post-ads/:category/:subcategory', { templateUrl: "ui/view/ad-details.php", controller: "adPostController", controllerAs: 'vm' }) </code></pre> <p><strong>AdPostController</strong></p> <pre><code>adPostController.$inject = ['ApiService', '$scope']; function adPostController(ApiService, $scope, $routeParams) { console.log("im here"); console.log($routeParams.category, $routeParams.subcategory); } </code></pre> <p><strong>HTML a href</strong></p> <pre><code>&lt;a href="#/post-ads/automobile/car&gt;click&lt;/a&gt; </code></pre> <p><strong>Error</strong></p> <blockquote> <p>TypeError: Cannot read property 'category' of undefined</p> </blockquote>
<p>Please inject <code>$routeParams</code></p> <p><code>adPostController.$inject = ['ApiService', '$scope', '$routeParams'];</code></p> <p>See: <a href="https://docs.angularjs.org/api/ngRoute/service/" rel="nofollow">https://docs.angularjs.org/api/ngRoute/service/</a>$routeParams</p>
Why does Gerrit compares a newly added file with a renamed file? <p>I renamed a file <code>ivim_uc5.xml</code> to <code>ivim_uc5_z1.xml</code>. Then I created 9 new files with the name <code>ivim_uc5_z2.xml ivim_uc5_z3.xml</code> and so on. After pushing the <code>Gerrit</code> shows like this:</p> <p><a href="https://i.stack.imgur.com/dfDt8.png" rel="nofollow"><img src="https://i.stack.imgur.com/dfDt8.png" alt="enter image description here"></a></p> <p>Why is it comparing the new files with a renamed file and how do I avoid this.</p>
<p>The "C" character on Gerrit UI indicates that you have copied the ivim_uc5_Z*.xml files from the ivim_uc5.xml one.</p> <p>See here:</p> <p><a href="https://gerrit-review.googlesource.com/Documentation/user-review-ui.html#files" rel="nofollow">https://gerrit-review.googlesource.com/Documentation/user-review-ui.html#files</a></p> <p>There's no way to change this behaviour but IMHO this is a very useful information and I can't see any issue with this.</p>
Mocha chai unexpected assertion testing error from object equaling object <p>I'm using Mocha and Chai to do some front end testing and put in the below assertion.</p> <pre><code> it('AddContact returns contact with type = ADD_CONTACT', function () { function hi() {return { type: 'ADD_CONTACT', data: { firstName: 'John', lastName: 'Doe', dateOfBirth: '1/2/89', phone: '123-456-7890', email: 'jdoe@gmail.com', notes: 'Most original name ever' }}} expect(hi()).to.equal({ type: 'ADD_CONTACT', data: { firstName: 'John', lastName: 'Doe', dateOfBirth: '1/2/89', phone: '123-456-7890', email: 'jdoe@gmail.com', notes: 'Most original name ever' } }); }); </code></pre> <p>However, I still get the error: </p> <pre><code> AssertionError: expected { Object (type, data) } to equal { Object (type, data) } + expected - actual </code></pre> <p>What's going on?</p>
<p>You have to use <code>to.deep.equal</code> else you are testing that's the <strong>same</strong> object in memory, not the value.</p>
Pivot SQL by Year <p>Well, there's a lot of references for pivot SQL. But still, I couldn't solve my problem.<br></p> <p>I have the following table:<br></p> <pre><code>----------------------------------------------------------------------- InspectYear PartNo PartDesc A B C D ----------------------------------------------------------------------- 2015 001 Part 1 9 8 8 6 2015 002 Part 2 8 8 8 6 2014 001 Part 1 9 2 8 6 2014 002 Part 2 8 8 8 4 </code></pre> <p>I want to have the following result with dynamic "<code>InspectYear</code>":</p> <pre><code>----------------------------------------------------------------------- PartNo PartDesc NewCol 2014 2015 ----------------------------------------------------------------------- 001 Part 1 A 9 9 001 Part 1 B 2 8 001 Part 1 C 8 8 001 Part 1 D 6 6 002 Part 2 A 8 8 002 Part 2 B 8 8 002 Part 2 C 8 8 002 Part 2 D 4 6 </code></pre> <p>Does anyone have an idea for the pivot query?<br> really appreciated.</p>
<p>Try below dynamic PIVOT:</p> <pre><code>DECLARE @InspectYear AS NVARCHAR(MAX),@Query AS NVARCHAR(MAX); SET @InspectYear = STUFF((SELECT distinct ',' + QUOTENAME(InspectYear) FROM table4 c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') SET @Query = ';WITH data AS ( SELECT InspectYear, PartNo, PartDesc, NewCol, number FROM table4 UNPIVOT ( number FOR NewCol IN (A, B, C,D) ) AS unpvt ) SELECT * FROM data PIVOT ( SUM(number) FOR InspectYear IN ( '+@InspectYear+' ) ) AS pvt ORDER BY PartNo, PartDesc, NewCol ' EXECUTE(@query) </code></pre> <p><strong>Note:</strong> Please refer @doraemon Create table and insert data statement</p>
Canvas Android, how can i do an OnTouchEvent when a bitmap is touched instead of the full screen? <p>I have this function:</p> <pre><code>@Override public boolean onTouchEvent(MotionEvent event1) { if(event1.getAction()==MotionEvent.ACTION_DOWN){ if(!player.getPlaying() &amp;&amp; newGameCreated &amp;&amp; reset) { player.setPlaying(true); player.setUp(true); } if(player.getPlaying()) { if(!started)started = true; reset = false; player.setUp(true); } return true; } if(event1.getAction()==MotionEvent.ACTION_UP) { player.setUp(false); return true; } return super.onTouchEvent(event1); } </code></pre> <p>This function will do it on full screen.<br/> But how do i make it only for when my bitmap is touched?</p>
<p>You could implement the parent layout touch and pass it to your view (where you binded your canvas) as child layout. You could follow as per below :</p> <p>1) Implement parent layout touch event </p> <pre><code>yourparentlayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // this method will pass your parent touch to your canvas parent view canvasparent.dispatchTouchEvent(event); return true; } }); </code></pre> <p>2) Implement onTouch listener to your canvasparent</p> <pre><code>canvasparent.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Rect viewRect = new Rect(); yourimageview.getGlobalVisibleRect(viewRect); if (!viewRect.contains((int) event.getRawX(), (int) event.getRawY())) { Log.d("Touch : "," Touching Outside Of your canvasparent"); }else{ Log.d("Touch : ","Touching Inside Of your canvasparent"); } return false; } }); </code></pre>
await thousands of Tasks <p>I have an application which converts some data often there are 1.000 - 30.000 files.</p> <p>I need to do 3 steps:</p> <ol> <li>copy a File (replace some text in there)</li> <li>Make a Webrequest with WebClient to download a file (I send the copied file to a WebServer, which converts the file to another format)</li> <li>Take the downloaded file and change some of the content</li> </ol> <p>So all three steps include some I/O and I used async/await methods:</p> <pre><code>var tasks = files.Select(async (file) =&gt; { Item item = await createtempFile(file).ConfigureAwait(false); await convert(item).ConfigureAwait(false); await clean(item).ConfigureAwait(false); }).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); </code></pre> <p>I don´t know if this is the best practice, because I create more than thousand tasks. I thought about splitting the three steps like:</p> <pre><code>List&lt;Item&gt; items = new List&lt;Item&gt;(); var tasks = files.Select(async (file) =&gt; { Item item = await createtempFile(file, ext).ConfigureAwait(false); lock(items) items.Add(item); }).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); var tasks = items.Select(async (item) =&gt; { await convert(item, baseAddress, ext).ConfigureAwait(false); }).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); var tasks = items.Select(async (item) =&gt; { await clean(targetFile, item.Doctype, ext).ConfigureAwait(false); }).ToList(); await Task.WhenAll(tasks).ConfigureAwait(false); </code></pre> <p>But that doesn´t seem to be better or faster, because I create 3 times thousands of tasks.</p> <p>Should I throttle the creation of tasks? Like chunks of 100 tasks? Or am I just overthinking it and the creation of thousands of tasks is just fine.</p> <p>The CPU is idling with 2-4% peak, so I thought about too many awaits or context switches.</p> <p>Maybe the WebRequest calls are too many, because the WebServer/WebService can´t handle thousands of Requests simultaneously and I should only throttle the WebRequests?</p> <p>I already increased the .NET maxconnection in the app.config file.</p>
<p>As commenters have correctly noted, you're overthinking it. The .NET runtime has absolutely no problem tracking thousands of tasks.</p> <p>However, you might want to consider using a TPL Dataflow pipeline, which would enable you to easily have different concurrency levels for different operations ("blocks") in your pipeline.</p>
Display data with the same title but different content <p>Let's say if I have a database which contain:</p> <blockquote> <p>ID: 1 | Name: hello | Content1: sample1 | Content2: sample2</p> </blockquote> <p>And I have developed a WSDL webservice which have the result like this:</p> <pre><code>&lt;name&gt; hello &lt;/name&gt; &lt;content1&gt; sample1 &lt;/content1&gt; &lt;content2&gt; sample2 &lt;/content2&gt; </code></pre> <p>I have used <code>KSOAP2</code> to read the data from the webservice.</p> <pre><code>String NAMESPACE = "blablabla"; String METHOD_NAME = "RequestDetails"; String SOAP_ACTION = NAMESPACE + METHOD_NAME; String URL = "blablabla"; try { SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); soapEnvelope.dotNet = false; soapEnvelope.setOutputSoapObject(Request); HttpTransportSE transport = new HttpTransportSE(URL, 1000000); Log.i(TAG, "transport started and completed! "); transport.call(SOAP_ACTION, soapEnvelope); SoapObject resultString = (SoapObject) soapEnvelope.getResponse(); constructor.setName(resultString.get("name").toString()); constructor.setContent1(resultString.get("content1").toString()); constructor.setContent2(resultString.get("content2").toString()); } catch(Exception e) { e.printStackTrace(); } list.add(construct); </code></pre> <p>And now I put this list into a customAdapter. Then, the result will be like:</p> <p>Name Content1 Content2</p> <p>Is there anywhere for me to make the result be like?</p> <p>Name Content1 Name Content2</p> <p>As it is a listview, so i wish to have</p> <p>Name Content1 is position 0.</p> <p>Name Content2 is position 1.</p>
<p>all you need to do is make listview_item_row as name content1 name content2</p> <p>and while adding data to listview just check name and content, ex: </p> <blockquote> <p>if(content2 == null)</p> </blockquote> <p>do not add name for content 2 </p> <blockquote> <p>if(content2 != null)</p> </blockquote> <p>then jsonparsing be like </p> <pre><code>constructor.setName(resultString.get("name").toString()); constructor.setContent1(resultString.get("content1").toString()); constructor.setName(resultString.get("name").toString()); constructor.setContent2(resultString.get("content2").toString()); </code></pre>
cursor loop in PostgreSQL <p>This below code is a cursor in PostgreSQL 9.0. I want to fetch my records by joining more than one table and i am getting JSON data from that join.</p> <p>So I want to loop those records and parse that json using query something like </p> <pre><code>SELECT "Dump"-&gt;'activities-steps'-&gt;0-&gt;'value' as "steps" FROM "ActivitySessionDump" where "Id"=42594321345021288 </code></pre> <p>then i have to get data from this query and insert to some other table like</p> <pre><code>insert to table name (key,value); </code></pre> <p>So i prepared one readonly cursor to achieve this task </p> <pre><code>begin work; DECLARE sessionids INSENSITIVE no scroll CURSOR FOR SELECT asn."Id",asn."UserId",asn."ActivityId",ad."Dump" FROM "ActivitySession" as asn inner join "ActivitySessionDump" as ad on asn."Id"=ad."ActivitySessionId" where asn."CreatedAt" between now() - interval '5 hours' and now() and asn."ActivityId"=1 for read only; ---- i want her loop should start and i will parse a json Dump by executing query-------- --------insert record to another table--------------- ---end loop----------- FETCH next FROM sessionids; CLOSE sessionids; COMMIT WORK; </code></pre> <p>Any help really appreciated.Thanks </p>
<p>Since you cannot loop in SQL, you'll have to use PL/pgSQL, for example with a <code>DO</code> statement.</p> <p>In your case, that could look like this:</p> <pre><code>DO $$DECLARE asn_id ...; asn_userid ...; ... c refcursor; BEGIN /* assign the SQL cursor to the refcursor variable */ c := 'sessionids'; LOOP FETCH c INTO asn_id, asn_userid, ...; IF NOT FOUND THEN EXIT; END IF; /* process the result row */ END LOOP; END;$$; </code></pre> <p>Of course it is a bit awkward to declare a cursor in SQL and use it in PL/pgSQL. It might be better to put the statement in a <code>FOR</code> loop like this:</p> <pre><code>FOR asn_id, asn_userid, ... IN SELECT ... LOOP /* process the result row */ END LOOP; </code></pre> <p>Maybe you could even squeeze the whole thing into a single <code>INSERT</code> statement, that would be most efficient:</p> <pre><code>INSERT INTO ... (SELECT ...); </code></pre>
MongoDB query array and summarize keywords <p>I would like to query the sub-key of an array, extract keywords, and count them. </p> <p>The words that I'd like to extract from are in "Title." When I applied the query filter, it shows that the field I need to query is <code>Reviews.0.Title</code>. But I have at least 200 elements inside the <code>Reviews</code> array. </p> <p>How do I do this?</p> <pre><code>{ "_id" : ObjectId("561c3ccc4c97f053753f1a78"), "Reviews" : [ { "Ratings" : { "CustomerService" : "4", "Overall" : "5" }, "Location" : "San Francisco", "Title" : "“Excellent Location”", "Author" : "JDoe", "ReviewID" : "1", "Date" : "March 30, 2015" }, { "Ratings" : { "CustomerService" : "4", "Overall" : "5" }, "Location" : "Wisconsin", "Title" : "“Great Location!”", "Author" : "John Doe", "ReviewID" : "2", "Date" : "March 27, 2016" } ] } </code></pre> <p>I would like to get the following output: </p> <pre><code>{ "_id" : "Excellent", "value" : 1 } { "_id" : "Great", "value" : 1 } { "_id" : "Location", "value" : 2 } </code></pre>
<p>I managed to find a <code>mapReduce</code> solution that provides a functionality similar to what you are looking for <a href="http://stackoverflow.com/questions/16174591/mongo-count-the-number-of-word-occurences-in-a-set-of-documents">here</a></p> <p>I adjusted that solution and generated the following <code>mapReduce</code> query:</p> <pre><code>db.reviews.mapReduce( // Map function function () { if(this.Reviews) { this.Reviews.forEach(function(review) { if(review["Title"]) { // Remove all punctuation from the review title var titleNoPunctuation = review["Title"].replace(/[^\w\s?.]/g, ""); // Transform all the review titles to lower case and split them into word tokens var titleTokens = titleNoPunctuation.toLowerCase().split(" "); titleTokens.forEach(function(word) { emit(word, 1); }); } }); } }, // Reduce function function (key, values) { var counter = 0; values.forEach(function(value) { counter += value; }); return counter; }, // Output collection { out: "word_count"}); </code></pre> <p>The above query stores its results in a different collection, as specified in the <code>out</code> attribute, in this example <code>word_count</code>.</p> <p>Thus, in order to fetch the result set returned by the <code>mapReduce</code> job, you need to run the following query on the <code>out</code> collection (<code>word_count</code>):</p> <pre><code>&gt; db.word_count.find(); { "_id" : "excellent", "value" : 1 } { "_id" : "great", "value" : 1 } { "_id" : "location", "value" : 2 } </code></pre>
What does '...' in React-Native mean? <p><strong>A piece of react-native code</strong>:</p> <pre><code>enderScene(route, navigator) { let Component = route.component; return ( &lt;Component {...route.params} navigator={navigator}&gt;&lt;/Component&gt; ); } </code></pre> <p>this code returns a Component Object ,</p> <p>But I don't understand this code ---> {...route.params} </p> <h2>Question:</h2> <ol> <li>What is meant by '...' ?</li> <li>Can you tell me what is meant by " {...route.params}" ?</li> </ol>
<p>The '...' is called Spread syntax.</p> <blockquote> <p>The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.</p> </blockquote> <p>Example :</p> <pre><code>var car = ["door", "motor", "wheels"]; var truck = [...car, "something", "biggerthancar"]; // truck = ["door", "motor", "wheels", "something", "biggerthancar"] </code></pre> <p>If you want to know more about spread operator :</p> <p><a href="https://rainsoft.io/how-three-dots-changed-javascript/" rel="nofollow">https://rainsoft.io/how-three-dots-changed-javascript/</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator</a></p>
Excel VBA RemoveDuplicates function with case sensitivity <p>I'm trying to remove some duplicates from selected column, but the function removes all duplicates irrespective of the case. <code>RemoveDuplicates</code> considers lower case, upper case, etc as duplicate. E.g. the function removed <code>CENTRAL</code>, <code>central</code> and <code>Central</code>.</p> <p>I have simply recorded the following code and only changed it a little bit. I need to keep items with different cases and don't want to remove as duplicates.</p> <pre><code>Sub Macro1() ' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+q ' ActiveWorkbook.Sheets(3).Range("A:A").Clear Selection.Copy Sheets("Sheet3").Select Range("A1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("A1").Select Range(Selection, Selection.End(xlDown)).Select Application.CutCopyMode = False Selection.RemoveDuplicates Columns:=1, Header:=xlNo Range("A1").Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Sheets("Sheet2").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True 'Range("B12").Select Selection.End(xlToRight).Select ActiveWorkbook.Sheets(3).Range("A:A").Clear End Sub </code></pre>
<p>Try the following code using a <code>Dictionary</code> to remove duplicates with case sensitivity:</p> <pre><code>Option Explicit Sub Test() RemoveDuplicates Sheet1.Range("A1:A12") End Sub Sub RemoveDuplicates(rngDataColumn As Range) 'assumes rngDataColumn is a column of data Dim dic As Object Dim rngCell As Range Dim varKey As Variant Dim lngCounter As Long 'create dictionary Set dic = CreateObject("Scripting.Dictionary") 'dictionary becomes case sensitive dic.CompareMode = vbBinaryCompare 'iterate range for unique values For Each rngCell In rngDataColumn If Not dic.Exists(rngCell.Value) Then dic.Add Key:=rngCell.Value, Item:=True End If Next rngCell 'clear source range rngDataColumn.ClearContents 'output unique items - with case sensitivity lngCounter = 1 For Each varKey In dic.Keys rngDataColumn(lngCounter, 1).Value = varKey lngCounter = lngCounter + 1 Next varKey End Sub </code></pre> <p>A1:A12 in my test case is as follows:</p> <p><a href="https://i.stack.imgur.com/0V4EN.png" rel="nofollow"><img src="https://i.stack.imgur.com/0V4EN.png" alt="enter image description here"></a></p> <p>So, to update your recorded macro, you could try:</p> <pre><code>Sub Macro1() ' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+q ' ActiveWorkbook.Sheets(3).Range("A:A").Clear Selection.Copy Sheets("Sheet3").Select Range("A1").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("A1").Select Range(Selection, Selection.End(xlDown)).Select Application.CutCopyMode = False 'use the new function here RemoveDuplicates Selection 'Selection.RemoveDuplicates Columns:=1, Header:=xlNo Range("A1").Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy Sheets("Sheet2").Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=True 'Range("B12").Select Selection.End(xlToRight).Select ActiveWorkbook.Sheets(3).Range("A:A").Clear End Sub </code></pre>
Knockoutjs: Split a string into an array of string <p>I'm a newbie in knockout so please forgive my ignorance.</p> <p>This is my knockout.js file:</p> <pre><code>self.names = ko.observable(); // john, mary, jimmy var arrNames= new Array(); arrNames = self.names().toString().split(","); </code></pre> <p>But I'm getting this error:</p> <blockquote> <p>Cannot read property 'toString' of undefined</p> </blockquote> <p>I've tried:</p> <pre><code>self.names().split(","); self.names.split(","); </code></pre> <p>But nothing works. Please help.</p> <p>On related note: How can I split the string into an array based on a comma or linebreak?</p>
<p>You can use computed in order to get recalculable result:</p> <pre><code>self.names = ko.observable(); // john, mary, jimmy self.arrNames = ko.computed(function() { return self.names() &amp;&amp; self.names().split(",") || []; }); </code></pre> <p>Sample usage:</p> <pre><code>var a = self.arrNames() // a = [] self.names("john,mary,jimmy"); var b = self.arrNames() // b = ["john", "mary", "jimmy"] </code></pre>
Cannot convert BinaryReader.PeekChar or ReadChar to String C# <p>Whenever I try to convert <code>BinaryReader</code> <code>PeekChar</code> or <code>ReadChar</code> to string it gives me an error </p> <blockquote> <p>Error 1 'System.IO.BinaryReader.PeekChar()' is a 'method', which is not valid in the given context</p> </blockquote> <p>How do I convert it? Here is my code sample:</p> <pre><code> private void openTextToolStripMenuItem_Click(object sender, EventArgs e) { myPath = textBox3.Text; BinaryReader objBinReader = new BinaryReader(File.Open(myPath, FileMode.Open)); listBox1.Hide(); richTextBox1.Show(); richTextBox1.Text = ""; do { try { richTextBox1.Text = richTextBox1.Text + objBinReader.ReadChar.toString(); } catch { MessageBox.Show(objBinReader.PeekChar.toString()); } } while (objBinReader.PeekChar.toString() != "-1"); objBinReader.Close(); } </code></pre> <p>Thanks in advance!</p>
<p>You are missing the <code>()</code> for the method calls</p> <pre><code>richTextBox1.Text = richTextBox1.Text + objBinReader.ReadChar().ToString(); </code></pre> <p>and</p> <pre><code>objBinReader.PeekChar().ToString() </code></pre>
Best practices for passing data from one angular module to another, in different HTML pages <p>I have an API that manages Lab, now I'm trying to develop a Form Manager, form quotations, orders, etc. Since I will add Metalwork in the future, and for OO principles, I would like to have the Forms separated from the 'Works'. But, say I select several items from the Lab, and want to make a quotation, I should somehow pass them to the Form Manager. Also, the status of the item should be updated once the form is submitted. </p> <p>Solutions:</p> <ol> <li>Storing the data in an intermediate service?</li> <li>Push it to a local (Lab or Form) service? Seems odd, because forms will have to know about lab and vice versa. </li> <li>Pushing to the server via an API into a temporary collection and removing from there once finished?</li> </ol>
<p>I suggest to store the data inside a "model" like <code>.factory()</code> and consume it.</p> <p>Example:</p> <pre><code>/* models.js */ import angular from 'angular'; import User from 'models/User'; const models = angular.module('app.models', []); models .factory('UserModel', User); export default models; /* user.js */ function User (dependencies) { let User; return { setProperties(user), getProperties(User), } } export default User; /* controller 1 */ function Controller1(UserModel) { UserModel.setProperties($scope.model); } export default Controller1; /* controller 2 */ function Controller2(UserModel) { UserModel.getProperties(); } export default Controller2; </code></pre>
Why is `as Date` required for `timeIntervalSince()` with two `NSDate` objects? <p>I have an <code>NSManagedObject</code> object with:</p> <pre><code>@NSManaged public var timestamp: NSDate </code></pre> <p>I needed the time interval between two of these, so I implemented:</p> <pre><code>let interval = next.timestamp.timeIntervalSince(current.timestamp) </code></pre> <p>Why does this result in the following error?</p> <pre><code>'NSDate' is not implicitly convertible to 'Date'; did you mean to use 'as' to explicitly convert? </code></pre> <p>I'm surprised because both <code>next</code> and <code>current</code> are of type <code>NSDate</code>, and <code>timeIntervalSince()</code> is an <code>NSDate</code> method.</p> <p>It's easily fixed by following the suggestion in the error, but I'd like to understand what going on here:</p> <pre><code>let interval = next.timestamp.timeIntervalSince(current.timestamp as Date) </code></pre> <p>In case it matters, this is on Swift 3.0.</p>
<p>Referring to <a href="https://developer.apple.com/reference/foundation/nsdate" rel="nofollow">NSDate Apple Documentation</a>: </p> <blockquote> <p>The Swift overlay to the Foundation framework provides the Date structure, which bridges to the NSDate class. The Date value type offers the same functionality as the NSDate reference type, and the two can be used interchangeably in Swift code that interacts with Objective-C APIs. This behavior is similar to how Swift bridges standard string, numeric, and collection types to their corresponding Foundation classes.</p> </blockquote> <p>If you check <code>timeIntervalSince</code> method signature, it is <code>func timeIntervalSince(_ anotherDate: Date) -&gt; TimeInterval</code>, note that <code>anotherDate</code> date type is <code>Date</code> (not <code>NSDate</code> anymore).</p> <p>For more information about new value types, check <a href="https://github.com/apple/swift-evolution/blob/master/proposals/0069-swift-mutability-for-foundation.md" rel="nofollow">this proposal</a> of mutability and foundation value types, there is a bunch of new value types such as: NSData, NSMutableData -> <em>Data</em>, NSIndexPath -> <em>IndexPath</em>, NSNotification -> <em>Notification</em>...</p>
Using multiple columns as ForeignKey to return in another table <p>I'm new to Django so I make 3 simple tables to return a WishList. The thing is that I want whenever user asks for WishList, his/her <code>user_id</code> is used to make a <code>SELECT</code> query to return his/her own WishList. And I want to get product title and product url from my WishList table. I'm using <code>to_field</code> but with that way I only can get product title back. I don't know much about Django so help me!</p> <h1>Product</h1> <pre><code>class Product(models.Model): class Meta: unique_together = (('id', 'title'),) title = models.CharField(max_length=200, unique=True, help_text='Name of the product') url = models.CharField(max_length=300, default='', help_text='Url of the product') def __str__(self): return 'Product: {}'.format(self.title) </code></pre> <h1>WishList</h1> <pre><code>class WishList(models.Model): class Meta: unique_together = (('user', 'product'),) user = models.ForeignKey(fbuser, on_delete=models.CASCADE, help_text='Facebook user', to_field='user_id') product = models.ForeignKey(Product, to_field='title', db_column='title', on_delete=models.CASCADE) def __str__(self): return 'WishList: {}'.format(self.user) </code></pre>
<p>Django documentation is your friend, <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/" rel="nofollow">read it</a>.</p> <p>Im serious, read the entire <a href="https://docs.djangoproject.com/en/1.10/" rel="nofollow">documentation</a>.</p> <p>Moreover its not a good practice to override to_field to another field different than your model.pk unless you have a really good reason and you know what you are doing (definitely not the case right now).</p> <p>So after you read the docs, you will know that in order to get wishlisht related to a user, you can use the <code>ForeignKey</code> reverse relation to get all related wishlists for a user.</p> <pre><code>user_wishlists = my_user.wishlist_set.all() #Because we know that you want to access the wishlist.products #in order to optimize things (in terms of db queries) #you can add and .select_related('product') #e.g, user_wishlists = my_user.wishlist_set.all().select_related('product') #now follow the wishlist.product foreign key to access the related product for every wishlist for wishlist in user_wishlists: product = wishlist.product print (product.id, product.title, product.url) </code></pre> <p>Now after you read a little bit more of the documentation you will notice that your <code>WishList</code> model is in fact an <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow">intermediate model</a> for a <code>ManyToMany</code> relation between <code>User</code> and his wished products, then you will know that you can define a M2M field between user and products via <code>WishList</code> like so:</p> <pre><code>class FbUser(models.Model): #... wished_products = models.ManyToManyField( Product, through='WishList', through_fields=('user', 'product') ) #and now accessing user wished products would be easy as: user_wished_products = my_user.wished_products.all() for product in user_wished_products: print (product.id, product.title, product.url) </code></pre>
Using o-auth to authentify users on my API <p>I've got a project made of two websites:</p> <ul> <li>The front : A Laravel website without database and logic (just showing static pages and my javascript)</li> <li>The API : A project using Lumen/Dingo API with my endpoints, my database, my logic and my models</li> </ul> <p>I want to allow my front to ask data to my API depending the user.</p> <blockquote> <p>Ex. I want to log the user, retrieve his friends, add some post to his account, etc. (from the Javascript)</p> </blockquote> <p><strong>What is the best solution?</strong></p> <ul> <li>Using an identification per user (using o-auth or JWT)</li> <li>Allow my front project to ask to my API then each javascript call needs to use my front without knowing my API) (In this solution I need to create routes similars to my API's routes)</li> </ul>
<p>Identification per user is always a better solution as the claims can be decided per user, also in future when it is required to provide permissions to access API based on claims or roles, it becomes easy to give information using the claims and amount of access you can give to a specific user. </p> <p>So the way it will work is:</p> <ol> <li><p>There will be identity server which will be containing the list of users in the system, and also the clams and scopes per user.</p></li> <li><p>The API project will trust the identity server, that means any token provided by the identity server can get verified. </p></li> <li><p>Based on the token per user your API app can decide how much information you want to give to the user. </p></li> <li><p>That way in future you can have methods based on roles, claims and users will be provided with only the information that they have access to. </p></li> </ol>
cURL error on whitespace within data field <p>I'm writing a bash script using cURL to call an API. I'm generating some part of the contents transforming strings coming out from other sources. From the db the spaces are replaced with "_SPACE_" string for application reasons. I'm replacing it using</p> <pre><code>ITEM=${M//_SPACE_/ } </code></pre> <p>and then I call cURL as follow:</p> <pre><code>curl ... --data '{"field": "'$ITEM'"}' ... </code></pre> <p>Running the script it returns an exception on curl execution</p> <pre><code>curl: (3) [globbing] unmatched close brace/bracket in column 21 org.codehaus.jackson.JsonParseException: Unexpected end-of-input in VALUE_STRING at [Source: org.apache.catalina.connector.CoyoteInputStream@185ff06c; line: 4, column: 139] </code></pre>
<p>The exception</p> <pre><code>org.codehaus.jackson.JsonParseException: Unexpected end-of-input in VALUE_STRING ... </code></pre> <p>says that your lib from codehouse is not able to parse the data object which is send via curl. i could imagin that your --data '{"field": "'$ITEM'"}' object fails because of the single quotes '$ITEM'. could u send the complete data object or script ? </p>
Why does my result data returned as void* gets broken? <p>I am working in a project with a huge legacy code base and have been trying to re-design parts of it to get away from old c-style code.</p> <p>I've run into a problem and have prepared a short program to explain. </p> <p>The legacy interface I am using needs me to pass a pointer to the result data as void* and I would like to avoid having to change this.</p> <p>The unique_ptr in the example just goes to demonstrate, that in my real code base everything working on the data is using smart pointers to manage memory.</p> <p>My problem is, that the result data gets broken (see last output line / last call to printPayload); everything is 0 at the end, but it doesn't seem to be a problem with converting to the void* and back as shown by the 2nd and 3rd output line.</p> <p>Is this a problem related to temporaries? I don't get it...</p> <p>I hope this kind of problem has relevance for some of you.</p> <pre><code>#include &lt;iostream&gt; #include &lt;memory&gt; struct Payload { long a; int b; int c; Payload() : a(), b(), c() {} Payload(long setA, int setB, int setC) : a(setA), b(setB), c(setC) {} }; void printPayload(const Payload&amp; printThis) { std::cout &lt;&lt; "payload -- a: " &lt;&lt; printThis.a &lt;&lt; " b: " &lt;&lt; printThis.b &lt;&lt; " c: " &lt;&lt; printThis.c &lt;&lt; std::endl; } void doSomething(Payload* sourceData, void* targetData) { if (!sourceData) return; std::unique_ptr&lt;Payload&gt; sourceDataUnique(sourceData); sourceDataUnique-&gt;a = 222; sourceDataUnique-&gt;b = 333; sourceDataUnique-&gt;c = 444; printPayload(*sourceDataUnique); targetData = reinterpret_cast&lt;void*&gt;(sourceDataUnique.release()); printPayload(*(reinterpret_cast&lt;Payload*&gt;(targetData))); } int main(void) { Payload* myPayload = new Payload(14, 8, 1982); Payload myResult; printPayload(*myPayload); doSomething(myPayload, &amp;myResult); printPayload(myResult); } </code></pre> <p>Output:</p> <pre><code>payload -- a: 14 b: 8 c: 1982 payload -- a: 222 b: 333 c: 444 payload -- a: 222 b: 333 c: 444 payload -- a: 0 b: 0 c: 0 </code></pre>
<p><code>targetData</code> is a <em>local</em> variable to <code>doSomething</code>. After you assign an address to it, it goes out of scope.</p> <p>You never actually assign to <code>myResult</code>.</p>
How to make selected alert pop up when selected index was choosen <p>I want to make if selected index in option was choosen then the selected alert is pop up, but I don't know how to do it, here is my JavaScript code:</p> <pre><code>&lt;script&gt; function check1(){ var e= document.getElementById("maske"); var selec= e.options[e.selectedIndex].value; if(document.selec.value==1){ alert("Minta tambahan gaji"); } } </code></pre> <p>My html code:</p> <pre><code>&lt;select name="masalah_keuangan" id="maske"&gt; &lt;option value="1"&gt;Gaji terlalu sedikit&lt;/option&gt; &lt;/select&gt; &lt;button name="button1" onclick="check1();"&gt;Enter&lt;/button&gt; </code></pre> <p>I want if the option value is 1, then the <code>alert("Minta tambahan gaji")</code> pops up</p> <p>How to do it?</p>
<p>Function should be like below</p> <pre><code>function check1(){ var e = document.getElementById("maske"); var selec = e.options[e.selectedIndex].value; if(selec==1){ alert(e.options[e.selectedIndex].text); } } </code></pre>
php shell_exec() command pop out error and permission denied ffmpeg <p>This is the main index.php file where I run my code to generate a video thumbnail with ffmpeg but it has no lucks at all I have been searching online for a lot of solution but nothing comes out i will be very appreciate if you guys can help me out. The shell_exec() keep giving me error</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="index.php" method="POST" enctype="multipart/form-data"&gt; &lt;input type="file" name="file"&gt;&lt;input type="submit" name="submit" value="upload"&gt; &lt;/form&gt; &lt;?php if(isset($_POST['submit'])){ $ffmpeg = "/Users/mac/Documents/ffmpeg/3.1.4/bin/ffmpeg"; $videoFile = $_FILES["file"]["tmp_name"]; $imageFile = "1.jpg"; $size = "320x240"; $getFromSecond = 5; $cmd = "$ffmpeg -i $videoFile -an -ss $getFromSecond -s $size $imageFile 2&gt;&amp;1"; echo shell_exec($cmd); echo shell_exec('whoami'); if(!shell_exec($cmd)){ echo "thumbnail created"; }else{ echo "error creating thumbnail"; } } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>The user which is attempting to run this file does not have the correct permissions (usually <code>www-data</code>). To test this theory, try running with <code>sudo</code>:</p> <pre><code>shell_exec('sudo -u user -p pass -s $ffmpeg -i $videoFile -an -ss $getFromSecond -s $size $imageFile 2&gt;&amp;1'); </code></pre> <p>You could also configure Apache to run your virtual host as a different user other than <code>www-data</code> or change permissions to the files you would like <code>www-data</code> to access:</p> <p><a href="http://unix.stackexchange.com/questions/30879/what-user-should-apache-and-php-be-running-as-what-permissions-should-var-www">http://unix.stackexchange.com/questions/30879/what-user-should-apache-and-php-be-running-as-what-permissions-should-var-www</a></p>
Response status code:: 404 retrofit 2.0 <p>as far as i understand i get this issue because smth wrong with my code, but i can find exectly reason</p> <p>There is my code</p> <pre><code>public class MainActivity extends AppCompatActivity { private MyServerConnection connection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String URL = ...; final Retrofit retrofit = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(GsonConverterFactory.create()) .build(); connection = retrofit.create(MyServerConnection.class); } interface MyServerConnection { @POST("/appreg") Call&lt;JSONObject&gt; postWithJson(@Body JSONObject object); } public void test(View view) { Log.e("TAG", "---!!! TEST !!!---"); final Call&lt;JSONObject&gt; call = connection.postWithJson(getJson()); call.enqueue(new Callback&lt;JSONObject&gt;() { @Override public void onResponse(Call&lt;JSONObject&gt; call, Response&lt;JSONObject&gt; response) { Log.e("Response status code: ", String.valueOf(response.code())); // isSuccess is true if response code =&gt; 200 and &lt;= 300 if (response.isSuccessful()) { Log.e("response body : ", response.body().toString()); } else { try { Log.e("response body error : ", response.errorBody().string()); here i get NULL ---&gt; Log.e("!!!-- response body : ", " " + response.body()); } catch (IOException ignored) { } } } @Override public void onFailure(Call&lt;JSONObject&gt; call, Throwable t) { Log.e("TAG", "---!!! ERROR !!!--- : " + t.getMessage()); } }); } private JSONObject getJson() { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("key", "val"); } catch (JSONException e) { e.printStackTrace(); } return jsonObject; } </code></pre> <p>and i get such error message </p> <pre><code>E/response body error :: &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="content-type" content="text/html; charset=utf-8"&gt; &lt;title&gt;Page not found at /appreg&lt;/title&gt; &lt;meta name="robots" content="NONE,NOARCHIVE"&gt; &lt;style type="text/css"&gt; html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body&gt;div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } table { border:none; border-collapse: collapse; width:100%; } td, th { vertical-align:top; padding:2px 3px; } th { width:12em; text-align:right; color:#666; padding-right:.5em; } #info { background:#f6f6f6; } #info ol { margin: 0.5em 4em; } #info ol li { font-family: monospace; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="summary"&gt; &lt;h1&gt;Page not found &lt;span&gt;(404)&lt;/span&gt;&lt;/h1&gt; &lt;table class="meta"&gt; &lt;tr&gt; &lt;th&gt;Request Method:&lt;/th&gt; &lt;td&gt;POST&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;Request URL:&lt;/th&gt; &lt;td&gt;http://52.58.65.214:3030/appreg&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id="info"&gt; &lt;p&gt; Using the URLconf defined in &lt;code&gt;APIGW.urls&lt;/code&gt;, Django tried these URL patterns, in this order: &lt;/p&gt; &lt;ol&gt; &lt;li&gt; ^gcm/ &lt;/li&gt; &lt;li&gt; ^web/ &lt;/li&gt; &lt;li&gt; ^app/ &lt;/li&gt; &lt;/ol&gt; &lt;p&gt;The current URL, &lt;code&gt;appreg&lt;/code&gt;, didn't match any of these.&lt;/p&gt; &lt;/div&gt; &lt;div id="explanation"&gt; &lt;p&gt; You're seeing this error because you have &lt;code&gt;DEBUG = True&lt;/code&gt; in your Django settings file. Change that to &lt;code&gt;False&lt;/code&gt;, and Django will display a standard 404 page. &lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>it is weird because if i put a URL in browser i retrive standard respond</p> <pre><code>{ "data": null, "service": null, "status": { "code": 1, "description": "An error occurs while processing your request, Please try later or contact our sales department", "status": "success" } } </code></pre> <p>How i can get the same standard message with my app? </p> <p>What am I doing wrong?</p>
<p>Eventually i found the reason in my case due to <code>/</code></p> <p>i put this sing <code>/</code> in <code>.baseUrl(URL)</code> in the end of URL and also i put it in method <code>@POST("/appreg")</code>...</p> <p>When I delete it from method like this <code>@POST("appreg")</code> it begin to work</p>
sed - replace second octet on an IP address <p>I would like to replace the second octet on an IP address using sed:</p> <p>Example:</p> <blockquote> <p>10.<strong>110</strong>.30.11</p> <p>10.<strong>133</strong>.30.11</p> </blockquote> <p>What is the easiest way to perform this task?</p> <p>Thank you</p>
<p>An attempt in pure <code>bash</code>, apart from wonderful <code>awk</code> and <code>sed</code> answers from above.</p> <pre><code> $ IFS="." read -r octet1 _ octet3 octet4 &lt;&lt;&lt;"10.110.30.11" $ octet2=133 $ printf "%s.%s.%s.%s\n" "$octet1" "$octet2" "$octet3" "$octet4" 10.133.30.11 </code></pre>
Edit markers's lat-lng in Google Maps V3 <p>I'm using Google Map DrawingManager to add Markers to map. After a marker is added, it also adds a column into the table below the map. This column has some information about the marker (title, description, lat, lng) and 2 links (Edit and Delete). You can see that on this photo. </p> <p><a href="https://i.stack.imgur.com/f78mN.png" rel="nofollow"><img src="https://i.stack.imgur.com/f78mN.png" alt="enter image description here"></a></p> <p>User can click <code>delete</code> to remove a marker and <code>edit</code> to edit marker's information. I have done <code>delete</code> function but haven't done <code>edit</code> function. I have tried a few solutions but they weren't working. Does anyone have any solution to do this? Thanks in advance.</p> <p>My source code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var $body = $('body'), markers = {}, html = '&lt;tr&gt;' + '&lt;td&gt;&lt;input type="text"&gt;&lt;/td&gt;' + '&lt;td&gt;&lt;input type="text"&gt;&lt;/td&gt;' + '&lt;td&gt;&lt;input type="text" value="" class="marker-lat"&gt;&lt;input type="text" value="" class="marker-lng"&gt;&lt;/td&gt;' + '&lt;td&gt;&lt;a href="#" class="edit-marker"&gt;Edit&lt;/a&gt;&lt;a href="#" class="delete-marker"&gt;Delete&lt;/a&gt;&lt;/td&gt;' + '&lt;/tr&gt;'; initMap(); function initMap() { var myOptions = { center: new google.maps.LatLng(-16.920334, 145.770859), zoom: 12, }; var drawingManager = new google.maps.drawing.DrawingManager({ drawingControl: false, }); var map = new google.maps.Map($('.map')[0], myOptions); google.maps.event.addDomListener(drawingManager, 'markercomplete', function(marker) { var pos = marker.getPosition(), obj = { lat: pos.lat(), lng: pos.lng() }; $('.marker-table').find('tbody').append(html); $('.marker-table').find('.marker-lat:last').val(obj.lat); $('.marker-table').find('.marker-lng:last').val(obj.lng); markers[obj.lat + ':' + obj.lng] = marker; }); google.maps.event.addDomListener(drawingManager, 'polylinecomplete', function(line) { var paths = ''; path = line.getPath(); for (var i = 0; i &lt; path.length; i++) { paths += path.getAt(i) + ";"; } $('.paths').val(paths); }); drawingManager.setMap(map); $body.on('click', '.add-marker', function() { drawingManager.setDrawingMode(google.maps.drawing.OverlayType.MARKER); }); $body.on('click', '.draw-line', function() { drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE); }); $body.on('click', '.delete-marker', function(e) { var $this = $(this), $tr = $this.closest('tr'), lng = $tr.find('.marker-lng').val(), lat = $tr.find('.marker-lat').val(), marker; e.preventDefault(); markers[lat + ':' + lng].setMap(null); $tr.remove(); }); $body.on('click', '.edit-marker', function(e) { var $this = $(this); e.preventDefault(); }); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=drawing"&gt;&lt;/script&gt;&lt;input type="button" value="Add Marker" class="add-marker"&gt; &lt;input type="button" value="Draw a line" class="draw-line"&gt; &lt;div class="map" style="width: 600px; height: 200px;"&gt;&lt;/div&gt; &lt;table class="marker-table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Title&lt;/th&gt; &lt;th&gt;Description&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; &lt;input type="text" class="paths" name="paths"&gt;</code></pre> </div> </div> </p> <p>Here is <a href="https://jsfiddle.net/Lxx5osk8/2/" rel="nofollow">my fiddle</a></p>
<p>I have found out a solution to do this.</p> <p>Instead of using <code>markers[obj.lat + ':' + obj.lng] = marker;</code> to store markers, I use <code>markers[index] = marker;</code> (index is integer number).</p> <p>Here is my change:</p> <pre><code>var index = 0; google.maps.event.addDomListener( drawingManager, 'markercomplete', function( marker ) { var pos = marker.getPosition(); $( '.marker-table' ).find( 'tbody' ).append( html ); $( '.marker-table' ).find( '.marker-lat:last' ).val( pos.lat() ); $( '.marker-table' ).find( '.marker-lng:last' ).val( pos.lng() ); $( '.marker-table' ).find( '.marker-index:last' ).val( index ); markers[index] = marker; index++; } ); $body.on( 'click', '.edit-marker', function( e ) { e.preventDefault(); var $this = $( this ), $tr = $this.closest( 'tr' ), latlng = new google.maps.LatLng($tr.find( '.marker-lat' ).val(), $tr.find( '.marker-lng' ).val()); markers[$tr.find( '.marker-index' ).val()].setPosition(latlng); } ); </code></pre>
Bad practise? Take row by username, then do validations if passwords match and then add to session? <pre><code>$user = \App\User::where("name", $req-&gt;us)-&gt;firstOrFail(); </code></pre> <p>then:</p> <pre><code>if(Hash::check($plain_text_password, $user-&gt;password)){ //add user to session } else{ //bad credentials } </code></pre> <p>I'm aware of other methods available in Laravel, I'm asking about this specific situation.</p>
<p>There are two approaches.</p> <p><strong>Approach 1.</strong> You can add both username password in the where condition.</p> <p>If the username and password not matching, The error message will be like "Invalid Username and password"</p> <p><strong>Approach 2.</strong> (Your approach). Get the user record from the user table using <code>where("name", $req-&gt;us)</code> and validate the password <code>if(Hash::check($user-&gt;password, $user-&gt;password))</code>. The advantage in this approach is you can show the error message like below.</p> <ul> <li>If the username is not in the table, you can display error like "Invalid Username".</li> <li>If the password is not matching, you can display error like "Invalid Password".</li> </ul> <p>You can use any approach and from a security perspective you can go with the approach 1. </p>
facebook og meta tag duplicated title <p>I have a problem sharing in facebook. I think i have correctly og:meta title but facebook duplicate title.</p> <p>This is the link:</p> <p><a href="https://developers.facebook.com/tools/debug/sharing/?q=http%3A%2F%2Fwww.pisos.afys.cat%2Fvivienda%2Fesgl%25C3%25A8sia%2Fplanta-baja_en_sant-joan-de-vilatorrada_4290167.3377.html%23f" rel="nofollow">https://developers.facebook.com/tools/debug/sharing/?q=http%3A%2F%2Fwww.pisos.afys.cat%2Fvivienda%2Fesgl%25C3%25A8sia%2Fplanta-baja_en_sant-joan-de-vilatorrada_4290167.3377.html%23f</a></p> <p>Can anyone help me?</p> <p>Thx :)</p>
<p>After a re-scrape, debug tool shows the following message:</p> <blockquote> <p>Object at URL <code>http://www.pisos.afys.cat/vivienda/esgl%C3%A8sia/planta-baja_en_sant-joan-de-vilatorrada_4290167.3377.html#f</code> of type <code>website</code> is invalid because the given value <code>494641230470</code> for property <code>fb:admins</code> could not be parsed as type <code>fbid</code>.</p> </blockquote> <p><code>494641230470</code> is the id of a Facebook page, not of a user profile. Pages can not moderate comments.</p> <p>Fix this error first, and after that re-scrape again, to update Facebook's cache of your page.</p>
UITabBarController's viewControllers, the second one is loaded before the first one <p>I'm working with an App and its rootViewController is <code>UITabBarController</code>. I assigned <code>UITabBarController's</code> <code>viewController</code> with NewsViewController(index = 0), MusicViewController(index = 1) and WeatherViewController(index = 2).</p> <p>This app seems working correctly. However, when the App was launched, I noticed that MusicViewController's viewDidLoad method was invoked before NewsViewController's viewDidLoad, viewWillAppear and viewDidAppear methods. From my point of view, only NewsViewController's lifecycle methods should be called. </p> <p>I just cannot understand why viewDidLoad method of MusicViewController(index = 1) is called when the app was launched.</p> <p>Thanks for any info.</p>
<p>when you are using <code>UITabBarViewController</code> keep in mind that:</p> <p>first thing will be load is the <code>UITabBarViewController</code>, then it will load the first 3 view controllers from where you are standing.</p> <p>for example if you are in index 0 it will load view controllers in index 0,1,2.</p> <p>then when you go to index 1 it will load view controllers in 1,2,3 and so on.</p> <p>How `UITabBarViewController is working with you right now is the normal behavior for it.</p> <p>Hope this answer is your question.</p>
How to use java object as a key In JSON? <p>Hi I have a Java Class like,</p> <pre><code>// code class A{ private int i; private String j; // getters/setters } </code></pre> <p>I want to use this object as a map key in my json, how i can do this? e.g : i want something like - {javaObject:value}</p>
<p>In that case when you want to convert object to json, use this <a href="http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html" rel="nofollow">link</a>. Gson can be used to do that.</p>
How can i convert string to date with some strange format <p>I am getting some strange date format as string from server<br> <code>2016-10-03T17:28:34.773</code><br> Which format I need to use to convert this string to date.</p>
<p>You can use this function to get date from your string.</p> <pre><code> - (NSDate *) dateFromServerAttributeDateFormat:(NSString *)dateString { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"]; [dateFormatter setLocale:[NSLocale currentLocale]]; if (!dateString.length){ return nil; } else return [dateFormatter dateFromString:dateString]; } </code></pre> <p>in swift </p> <pre><code> func dateFromServerString(dateString:String) -&gt; NSDate { let dateFormater = NSDateFormatter() dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS" dateFormater.locale = NSLocale.currentLocale() return dateFormater.dateFromString(dateString)! } </code></pre>
Removing leading spaces on Pascals Triangle <p>I have some example code below to print Pascals Triangle. (I am using the test case = 14 on scanner) The code works, but there are leading spaces in the result. How do I remove these spaces in front of the triangle?</p> <pre><code>import java.util.Scanner; public class PascalsTriangle { public static void main(String[] args) { Scanner input = new Scanner(System.in); int rows = input.nextInt(); for(int i = 0;i&lt;rows;i++) { int pascal = 1; System.out.format("%"+(rows-i)*2+"s","");) for(int j=0;j&lt;=i;j++) { System.out.format("%4d", pascal); pascal = pascal* (i - j) / (j + 1); } System.out.println(); } } } </code></pre>
<p>I think what is happening is you are outputting your numbers in 4 char 'blocks' this line looks after that part;</p> <pre><code>String output = String.format("%4d", number); </code></pre> <p>The following would output the number to the left of the 'box' - Although the whitespace would now be trailing.</p> <pre><code>String output = String.format("%-4d", number); </code></pre> <p>It all depends on what the maximum value of n you are going to use. For example, you can decide that each number will take 4 characters (if all the numbers are 9999 or less--actually, with Pascal's triangle with 20 rows, you'll need at least 5 characters). Then you'll need to adjust the number of spaces you print out in each row of the triangle.</p>
get count of data from previous 12 months start with sysdate <p>I am having scenario like this : I have table has date field.like</p> <pre><code>id | date |name | 1 |1/12/2012 |new | 1 |1/12/2012 |renew | 1 |1/09/2012 |new | 1 |1/12/2012 |renew | </code></pre> <p>i need to get count like |</p> <pre><code> name |Jan-12| Feb-12 | Mar-12| ....... |Dec-12| |new |0 | 0 | ............... |1 | |renew|0 | 0 | ............... |2 | </code></pre> <p>if i give todays date in where condition count need to display for last 12 months monthly wise.</p> <p>please give me some solution.</p>
<p>You would get the results that you have shown as row (one row for each month) rather than columns.</p> <pre><code>Select to_char(YOUR_DATE, 'YYYY-MM'), count(id) FROM table_name a WHERE YOUR_DATE BETWEEN ADD_MONTHS(SYSDATE, -12) AND SYSDATE GRoup by to_char(YOUR_DATE, 'YYYY-MM') order by 1; </code></pre> <p>Something like below:-</p> <pre><code>2015-10 79 2015-11 223 2015-12 193 2016-01 182 </code></pre> <p><strong>Using PIVOT:-</strong></p> <pre><code>Select * FROM (Select to_char(YOUR_DATE, 'YYYY-MM') AS "TDATE" FROM table_name a WHERE YOUR_DATE BETWEEN ADD_MONTHS(SYSDATE, -12) AND SYSDATE) PIVOT ( count (TDATE) for (TDATE) IN ('2015-10', '2015-11', '2015-12', '2016-01', '2016-02', '2016-03','2016-04','2016-05','2016-06''2016-07','2016-08','2016-09', '2016-10')); </code></pre> <p>Please note that the IN clause is mandatory and it needs to be present for column headings.</p>
SLURM how to get CPUids and max memory of current job <p>i am working with slurm and i want to find out the cpu_ids and max memory my current process is allowed to use. Is there a way to figure that out?</p>
<p>Use <code>scontrol show job -d &lt;jobid&gt;</code> and look for <code>CPU_IDs</code> and <code>Mem</code>. The information will be given node per node.</p> <p>From within the process, you can look at the <code>SLURM_MEM_PER_CPU</code> and <code>SBATCH_CPU_BIND_LIST</code> env variables if <code>TaskPlugin=task/affinity</code> is set, or at <code>/proc/self/cgroup</code> if cgroups are used.</p>
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' +HOST <p>I am VERY new to programming and I found this program and APPLY IT BUT I FOUND THESE ERROR (I put error at the end of program), import requests import telnetlib import time import sys</p> <pre><code>import numpy as np import matplotlib import matplotlib.patches as mpatches import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.ticker as plticker USERNAME = 'ubnt' PASSWORD = 'ubnt1' HOST = "192.168.1.220" PORT = 18888 TIMEOUT = 10 FRAME_SPEED = 1 LOGIN_URI = 'http://' + HOST + ':80/login.cgi' #LOGIN_URI = 'https://' + HOST + ':443/login.cgi' def usage(): print ("Usage:+ sys.argv[0] + &lt;live|replay FILENAME&gt;") print ("") print ("Options:") print ("\tlive \t=\tProcess live data from device ") + HOST print ("\treplay FILENAME \t=\tReplay FILENAME") print ("\trecord FILENAME \t=\tMake movie of FILENAME") exit(128) if len(sys.argv) == 2 and sys.argv[1] == 'live': ACTION='live' FILENAME = None elif len(sys.argv) == 3 and sys.argv[1] == 'replay': ACTION='replay' ocessing FRAME_SPEED = 50 elif len(sys.argv) == 3 and sys.argv[1] == 'record': ACTION='record' FILENAME = sys.argv[2] # Stored data processing FRAME_SPEED = 50 else: usage() def parse_get_frame_resp(line): _,vals_raw = line.split(':') vals = map(int, vals_raw.split(',')) frame_nr = vals.pop(0) return(frame_nr, vals) #TODO: Make me dynamic parse from 'SCAN RANGE' response scan_range_begin = 2402000000 scan_range_end = 2497000000 if not FILENAME: print ("Enabling Ubiquiti airView at %s:%s@%s...") %(USERNAME, PASSWORD, HOST) s = requests.session() s.get(LOGIN_URI, verify=False) r = s.post(LOGIN_URI, {"username": USERNAME, "password": PASSWORD, "uri": "airview.cgi? start=1"}, verify=False) if 'Invalid credentials.' in r.text: print ("# CRIT: Username/password invalid!") sys.exit(1) print ("Waiting for device to enter airView modus...") # Allow device a few moments to settle time.sleep(TIMEOUT) print ("Start scanning...") tn = telnetlib.Telnet(HOST, PORT, timeout=TIMEOUT) #tn.set_debuglevel(99) # Storage on unique files outfile = 'output-%s.dat' % int(time.time()) print ("Storing output at '%s'") % outfile fh = open(outfile, 'a') def writeline(cmd): """ Write line to device""" ts = time.time() tn.write(cmd) print (cmd) fh.write("%s\001%s" % (ts, cmd)) return ts def getline(): """Read line from device""" line = tn.read_until("\n") print (line) fh.write("%s\001%s" % (time.time(), line)) return line # Commands needs to have a trailing space if no arguments specified writeline("CONNECT: \n") getline() #writeline("REQUEST RANGE: 2402000000,2407000000\n") # 5 MHz #writeline("REQUEST RANGE: 2402000000,2412000000\n") # 10 MHz #writeline("REQUEST RANGE: 2402000000,2417000000\n") # 15 MHz #writeline("REQUEST RANGE: 2402000000,2422000000\n") # 20 Mhz #writeline("REQUEST RANGE: 2402000000,2477000000\n") # (ch 1-11 - US allocation) #writeline("REQUEST RANGE: 2402000000,2487000000\n") # (ch 1-13 - UK allocation) writeline("REQUEST RANGE: 2402000000,2497000000\n") # (ch 1-14) getline() writeline("START SCAN: \n") getline() print ("Waiting for scan to start...") time.sleep(2) def get_frame(frame): """ Get frame from device airView """ # TODO: Receiving frames in order, sometimes yield of empty responses. Already flush out maybe? #writeline("GET FRAME: %s\n" % frame) ts = writeline("GET FRAME: \n") line = getline() return((ts,) + parse_get_frame_resp(line)) else: # No need for logic since we are processing stored data sh = open(FILENAME, 'r') def get_frame(frame): """ Perform replay data processing """ while True: line = sh.readline() if not line: return(None, None, None) ts_raw, a = line.split('\001', 1) ts = float(ts_raw) cmd, ret = a.split(':', 1) if cmd == 'FRAME': return((ts,) + parse_get_frame_resp(a)) # Get innitial frame number and bins sizes _, frame_nr, vals = get_frame(None) bin_size = len(vals) bin_sample_khz = float(scan_range_end - scan_range_begin) / 1000 / bin_size print ("Bin size: %s") % bin_size # Start making picture fig, ax = plt.subplots(figsize=(20,11)) fig.canvas.set_window_title('UBNT airView Client') ax.set_ylabel('100ms units elapsed') ax.set_xlabel('Frequency (sampled with bins of %s kHz)' % bin_sample_khz) # Channel center frequencies a = [2402,2412,2417,2422,2427,2432,2437,2442,2447,2452,2457,2462,2467,2472,2484,2497] channels = (np.array(a,dtype='float32') - 2402) / (bin_sample_khz / 1000) ax.get_xaxis().set_ticks(channels) plt.xticks(rotation=90) # Plot channel description for i in range(1,15): width_20mhz = 20000.0 / bin_sample_khz if i in [1,6,11,14]: pac = mpatches.Arc([channels[i], 0], width_20mhz, 300, theta2=180, linestyle='solid', linewidth=2, color='black') else: pac = mpatches.Arc([channels[i], 0], width_20mhz, 300, theta2=180, linestyle='dashed', linewidth=2, color='black') ax.add_patch(pac) ax.get_xaxis().set_major_formatter( plticker.FuncFormatter(lambda x, p: format(int((x * bin_sample_khz / 1000) + 2402), ','))) plt.grid(linewidth=2,linestyle='solid',color='black') plt.tight_layout() bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = bbox.width*fig.dpi, bbox.height*fig.dpi print (width), (height) # Initial data and history of amount of pixels of the screen, since it is # important that all lines are draw on the screen. bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = bbox.width*fig.dpi, bbox.height*fig.dpi matrix = np.empty([int(height),bin_size]) * np.nan pcm = ax.pcolorfast(matrix, vmin=-122, vmax=-30) if ACTION == 'record': # Set up formatting for the movie files Writer = animation.writers['ffmpeg'] writer = Writer(fps=15, metadata=dict(artist='AnyWi UBNT airViewer'), bitrate=1800) # # Matplotlib Animation # def update(data): global frame_nr, matrix # Fast forwarding in time for i in range(FRAME_SPEED): frame_nr_next = -1 # The same frame (duplicated), we are too fast while frame_nr_next &lt;= frame_nr: ts, frame_nr_next, row = get_frame(frame_nr + 1) frame_nr = frame_nr_next # We are on the end of the file if not ts and not frame_nr and not row: return #matrix = np.vstack([row, pcm.get_array()[:-1]]) matrix = np.vstack([row, matrix[:-1]]) pcm.set_array(matrix) ax.set_title('Frame %s at %s' % (frame_nr,time.asctime(time.localtime(ts)))) #fig.canvas.draw() ani = animation.FuncAnimation(fig, update, interval=100) # Dual display and recording data does not seems to work, use a screencast # program like gtk-recordmydesktop for that matter if ACTION == 'record': ani.save('live.mp4' if not FILENAME else FILENAME.rsplit('.',1)[0] + '.mp4', writer=writer) else: plt.show() # # Takes some time (10 seconds) for device to return to an active state # error output Usage:+ sys.argv[0] + &lt;live|replay FILENAME&gt; Options: live = Process live data from device Traceback (most recent call last): File "C:\Users\ABDULHUSSEIN\Desktop\py-ubnt-airviewer-master\airviewer.py", line 76, in &lt;module&gt; usage() File "C:\Users\ABDULHUSSEIN\Desktop\py-ubnt-airviewer-master\airviewer.py", line 58, in usage print ("\tlive \t=\tProcess live data from device ") + HOST TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' </code></pre> <p>Any one pls can help me????</p>
<p>it should be <code>print ("\tlive \t=\tProcess live data from device ",HOST)</code> not <code>print ("\tlive \t=\tProcess live data from device ") + HOST</code></p>
The notification sound does not want to shut down by hardware key <p>"I'm making iOS alarm application.</p> <p>currently it's proceeded through UILocalNotification.</p> <p>but when alarming on scheduled time, I want to stop alarming only in the application. app is backgrounded. generally when alarming through UILocalNotification, it's possible to kill the alarm sound as hardware key. what should I do? </p> <p>help ~~ </p>
<p>There's no published way currently to handle this. You can make this using any private API's like <a href="http://sharkfood.com/content/Developers/content/Sound%20Switch/" rel="nofollow">Sound Switch</a>. Apple will not accept your app in AppStore. </p>
Azure deployment source not showing private repository from BitBucket <p>I have a private repository hosted on BitBucket. On Azure I have created a web app and in the app service I want to set a deployment source to my BitBucket instance.</p> <p>The authorization was ok, but when I want to select a project, the list shows no results.</p> <p>What can be the issue here ?</p> <p><strong>Update</strong>: it looks like an authorization issue, because when opening the list of branches using the rest api, i get a forbidden result: <a href="https://bitbucket.org/api/1.0/repositories/" rel="nofollow">https://bitbucket.org/api/1.0/repositories/</a>{org}/{repo}/branches</p> <p>When the admin of my repo is available I'll ask for admin permission and update this post.</p>
<p>It was a permission issue. To have deployment source attached to a BitBucket instance, you need admin rights on the repository.</p>
send Data to controller from Jquery. MVC C# <p>my jquery script code part , the script is working fine and set data array/object in dataBLL..</p> <pre><code>var dataBLL = []; $('#mytable tr').each(function (i) { dataBLL.push({ id: $(this).find('td:eq(0)').text(), ctype: $(this).find('td:eq(1)').text(), cpath: $(this).find('td:eq(2)').text(), ckey: $(this).find('td:eq(3)').text(), ckey: $(this).find('td:eq(4) input:frist').val(), }); $.ajax ({ url:"User/BllBtn", type:"POST", data:"dataBll="JSON.stringify(dataBLL); dataType: "json", success: function (e) { alert("sucess"); }}) </code></pre> <p>but i am not able to send this object/Array to my controller to use it's data and iterate through each row entry .</p> <p>My controller signature </p> <pre><code>[HttpPost] public ActionResutl BllBtn(List&lt;string&gt; dataBll) { } </code></pre> <p>Please guide how to get this object as list so I can loop into in simplest way.</p>
<p>You've got a syntax error (which your browser console will have told you), and also you're producing invalid JSON. </p> <p><code>data: { "dataBll": dataBLL }</code> </p> <p>should work I think. Or</p> <p><code>data: JSON.stringify({ "dataBll": dataBLL })</code></p> <p>at worst. Also set </p> <p><code>contentType: 'application/json; charset=UTF-8'</code></p> <p>as another option in the ajax call. </p> <p>The next problem is you are trying to accept <code>List&lt;string&gt;</code> into your method, but <code>dataBll</code> is a complex object with the following properties:</p> <p><code>id, ctype, cpath, ckey, ckey</code></p> <p>Firstly, you can't define ckey twice in the same object, and secondly your JSON object is incompatible with the type in the C# method. You need to define a class, e.g.</p> <pre><code>public class myNewType { public string id {get; set; } public string ctype {get; set; } public string cpath {get; set; } public string ckey {get; set; } } </code></pre> <p>and then accept <code>List&lt;myNewType&gt;</code> as the parameter to the method:</p> <pre><code>public ActionResult BllBtn(List&lt;myNewType&gt; dataBll) </code></pre>
Unpredictable output from Excel Index-Match <p>I'm trying to do what should be a simple enough task: find the index of the last cell in an array that matches a certain value.</p> <p>I am using a MATCH-INDEX function combination that is giving me incorrect, inconsistent results. I can't figure out the problem.</p> <p>In this example I'm using an array with values of 1 or -1 and trying to find the index of the last 1 in the array.</p> <p><a href="https://i.stack.imgur.com/i5jA8.png" rel="nofollow"><img src="https://i.stack.imgur.com/i5jA8.png" alt="Photo of index-match results"></a></p> <p>My understanding is (and using the Evaluate Formula tool confirms), INDEX(A1:F1=1,0) should return an array of</p> <pre><code>{FALSE,TRUE,FALSE,TRUE,FALSE,FALSE} </code></pre> <p>Why does the MATCH(TRUE,...) not give a result of 4 when it is fed this index array? MATCH works backwards in the array and should return the index of the last match, which is the TRUE value in the 4th position.</p> <p>But here this code is giving a result of 6.</p> <p>To make matters worse, if I use the same code but change around the array fed into INDEX, the results are inconsistent. When I'm changing array values to 1 or -1, sometimes the formula result changes and sometimes it doesn't, and I can't figure out why.</p> <p>Below, changing only the 3rd array value changes the result of the formula from 4 to 6. WHAT IS GOING ON?!</p> <p><a href="https://i.stack.imgur.com/SrrjI.png" rel="nofollow"><img src="https://i.stack.imgur.com/SrrjI.png" alt="Photo of index-match results (2nd array configuration)"></a></p>
<p>It seems that match only finds first, but not last.</p> <p>But I have a possible solution, I would do it the following way:</p> <p>expect: your values are between H4 AND H27, the value you look for is "39"</p> <p>1: find the rownum for all matching cells</p> <blockquote> <p>I4 --> I27: IF(H4 = 39; ROW(H4); -1)</p> </blockquote> <p>2: find the max rownum in I4 --> I27</p> <blockquote> <p>MAX(....)</p> </blockquote> <p>3: subtract the rownum of first cell (zero- based index)</p> <blockquote> <p>MAX(....) - ROW(H4)</p> </blockquote> <p>4: to get it in only one cell put into a Matrix function (CONTROL SHIFT ENTER makes CURLY BRACKETS)</p> <blockquote> <p>{=MAX(IF($H$4:$H$27=39;ROW(H4:H27);-1))-ROW(H4)}</p> </blockquote> <p>sounds strange, but works :)</p>
Path to RouteValueDictionary in Asp.Net Core <p>I need to extract the route data (Controller, Action etc) from an <strong>arbitrary</strong> request path (<strong>not</strong> related to the current request) such as <em>/</em> or <em>/account/manage</em>. In previous versions of Asp.Net Mvc this could be accomplished like this:</p> <pre><code>var request = new HttpRequest(null, "http://localhost:3333/Home/About", "testvalue=1"); var response = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(request, response); var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); var values = routeData.Values; // The following should be true for initial version of mvc app. values["controller"] == "Home" values["action"] == "Index" </code></pre> <p><a href="http://stackoverflow.com/a/1831825/88513">Source</a></p> <p>This solution is not optimal since it requires a fully qualified Url instead of just a request path. </p>
<p>You can use <code>TemplateMatcher</code> to extract route values:</p> <pre><code>public class RouteMatcher { public static RouteValueDictionary Match(string routeTemplate, string requestPath) { var template = TemplateParser.Parse(routeTemplate); var matcher = new TemplateMatcher(template, GetDefaults(template)); var values = new RouteValueDictionary(); var moduleMatch = matcher.TryMatch(requestPath, values); return values; } // This method extracts the default argument values from the template. private static RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate) { var result = new RouteValueDictionary(); foreach (var parameter in parsedTemplate.Parameters) { if (parameter.DefaultValue != null) { result.Add(parameter.Name, parameter.DefaultValue); } } return result; } } </code></pre> <p>And example usage:</p> <pre><code>var template = "{controller=Home}/{action=Index}/{id?}"; var routeValues = RouteMatcher.Match(template, "&lt;your path&gt;"); </code></pre> <p>See this article: <a href="https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/" rel="nofollow">https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/</a></p>
What is the difference between the two css selectors [class^=test] vs [class|=test] <p>These two <code>[class^=test]</code> and <code>[class|=test]</code> matches the same elements as I see.</p> <p>Is there any real difference or case why should I use one over the other?</p>
<pre><code>[class^="test"] </code></pre> <p>The above selects all elements that <strong>starts with class</strong> "test", it will fail to find if the test is second class.</p> <p>But:</p> <pre><code>[class|="test"] </code></pre> <p>finding elements that matches class, won't show you if the class is "testing" but will find if the class is "test-ing", the above one will match both. Also , it will fail to find if the test is second class.</p> <pre><code>[class|="test-"] </code></pre> <p>And this case will only accept "test-" and won't accept "test-ing" or a string which starts with "test-", e.g., "test-ing".</p>
PHP user rating based on post and read count <p>Im trying to get user stars based on their post and read count.</p> <ol> <li>0 post, 0 reads – 0 stars </li> <li>3 post, 3,000 reads – 1 star </li> <li>15 post, 15,000 reads – 2 star </li> <li>25 post, 30,000 reads – 3 star</li> <li>35 post, 40,000 reads – 4 star</li> <li>50 post, 70,000 reads – 5 star</li> </ol> <p>code: <pre><code>$read = 15000; $news = 13; if($read &lt; 3000 || $news &lt; 3){ echo '0'; } else if(($read &gt;= 3000 &amp; $news &gt;= 3) &amp;&amp; ($read &lt; 15000 &amp; $news &lt; 15)){ echo '1'; } else if(($read &gt;= 15000 &amp; $news &gt;= 15) &amp;&amp; ($read &lt; 30000 &amp; $news &lt; 25)){ echo '2'; } else if(($read &gt;= 30000 &amp; $news &gt;= 25) &amp;&amp; ($read &lt; 40000 &amp; $news &lt; 35)){ echo '3'; } else if(($read &gt;= 40000 &amp; $news &gt;= 35) &amp;&amp; ($read &lt; 70000 &amp; $news &lt; 50)){ echo '4'; } else if($read &gt;= 70000 &amp; $news &gt;= 50){ echo '5'; } </code></pre> <p>this does not work well..</p>
<p>check this,</p> <pre><code>&lt;?php $read = 50; $post = 44; if($post &gt;= 50 &amp;&amp; $read &gt;= 70000){ echo "5 stars"; }else if($post &gt;= 35 &amp;&amp; $read &gt;= 40000){ echo "4 stars"; }else if($post &gt;= 25 &amp;&amp; $read &gt;= 30000){ echo "3 stars"; }else if($post &gt;= 15 &amp;&amp; $read &gt;= 15000){ echo "2 stars"; }else if($post &gt;= 3 &amp;&amp; $read &gt;= 3000){ echo "1 stars"; }else{ echo "0 stars"; } ?&gt; </code></pre>