Why does it take seconds to obtain IP address via DHCP?

Question: Out of curiosity, why does it often take seconds to obtain network configuration via DHCP when the CPU is capable of processing millions of operations per second and ping to the router takes a couple of milliseconds?
In my home environment with one WiFi router and about 5 devices, it is not rare to see times like 5-10 seconds.
Answer: In addition to the actual acquisition of the DHCP lease from the DHCP server (which typically doesn't take very long), some servers will first ping the IP address it's about to hand out before it actually hands it out to verify that it's not already in use on the network - this takes a few seconds to time out. The client sometimes will do the same (again, to prevent IP address conflicts) which will add some more time. Then, on top of that, some clients will also register their DNS entries etc.
Comment: The dhcp server at my work uses ARP requests to detect IP conflicts.
Answer: DHCP might take a bit longer time because it involves a series of transactions, not with a single server but with all the devices on the network during the initial request, as it sends a broadcast message.
If you check the RFC for DHCP,
http://www.faqs.org/rfcs/rfc2131.html
you can clearly see the the series of negotiations involves. At the beginning the client sends DHCPDISCOVER to all the devices on the LAN, then the servers running dhcp service return DHCPOFFER message. The client might also wait to get responses from all available dhcp servers before it picks one. Then it sends a DHCPREQUEST with an identifier which indicates which server it has chosen as its ip provider. Finally it gets DHCPACK with all the configuration parameters. This is just a summary of the "3.1 Client-server interaction - allocating a network address" from the RFC.
From my experience dhcp takes long time mainly in large LAN setting with lots of nodes connected. In a homenetwork with just a single dhcp server(WIFI router for instance) and one or two pcs, it is pretty fast.
Comment: In my home network with one WiFi router and about 5 devices, it takes about 5-10 seconds which I consider quite slow. But thanks for the explanation.
Comment: make sure you have a single dhcp server. If it is just 5 devices, you might want to reserve IPs to each device in the dhcp server. But if you are curious enough you can use tcpdump to look at the actual negotiation and see what is the causing the delay.
Comment: Depending on the dhcp server, it can take several seconds regardless of network activity or CPU speed. This is because the server first queries the network to see if an address is in use before it offers it to a client, and it has to wait at least a little while for answers to arrive. This timeout is part of the delay you notice, and it will exist even on the quietest network.
Comment: DHCP does decidedly not involve "transactions with all the devices on the network". A broadcast takes exactly the same time as a direct packet, and is not a transacitonj ina ny sense of the word. This answer is grossly wrong.
Answer: Two reasons (and solutions) I found when I wanted fast replies from my DHCP server.
1) My DHCP did a ping of the address it wanted to allocate.  This added 3 seconds delay.  I removed this by changing the DHCP config to have a mapping for MAC Address to IP address.  This is basically using DHCP to allocate a static address.  This removed the 3 second delay for me.
2) I have an isolated network, however, you may get this at times. There was a DNS look up being done, which for me resulted in many seconds delay from getting an IP Address from DHCP.  In the DHCP server config there were options for our domain and DNS servers.  After removing DNS options and above change I got instant replies from the DHCP server.  (**)
These issues were what I found in my setup.  Your milage may vary.
cheers
LB
(**) If I had a penny for every time a failed DNS lookup caused a delay which resulted in a strange knock on affect which resulted in me scratching my head, I would have many many pennies.
Answer: I don´t know what scenary you have, but in the real world you get the ip address...etc from an old server (dhcp server is always the one with the oldest hardware :) ) with lots of requests, behind a firewall, one or several routers/switches... Latency, cpu power...and in a windows world, dhcp implementation is not as efficient as we would like!.
Comment: Me thinks that you're regurgitating hyperbole gleaned from years of reading too many internet posts. "Microsoft is bad." "Why?" "Because everyone says so."
Comment: "in a windows world, dhcp implementation is not as efficient as we would like!." Do you have any documentation or sources to back up what you said here?
Comment: No, but for example.... Linux provides fail-over DHCP options in a very easy way.
Aside from the builtin Active directory functionality in Windows there´s some other points to consider as potential security problems.
Comment: You can do overlapping DHCP scopes on Windows DHCP servers. With win2k8 R2, apparently, there's a new failover option as well. Maybe Linux is better than that. None of that has anything to do with "efficiency". And what "security problems" in Windows DHCP are you referring to? I asked you for sources, and instead you throw out more claims.
Answer: If you are experiencing performance problems with dhcp;

Check network latency
Look at packet cap dhcp negotiation. You should be able to see what action is taking a long time. (problem may not be with the dhcp server, who is waiting on who?)
Examine dhcp server load and logs.
Comment: It's a home network scenario, I've updated the question.
Comment: ಠ_ಠ Y U NO ASK SUPERUSER THEN?
Comment: Maybe because it's related to networking and here is the best place for this ?
Comment: http://meta.serverfault.com/questions/1049/changing-the-faq-home-networks


Python: just can't add a new line to my file

Question: i know this has been asked so many times, and i tried about 20 different ways to make it work, but my code won't add a new line to my csv file, it just overwrites the first line all the time (the first line is written properly):
        string = str(data["message"]["id"]) + "," + str(data["message"]["date"])
        f = open('myfile.csv', 'w')
        f.write(string)
        f.write("\n")
        f.close()

EDIT : As proposed below, solved by changing 'w' for 'a' in open() command above. So append instead of write.
Comment: Python 3.6 under windows
Comment: Test if your string is actually a  object. Try print(type(string)) and let us know what is it showing. I don't see any other issue with the code.
Answer: You need to open the file in append mode not write mode.
change
f = open('myfile.csv', 'w')

to
f = open('myfile.csv', 'a')


How javascript language is working

Question: i am a new learner on javascript language but i have worked before with other programming language such c#
while i was doing a simple operation on javascript, i was astonished about the results makes me wonder how javascript works and why it is different like that
Example
i had an array of ['a','b'] , i want to reverse it and check is it the same or not

var char = ['a','b'];
var char_reversed = char.reverse();

normally , char should = ['a','b']  and char_revered should = ['b','a']
but i find that char = char_reversed = ['b','a']
Comment: [`reverse()` works in-place](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), what's so hard to understand?
Answer: The reverse function works in place, therefore the original array is modified.
If you do not want to modify the original list, you can refer to the following post.
https://stackoverflow.com/a/30610528/759762
Answer: The reason this works is that char.reverse() operates on the array char. It does not perform the operation and returns a copy of the array, but changes the array itself. The operation var char_reversed = char.reverse() actually is:
char.reverse() // ['b','a']
char_reversed = char

That is why char = char_reversed = ['b','a']
Comment: is this methodology of operating on the variable itself not creating a copy, exist on other methods or is it just the arrays which perform this way
Answer: .reverse() modifies original array.
You can call .slice() first to create a copy of the original array if you are expecting a new array where the elements are literal strings.

var char = ['a','b'];

var char_reversed = char.slice(0).reverse();

console.log(char, char_reversed);
Answer: In JavaScript some methods don't create new reference of your data. It's change your your data within the own memory. For example,
var a = [1, 2, 3];
a.reverse();
console.log (a); // a looks like [3, 2, 1]

a.pop();
console.log (a); // a looks like [3, 2] data changes within the memory.

console.log (a.slice(0, 1)); // output looks like [3]

console.log (a); // a looks like [3, 2]

In slice method that create new memory of your data and modified your new data. So your old data don't change or modified.
Comment: i think you mean the output on using slice looks like [3], but thanks for the explanation it is a great help
Comment: Ohh sorry I don't saw it. I will change it.

How javascript language is working


"i" value in JavaScript for loop is not being recognized in a jquery function

Question: I'm using jQuery and ajax to open a bootstrap modal window.  My code works perfectly when not in a loop, and my content is displayed appropriately in the modal window. But I have five modals on the page, and naturally I'd like to use a for loop so I don't repeat my code five times.
It seems like a no-brainer to write a for loop to execute the code five times, but somehow, there is a problem, and when I put the code into a for loop, the modal content will not show in the opened window.
Here is code that works how I need it, so the modal content from my modal1.php file shows in a modal popup window.  Notice that the i variable is used three times; once in the jQuery selector, and twice in the $.ajax(...) area:
var i = 1;

$('#modal' + i).on('show.bs.modal', function(e) {
    var id = e.relatedTarget.dataset.id;
    $.ajax({
        type:'post',
        url:'modals/modal' + i + '.php',
        data:{id:id},
        success:function(data){
            $('#modal' + i).html(data);
        }
    });
});

This code below uses the variable i the exact same way as the code above.  However, with the code below, the modal1.php content does not show (nor do any of the other files named 'modal[i].php').  Instead, only a blank dark background appears when they are opened.
for (i = 1; i < 6; i++) {
    $('#modal' + i).on('show.bs.modal', function(e) {
        var id = e.relatedTarget.dataset.id;
        $.ajax({
            type:'post',
            url:'modals/modal' + i + '.php',
            data:{id:id},
            success:function(data){
                $('#modal' + i).html(data);
            }
        });
    });
}

So I don't understand why the $.ajax() area of the code won't recognize the i variable in the for condition, but it will recognize it in the initial jQuery selector $('#modal' + i), which I've tested and found to be true.  Is there a way I can write this loop so that the ajax area will recognize the i variable?  Or is there a mistake in my code that I'm overlooking?
Incidentally, I've noticed that similar questions have been asked, but they have been downvoted for not being clearly written.  I've read them all, and they don't answer the question that I have today.
Comment: The issue is that the i is scoped outside the method, so that it will be the value of 6 when the modal logic executes.  You need to make a scoped down variable that is not mutable by the loop.  `forEach` or `$.each()` are good for this, which pass in the index to the callback.
Comment: I agree with @mituw16 . Here's another question that goes in to the same thing. https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
Comment: I _think_ you're running into issues with trying to register your event handler inside of a for loop. Perhaps this might help? https://stackoverflow.com/a/7774659/1729859
Answer: The problem here is that you are (unintentionally) referencing a variable (i) via a closure.
Since scope is dictated by function in JavaScript, wrap your on usage with another (immediately invoked) function so a unique i is saved:
for (i = 1; i < 6; i++) {
    (function() {
        var iModalNumber = i;
        $('#modal' + iModalNumber).on('show.bs.modal', function(e) {
            var id = e.relatedTarget.dataset.id;
            $.ajax({
                type:'post',
                url:'modals/modal' + iModalNumber + '.php',
                data:{id:id},
                success:function(data){
                    $('#modal' + iModalNumber).html(data);
                }
            });
        });
    }());
}

The reason that these questions get down-voted so much is because issues/misunderstanding of closures is so common. It is admittedly a difficult concept to grasp, and your question was well written.
More information: How do JavaScript closures work?
Comment: This article has also been helpful for me, when reviewing the above code:
https://stackoverflow.com/questions/9053842/advanced-javascript-why-is-this-function-wrapped-in-parentheses
Answer: You could probably do this without using loop but using jQuery .each() and adding value attributes to your html elements. Warning... untested code ahead.
    jQuery('.modal').each(function(){               // use a class instead of an id
        $(this).on('show.bs.modal', function(e) {    //use $(this) to target
            var i = $(this).val();                   // get the value id
            var id = e.relatedTarget.dataset.id;    // do your code
            $.ajax({
                type:'post',
                url:'modals/modal' + i + '.php',
                data:{id:id},
                success:function(data){
                    $('#modal' + i).html(data);
                }
            });
        });
    });


Counting on rectangles?

Question: In an array of dots, how many can be colored red without forming a red rectangle?
We use rectangular arrays of dots, and consider only those rectangles with horizontal and vertical
sides. A dot-rectangle is called "red" if its four corners are red. (Other dots can be of any color.)For whole numbers $m, n,$ define $R(m, n)$ to be the largest number of dots in an $m ×n$ array that can be colored red without making a red rectangle. Can you evaluate (with proof) $R(3, 4), R(3, 5), . . . ?$ How about $R(4, 4)$? Eventually, find a general formula for $R(m,n)$ and provide a rigorous proof.
So I think that this is needed to be solved by Ramsey theory and induction but I am having a hard time to find a place to start. I tried a few cases but I am extremely unconfident if those countings are right. Currently I am stuck here and any help will be appreciated( e.g. how to check if I put the maximum red dots in).
About the comment of results, I get 7 for  $R(3, 4)$. My reasoning is basically to fill out 3 spots of a rectangle and left the one blank, while trying to cram those spots together as tight as possible.
Comment: The problem is not asking for a general result. Symmetry considerations together with addition and multiplication rules should suffice for these small cases. You said you tried some cases. Did you try R(3,4)? Why not show your results (with reasoning).
Comment: Also, what makes you think the problem has anything to do with Ramsey Theory? I'm not saying it doesn't, just that I don't see the connection. Is this problem from a book? If so, which book, which chapter?
Comment: Um it is an assignment that my teacher. He is currently teaching about ramsey's theory and I think this is related to it. Also the concept of Ramsey's theory seems evident here( getting maximum stuff put in)?
Comment: Ok, seems reasonable. I take back my doubt concerning the connection.
Comment: R(3,4) = 7 is correct.
Comment: I get $R(m,n)=m+n$ But I dont have the prove...
Comment: I actually kind of get a horrible fake induction but dont think that counts as a legit prove .should I post it?
Comment: Sure, post it, at least you'll get some feedback (from someone) although I'm calling it a night soon.
Comment: Some values: http://oeis.org/A072567
Answer: Partial solution . . .

I'll do the case $R(3,n)$.

Claim: $R(3,n) = 3 + n$, for all $n \ge 3$.

For simplicity of discussion, instead of cells with either red dots or "other" dots, we'll just use cells either containing a dot, or else empty.

First we show $R(3,n) \le 3 + n$, for all  $n \ge 3$.

First, consider the case $n = 3$.

Suppose $R(3,3) > 6$.

Thus, suppose we have a rectangle-free $3\,{\times}\,3$ matrix containing at least $7$ dots. Since we have only $3$ rows, some row must have more than two dots, hence must have $3$ dots (i.e., it's "fully filled"). If any of the other rows contains at least two dots, those two dots together with the corresponding dots in the fully filled row would yield a rectangle. Thus, the two rows other than the fully filled row must each have at most one dot. But then the total number of dots is at most $5$, contradiction.

It follows that $R(3,3) \le 6$.

Next, consider the case $n = 4$.

Suppose $R(3,4) > 7$.

Thus, suppose we have a rectangle-free $3\,{\times}\,4$ matrix containing at least $8$ dots.

Note if a matrix with dots is rectangle free, it's still rectangle free if any of the rows are permuted, or if any of the columns are permuted.

Since we have only $3$ rows, some row must have more than two dots, hence must have at least $3$ dots. By an appropriate permutation of the rows and columns, we can assume the first row has $3$ dots in its first $3$ cells (left to right). The $6$ cells below those $3$ dots can have at most one dot in each row, hence must have one dot in each row, else you can't reach $8$. But then the right-most column must have $3$ dots, which yields two rectangles, contradiction.

It follows that $R(3,4) \le 7$.

Proceed by induction on $n$ . . .

Thus, suppose $R(3,n) \le 3 + n$, for some $n \ge 4$.

Our goal is to show $R(3,n+1) \le 3 + (n + 1) = 4 + n$.

Suppose $A$ is a $3\,{\times}\,(n+1)$ rectangle-free matrix with $d$ dots.

If we delete any column from $A$, the new matrix is a $3\,{\times}\,n$ rectangle-free matrix, hence, by the inductive hypothesis, contains at most $3 + n$ dots.

There are $n + 1$ choices for the deleted column, and in each case, the new matrix contains at most  $3 + n$ dots. If we count the total number of dots in all of these new matrices, the count is at most $(n + 1)(3 + n)$. But for this total, each of the dots in the original matrix $A$ is counted exactly $n$ times, hence
$$d \le  \frac{(n + 1)(3 + n)}{n} = \frac{3}{n} + 4 + n  < 5 + n$$
But $d < 5 + n \implies d \le 4 + n$.

It follows that $R(3,n+1) \le 4 + n$, which completes the induction.

Thus, we've shown $R(3,n) \le 3 + n$, for all  $n \ge 3$.

Next we show $R(3,n) \ge 3 + n$, for all  $n \ge 3$.

It suffices to construct a $3\,{\times}\,n$ matrix with $3 + n$ dots which is rectangle-free (i.e., for which no $4$ dots form a rectangle with horizontal or vertical sides).

Thus, consider the $3\,{\times}\,n$ matrix (stars represent dots)
$$
\begin{bmatrix}
  &  *&   *&  *& \cdots& *\\
*&   *&    &   &           &   \\
*&    &   *&   &           &   \\
\end{bmatrix}
$$
where the first row has dots in all but the first column, and each of the other two rows contains two dots, as shown.

It's clear that the matrix has $3 + n$ dots, and is rectangle-free.

It follows that $R(3,n) \ge 3 + n$, for all  $n \ge 3$.

Combining the results, we have $R(3,n) = 3 + n$, for all $n \ge 3$, as was to be shown.

Notes:

Using a much simpler argument, one can show $R(2,n) = 1 + n$, for all $n \ge 2$.
By arguments similar to those used to determine $R(3,4)$, one can show that $R(4,4) = 9$.
Thus, it might seem reasonable to conjecture that $R(m,n) = (2m - 3)  + n$, for all $n \ge m$.
Unfortunately, based on the link http://oeis.org/A072567 posted by Matthew Conroy, it's clear that the conjecture I proposed above is false. Moreover, it seems likely that no closed form expression for $R(m,n)$ is currently known.
Comment: @Guy who failed everything: Is your teacher asking for a formula for the general case, $R(m,n)$? If so, that kind of suggests that your teacher _knows_ such a formula. If you find out what your teacher thinks the formula is, please post it here.
Comment: Hi, I understand the explanation but how can I apply it to a general formula? My teacher today asks for a general formula and no one answers so I want to give a try.. But still can't approach
Comment: Ok. He told us that it uses sigma instead of using only m or n. I thought your solution is solid and there doesnt appear an error to me... I will try to work this out with you! Thank you for helping me!
Answer: Here are solutions with 14 and 17 dots, respectively, that are optimal for $R(4,8)$ and $R(5,8)$:
$$\begin{bmatrix}
 & & & & &*&*&*\\
 & & &*&*& & &*\\
 & &*& &*& &*& \\
*&*&*&*& &*& &
\end{bmatrix}
~
\begin{bmatrix}
 & & & & &*&*&*\\
 & & &*&*& & &*\\
 &*&*& & & & &*\\
*& &*& &*& &*& \\
*&*& &*& &*& &
\end{bmatrix}$$
Solutions with 12 and 16 dots, respectively, that are optimal for $R(5,5)$ and $R(6,6)$:
$$
\begin{bmatrix}
 & & &*&*\\
 & &*& &*\\
 &*& & &*\\
*& & & &*\\
*&*&*&*&
\end{bmatrix}
~
\begin{bmatrix}
 & & & &*&*\\
 & &*&*& & \\
 &*& &*& &*\\
 &*&*& &*& \\
*& & &*&*& \\
*& &*& & &*
\end{bmatrix}$$
Solutions with 21 and 24 dots, respectively, that are optimal for $R(7,7)$ and $R(8,8)$:
$$\begin{bmatrix}
 & & & &*&*&*\\
 & &*&*& & &*\\
 &*& &*& &*& \\
 &*&*& &*& & \\
*& & &*&*& & \\
*& &*& & &*& \\
*&*& & & & &*
\end{bmatrix}
~
\begin{bmatrix}
 & & & & & &*&*\\
 & & & &*&*& &*\\
 & & &*& &*&*& \\
 & &*& &*& &*& \\
 &*& &*&*& & & \\
 &*&*& & &*& & \\
*& &*&*& & & &*\\
*&*& & & & &*&
\end{bmatrix}$$
Finally, a solution with 29 dots that is optimal for $R(9,9)$:
$$\begin{bmatrix}
 & & & & & &*&*&*\\
 & & & &*&*& & &*\\
 & & &*& &*& &*& \\
 & &*& & &*&*& & \\
 &*& & &*& & &*& \\
 &*&*&*& & & & &*\\
*& & &*&*& &*& & \\
*& &*& & & & &*& \\
*&*& & & &*& & &
\end{bmatrix}$$
All are computed by a program.  The results for $R(n,n)$ are in agreement with A07267.  (Thanks to @MatthewConroy.)
Answer: An approximate solution (for at least part of the domain of $n$) for $R(n,n)$ is:
If $n$ is even then a solution of the form: $n + (n/2-m)(n/2+m)$ (where $0\le m<n/2$) is "close" in the cases listed in A07267. For values of $n: 2\le n \le 8$, then $m=0$ works best. For $n = 10$, then $m=1$, and for $n=12$, then $m=2$.
If $n$ is odd then $n+((n+1)/2+m)(n/2-m)$ is also "close". For values of $n: 1\le n \le 9$, then $m=0$ works best. For $n = 11$, then $n=1$ and for $n=13$ then $m=2$.
As $n$ increases, increasing $m$ yields a better estimate. However I don't have enough data points to determine what relationship between $n$ and $m$ works best.
Comment: Hi, how did you come up with the equations for the solutions?
Comment: Something like: 1) arrange dots in the first several columns so no overlap row-wise, so for $n=3$, two dots in first column, one in second; for $n=4$ that meant 2 in each of first 2. For 5 thru 8, the pattern continues using two columns. At 9 and more it worked better to distribute the first set of dots over more columns (4, 5, 6, 6, 7 for 9-13) again w/o row-wise overlap. 2) Use the remaining columns to distribute the remaining dots. For 3-8, this was 2 in each col, and for 9 and above it approximately $n/2$ dots in each of $n/2$ cols. As n increased tho, the total was too big, hence $m$.

Counting on rectangles？


Using margins to center an icon on a div

Question: I am trying a method of centering an icon using margins.I am giving the icon a width in % and the height in % too.I have
<code>.container{
width:600px;
height:200px;
background-color:orange;
}
img {
width:6%;
margin-left:47%;
margin-right:47%;
height:16%;
margin-top:12%;
margin-bottom:12%;
}
body{

}
</code>
The method centers the icon horizontally but not vertically.I wonder why this wont work
<code>img {
    width:6%;
    margin-left:47%;
    margin-right:47%;
    height:16%;
    margin-top:42%;
    margin-bottom:42%;
    }
</code>
I also have this fiddle but the margin-top and margin-bottom i have used are random http://jsfiddle.net/thiswolf/EKWWt/
Comment: For fixed layout: http://jsfiddle.net/EKWWt/2/
Comment: Using a percentage for `margin-[top|bottom]` will give a margin that is a percentage of the *width* of the element. `margin-[top|bottom]: n%` is not what you want here.
Answer: I can't see your image because of firewall nonsense, but take a look at this answer. Also here is my forked fiddle.
<code>.container{
    width:600px;
    height:200px;
    background-color:orange;
    text-align:center;
    line-height:138px; /*You'll have to play around with this value*/
}

img {
    vertical-align:middle;
}
</code>
Comment: I have that in a fiddle http://jsfiddle.net/thiswolf/HDN4M/ but i am testing it on bootstrap.UPDATE:Works on twitter bootstrap too.
Comment: @Dev I am guessing that the height of the line height and the height of the div have to be the same?
Answer: Try with:
<code>.container{
width:600px;
height:200px;
background-color:orange;
}
img {
margin:12% 50%;
}
</code>
Answer: You could try just placing the icon in as a background instead. If it's a requirement that it be in the html because it's loaded dynamically, then you can use javascript to replace it as a background.
Answer: I think the image is taking margins from the body and not from the container div.
To centre image horizontally and vertically you can set position: relative; in the container div and position: absolute; in img element. This can be one of the possible solution.
So the css can be like this...
<code>.container{
  width:600px;
  height:200px;
  background-color:orange;
    position: relative;
 }
 img {
 width:6%;
 margin-left:47%;
 margin-right:47%;
 height:16%;
 margin-top:42%;
 margin-bottom:42%;
    position: absolute;
}
</code>


New scheduled rule knocks out existing scheduled rule

Question: I have a rule set with an active rule to send mail to a user. This is triggered by a workflow being marked done.
This seems to work just fine until more than one, completely seperate, workflow is marked done.
When I view the scheduling rule set page that shows what's in queue for scheduling I can see the mail that is about to go out from the workflow I marked as done. Now when I go ahead and mark another workflow as done it seems to replace the email that was about to go out to another user from the previous workflow being marked done with the most recent one.
Any ideas as to why I cannot have more than one scheduled rule set in queue at a time?
D6, rules module up to date at v1.5
Answer: Make sure the Identifier for the scheduled task is unique. Adding the node ID of the node that completed the workflow could work to ensure the Identifier field is unique.
A new task will replace an existing task with the same Identifier. This happens because the Identifier value is the key each task is stored with in cron.
Check out this free video Introducing Rules Scheduler for more tips.
Comment: Thanks a lot @Andrew, just after I wrote this question I used some different keywords to search and saw this post also https://drupal.org/node/1022610


Como funciona essa função dentro de for?

Question: var del = document.getElementsByClassName("del");
if (del != null) {
    for (var i=0; i<del.length; i++) {
    (function(i) {
      var id_cliente = del[i].getAttribute('value');
      if (del[i].addEventListener) { del[i].addEventListener("click", function(){confirmaExclusao(id_cliente);}); }
      else if (del[i].attachEvent) { del[i].attachEvent("onclick", function(){confirmaExclusao(id_cliente);} ); }
        }
    )(i);
    }
}

Estou aprendendo a programar, e ao estudar este código que encontrei na internet, para deletar dados no Banco com Javascript e PHP me deparei com algo desconhecido pra mim até então. Dentro do for tem uma function que está entre parenteses, e ao terminar esta função, há a variável i do for entre parenteses >)(i);<

O que isso significa?

Dentro do meu programa, se eu retirar esta variável (i) ou retirar os parenteses da function, a função deixa de funcionar. Mas não consigo entender qual ou quais são os propósitos destes artefatos (função dentro de parenteses e (i)) no código Javascript.
Comment: Está respondido aqui no site mesmo: http://pt.stackoverflow.com/questions/23785/
Comment: Uma forma resumida de dizer oq é isso é: É uma função de auto execução. Ele cria um escopo fechado. Por isso q quando vc remove a variavel 'i' ela gera um erro. A um tempo atrás eu fiz uma pergunta semelhante, tem uns links bacana na minha pergunta e nas respostas. De uma olhada: http://pt.stackoverflow.com/questions/150775/melhor-forma-de-utilizar-module-pattern-em-javascript
Comment: Obrigado galera, ambos me deram uma luz. Mas o que matou minha dúvida de fato foi este artigo que encontrei: https://goo.gl/CYsFsw.
Deixo ai como referência pra quem precisar futuramente.
Grande abraço!
Answer: O que acontece nesse caso é o seguinte:

Dentro do escopo do for existe a variável i, a qual é inicializada em 0 e incrementada com +1 a cada "volta" que ocorre por causa do laço de repetição for
Também dentro do escopo do for é criado uma função anônima que recebe o parâmetro que também foi chamado de i por simples acaso do destino, o qual, poderia se chamar qualquer coisa, poderia ser por exemplo (funciontion(meuParametroMuitoLouco) { ...
A partir daí, a variável i dentro da função anônima passa a ser o parâmetro recebido na função, e não a variável i do for
Sobre o comando entre parêntesis (i) ao final da função anônima o que ele faz é simplesmente executar a função que acabou de ser criada anonimamente passando a variável i criada na declaração do método for

O motivo de você não entender o que acontece é justamente pela escolha dos nomes de variáveis, o que torna muito confusa a separação visual do código, uma alternativa é alterar o nome da variável recebida como parâmetro dentro da função anônima, conforme exemplo abaixo:
(function(indexParaDeletar) {
    var id_cliente = del[indexParaDeletar].getAttribute('value');
    if (del[indexParaDeletar].addEventListener) {
        del[indexParaDeletar].addEventListener("click",
            function() {
                confirmaExclusao(id_cliente);
            }
        );
    } else if (del[indexParaDeletar].attachEvent) {
        del[indexParaDeletar].attachEvent("onclick",
            function() {
                confirmaExclusao(id_cliente);
            }
        );
    }
})(i);

Outra alternativa é criar uma função e simplesmente chamá-la dentro do for, fazendo com que a função não seja anônima, o que tem o benefício de auxiliar no log de erro do console/browser, separar responsabilidades, melhorar legibilidade do código, etc, etc, etc, por exemplo:
function deletar(indexParaDeletar) {
    var id_cliente = del[indexParaDeletar].getAttribute('value');
    if (del[indexParaDeletar].addEventListener) {
        del[indexParaDeletar].addEventListener("click",
            function() {
                confirmaExclusao(id_cliente);
            }
        );
    } else if (del[indexParaDeletar].attachEvent) {
        del[indexParaDeletar].attachEvent("onclick",
            function() {
                confirmaExclusao(id_cliente);
            }
        );
    }
};

var del = document.getElementsByClassName("del");
if (del != null) {
    for (var i=0; i<del.length; i++) {
        deletar(i);
    }
}

Espero ter ajudado.
Comment: Não sei se entendi sua pergunta, mas o objetivo de criar uma função separada, chamando de `deletar`, por exemplo, é justamente que ela não seja anônima, e nem que possua um escopo "fechado" dentro da execução do `for`, fazendo com que não seja reutilizável por outros métodos que estejam no mesmo "nível" do `for`. Sendo assim, função anônima é diferente de escopo fechado. Não sei se respondi tua pergunta. Se eu não consegui responder, consegue perguntar de outra maneira?
Comment: Acabei removendo para não complicar o espaço dos comentários, mas é basicamente o fiddle de exemplo que o @Sergio postou aqui : http://pt.stackoverflow.com/questions/23785/
Comment: Entendi, gostei da resposta do @Sergio, se tu quiser remover essa minha explicação aqui embaixo, pelo mesmo motivo que tu removeu a tua pergunta, por mim tudo bem :)
Answer: O loop for(;;) não tem seu próprio escopo, e por conta disso essa função cria um novo escopo, re-generando o i como argumento.
O argumento i dentro do escopo dessa função permanecerá tendo o mesmo valor, enquanto o valor do i do escopo de fora vai sendo modificado pela ação do loop.
A intenção é poder usar o valor atual do i em escopos de dentro de loop, sem perder o mesmo valor quando esse escopo for executado, por exemplo:
var functions = [];

for (var i = 0; i < 5; ++i)
    (function(i){
        functions.push(function() {
            console.log(i);
        });
    })(i);

for (var fnc of functions)
    fnc();

// 0
// 1
// 2
// 3
// 4


Jquery adicionar e remover atributo não funcionando

Question: Estou tentando criar uma forma de minimizar e maximizar uma DIV. Minimizar funciona, mas o maximizar não.
O que estou fazendo de errado?

$("#chatMinimizar").click(function() {
  $("#chat").attr("style", "height: 45px;");
  $("#chatMinimizar").attr("id", "chatMaximizar");
});

$("#chatMaximizar").click(function() {
  alert("oi");
  $("#chat").removeAttr("style", "height: 45px;");
  $("#chatMaximizar").attr("id", "chatMinimizar");
});
.chat{
    width: 270px;
    height: 400px;
    float: right;
    border: 1px solid #4c4d4d;
    margin-right: 10px;
}
.chat .titulo{
    background-color: #1f2836;
    padding: 7px;
    color: white;
}
#chatEscrita{
    border-top:1px solid black;
    border-left: 0px;
    border-bottom: 0px;
    border-right: 0px;
    background-color: #e4e4e4;
    font-size: 15px;
    padding: 5px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

Cliente

      <input id="chatEscrita" name="msg" class="bg-cinza" style="width: 100%; height: 50px;" autocomplete="off">
      <input type="hidden" id="de" value="2">
      <input type="hidden" id="para" value="1">

Comment: Tente trocar `.click(...)` por `.on("click", ...)`.
Comment: `$("#chat").css("height", "45px");`
Comment: Existe uma diferença entre atributo e propriedade. Raramente é preciso alterar o valor de um atributo.
Comment: Obrigado pela dica, mas o problema é quando clica no minimizar. Quando a janela esta aberta e clica em minimizar, é mudando o ID do campo para **chatMaximizar**, mas não esta reconhecendo esse no ID.
Comment: Nem o simples alert que coloquei para testar executa.
Comment: Pode me judar @bfavaretto?
Comment: Pode me ajudar @AndersonCarlosWoss?
Answer: A forma correta de modificar o css através de Jquery é utilizando a função css.
Logo para minimizar:
$("#chatMinimizar").click(function() {
    $("#chat").css("height", "45px"); //colocar a altura a 45px
}

Se quiser fazer a lógica de voltar a maximizar pelo mesmo botão pode utilizar um if para esse efeito, testando o valor que tem no momento, o que faz com que necessite apenas de um botão:
$("#chatMinimizar").click(function() {
    if ($("#chat").css("height") == "45px"){ //se está minimizado
        $("#chat").css("height", ""); //retira o que tinha, voltando ao inicial
    }
    else { //se maximizado
        $("#chat").css("height", "45px"); //minimiza aplicando 45px
    }
});


Shade Background iOS Popup

Question: I have two specific questions.
Background Info:
-Using MonoTouch (although I can understand some Objective-C)
First, how would I make a view appear that doesn't take up the whole screen (like a popup, but I don't want to use UIAlertView or anything like that).
Also, how would I make the background a little darker (to contrast between the popup and the original view)?
Appreciate any help anyone can give!
Answer: You can't do that by presenting a different view controller. A View controller (along with it's view) always take up the entire screen and even if the view is smaller, the rest of the screen will be filled with black.
What you describe is easy to do with a hidden View (let's name it panelView) inside your parent view. The panelView should have Hidden=true to begin with and then you can show it by changing this attribute, or maybe animate it's Alpha property to show it slowly.
To achieve the effect with the darker background, you could use a background image for panelView. It should have an alpha channel so that around the center the background view shows through, while it is solid in the center where the content is.
Let me know if you need more info, I have implemented this in an app :
http://obliviusapps.files.wordpress.com/2012/01/4.png?w=370&h=

Shade Background iOS Popup


How to change color in Python?

Question: from tkinter import *

def move():
    global x1, y1, dx, dy, flag, n

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360:
        n = 0
        x1, dx, dy = 360, 0, 15

    if y1 > 360:
        n = 1
        y1, dx, dy = 360, -15, 0

    if x1 < 10:
        x1, dx, dy = 10, 0, -15
        n = 2

    if y1 < 10:
        y1, dx, dy = 10, 15, 0
        n = 3

    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

def stop():
    global flag
    flag = 0

def start():
    global flag
    if flag == 0:
        flag = 1
        move()

###

x1, y1 = 10, 10
dx, dy = 15, 0
color = [["white"], ["red"], ["green"], ["blue"]]
n = 0

flag = 0

###

abl1 = Tk()
abl1.title("Animációs gyakorlat Tkinter-rel")

can1 = Canvas(abl1, bg = "dark grey", height = 400, width = 400)
can1.pack(side=LEFT)

oval1 = can1.create_oval(x1, y1, x1 + 30, y1 + 30, fill = color[n])

but1 = Button(abl1, text = "Quit", command = abl1.destroy).pack(side=BOTTOM)
but2 = Button(abl1, text = "Start", command = start).pack()
but3 = Button(abl1, text = "Stop", command = stop).pack()

abl1.mainloop()

When the ball reaches the edge of the square, it has to change color. Now with this list of colors and with ifs it doesn't do anything and I don't know what's wrong. I tried a lot of different variants but did not work either.
Thank you for your help.
Answer: Inside of your x1 > 360 check in move(), n == 1 should be n = 1.
I assume n is the variable you're using as your list index. If so, you need to add the following line before your flag > 0 check at the bottom of move():
can1.itemconfig(oval1, fill=color[n])

That should change the colours like you wanted.
Copy-paste of my version of your move():
def move():
    global x1, y1, dx, dy, flag, n

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360:
        n = 1
        x1, dx, dy = 360, 0, 15

    if y1 > 360:
        n += 2
        y1, dx, dy = 360, -15, 0

    if x1 < 10:
        x1, dx, dy = 10, 0, -15
        n = 2

    if y1 < 10:
        y1, dx, dy = 10, 15, 0
        n = 3

    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    can1.itemconfig(oval1, fill=color[n])

    if flag > 0:
        abl1.after(50, move)

Edit: Jaredp37's answer would definitely be more efficient than mine, since mine tries to change the colour every time the function gets called.
Answer: In your move function you have to set the itemconfig() fill parameter on each iteration.  The call to can1.create_oval() returns an ID for the oval which you can pass into the itemconfig() method as the first argument.  You can then set the fill from there as in the code below.  This is not the most efficient way to code this though.  With all your globals it may be best to make this script into a class.
def move():
    global x1, y1, dx, dy, flag, n

    x1, y1 = x1 + dx, y1 + dy

    if x1 > 360:
        n = 1
        x1, dx, dy = 360, 0, 15
        can1.itemconfig(1, fill=color[n])

    if y1 > 360:
        n = n + 2
        y1, dx, dy = 360, -15, 0
        can1.itemconfig(1, fill=color[n])

    if x1 < 10:
        n = 2
        x1, dx, dy = 10, 0, -15
        can1.itemconfig(1, fill=color[n])

    if y1 < 10:
        n = 3
        y1, dx, dy = 10, 15, 0
        can1.itemconfig(1, fill=color[n])

    can1.coords(oval1, x1, y1, x1 + 30, y1 + 30)

    if flag > 0:
        abl1.after(50, move)

Comment: @req Technically a mix of both of our answers is correct because mine is still being called on every iteration where the given conditional is true. ;)

How to change color in Python?


Prestashop blocklayered + infinite scroll issue

Question: I ran into an issue with Prestashop using infinite scrolling plugin from http://www.infinite-scroll.com/ for more user-friendly pagination of category product list. The problem is when I started using blocklayered for filtration. Somehow infinite scroll doesnt work with blocklayered.
I think the solution lies somewhere in blocklayered.js in function reloadContent (around line 327). I tried to create a new instance of infinite scroll there but wasnt very successful.
Here is the code I have put at the bottom of category page
$('#product_list').infinitescroll({
    navSelector  : "#pagination_bottom",
    nextSelector : "a.next_button_inf",
    itemSelector : "#product_list .row"
});

I will be thankful for any help! :)
P.S.: Im using Presta 1.5+ and InfiniteScroll 1.5+ as well.
Answer: the free version of infinite scroll bar for prestashop available on git hub. try this https://github.com/Prestastrap/infinite-scroll-prestashop


Efficiently iterating a dictionary in Python

Question: So here's the problem, I'm importing a dictionary with anywhere from 6000 to 12000 keys. Then using a nested for algorithm to group them into a list inside of another dictionary. I'm using the following code to check if the key is in the dictionary:
for key in range(sizeOfOriginalKeys):
    if key in key_data:

As you might imagine, this is taking forever since the sorting algorithm is fairly complex. I would like to only iterate through the keys in 'key_data', without doing 1000 to 11999 checks if there is that key in the dictionary. Is there a way to make a list of current keys? Then iterate through them? Or at least something more efficient than what I'm currently doing?
Current Code after Kevin's suggestion:
for key in key_data:
    currentKey = key_data[key].name
    if key_data[currentKey].prefList[currentPref] == currentGroup
        key_data[currentKey].currentScore = getDotProduct()
        group_data[currentGroup].keyList.append(key_data[currentKey])
        group_data[currentGroup].sortKeys()
        del key_data[currentKey]

The key names are integers.
At the end of the sorting algorithm I delete the key, if its been sorted into a group.
Now I get an error: dictionary changed size during iteration.
Thoughts?
Comment: Can you show a bit more of your algorithm's skeleton?
Comment: Sure, one moment. I'll edit my original post.
Comment: key checking in a dict is an O(1) operation, so very cheap - perhaps there are other areas that need to be optimised. Don't delete the item from key_data in the loop, you can't change the dict you are operating over. If you need to know you've handled it then add the key to a handled `set()`
Answer: You're trying too hard:
for key in key_data:

Comment: I could literally kiss you! For legal reasons, I won't.
Comment: Wait, I just ran the code. So, at the end of the algorithm it deletes the key out of the dictionary. Which throws the error: dictionary changed size during iteration. Any way around that?
Comment: @TheNoviceAllen There's no easy way around that - unless you can delay the deletion. If you can, just put the keys you want to delete into a list, and delete everything after the `for`
Comment: @TheNoviceAllen: Alternatively, do `for key in list(key_data)`.
Comment: I created a temp dictionary to handle people getting removed. Though maybe I should try the list, it seems more efficient. I might do that later, right now I'm dealing with a problem where all of the keys aren't getting assigned to a group. Thanks again!
Answer: You can try
for key,value in key_data.items() :
    print key
    print value

you can access to value without calling key_data[key]
Comment: did you forget `.items()`? or possibly `iteritems()`?
Comment: opps! sorry about that


How to build a cluster where users have power to remove/add?

Question: I work in a company where each engineer/scientist has a pretty high end desktop machine.  80% of the time, they are not pumping it to full capacity... This makes me sad.
I want to be able to install some software on each of our machines which should allow any node to use computing resources on the other's machine.
However, each engineer/scientist should be able to take their machines off the cluster to use it as a dedicated workstation.
What software should I look at?
I think this is different from grid computing because tasks aren't determined before hand.
I think this is different from traditional cluster computing because I don't have exclusive access to all the slave nodes.
Thanks!
Every computer is Ubuntu 10.04
Comment: Is the OS among the users the same? Some Linux? Windows? OS X?
Comment: This is exactly what [distributed.net](http://distributed.net/) does (and other distributed computing projects).  I'm sure there must be general purpose tools out there for this sort of thing.
Comment: Is this a mandate from the business or just your own personal desire? Are you responsible for the IT infrastructure at your company? Are you responsible for the engineering/scientific department or the computing resources in the engineering/scientific department?
Comment: my own personal desire.  but yes I could probably convince the company to do it (small startup).
Answer: Check out BOINC — you can set up your own local BOINC server to manage internal jobs, and install (user-controllable) client software on each workstation.  Compatible with Linux, Mac, and Windows.
Answer: The real question is, what problem are you trying to solve?  If you have parallel computing tasks (MPI, hadoop, etc. program) or embarrassingly parallel problem to solve (i.e. rendering frames of a movie) then your software would be specific to that.  If you're just trying to use spare cycles for "some greater good" then distributed.net is a good place to start.
It sounds like you've got a solution without a problem right now, and most companies don't like to spend resources (i.e. setup time, administrative time, etc.) without a clear purpose.


When or why do i utilize the repeated measure design in my analysis?

Question: I know the Repeated measures ANOVA is the equivalent of the one-way ANOVA, but for related, not independent groups but I can't understand. When can I use this design? When one way? And when repeated design?
Answer: Nomen est omen: You have to use repeated measures procedures, if you have multiple observations on the same experimental unit (e.g. proband), just at different time points or places. This happens usually, if there is at least one (fixed) factor like time crossed with the other factors. It is recommended to study the terminology of factorial designs first. Then it is easy to see if an experiment requires repeated measures analysis.
If you don't want to infer anything about the time factor, you can calculate the mean of the time points per subject and do a one-way ANOVA on these means.
Comment: Ok It's right but I guess that We can use anova or block design When we have different subject per any time or condition. It means we need more subject for design.For example 4 subject but by same features for 4(level) time or condition point not one subject for all 4 level of time or condition.
Comment: Yes, in this case you don't have repeated measures. In terms of factorial designs, your example means that the subjects are nested under the time or condition, that means each subject has an observation only at a certain time point. If on the other hand subject and time are crossed, each combination of subject and time exists. These combinations are the repetitions.
Comment: The key question for me is still regarding _"If you don't want to infer anything about the time factor [...]"_ If you do want to infer something about the time factor, wouldn't this imply a possibly totally different design and/or test optimized to test time specifically? Does just because you have multiple measurements justify a repeated measures ANOVA? In my case I take 8 measurements over the course of 50 minutes, however, I do not control fully for the nature of them (they differ slightly). I take 8 measurements exactly because I want to have a meaningful mean. What if I would take 100?
Comment: @StevenJeuris... the design of the model is generally restricted by how you collect your data and the type of data it is. As such, if the dependent variable is measured at different time points on the same experimental unit, then the model will be restricted to some form of repeated measures design. In your case, if the 8 measurements are not taken at the same time for each person, a repeated measures ANOVA cannot account for the differences in timing (but still might work well), but a *mixed model* with time as a random effect might be better suited. Still a repeated measures *mixed model*


Is this untreated major seventh acceptable because of the tonic pedal? (recapitulation of the 1st mov. of Mozart's Piano Sonata nº 7, K.309)

Question: I am referring to the G-F# in m. 123. We are in G major, as I understand, heading to a PAC (m. 126) that will be reinterpreted as a half-cadence when the subordinate theme starts at m. 127.

I am currently understanding that the F#, perhaps in a incomplete D7 harmony, is a leading tone to G, in a incomplete G harmony given by the double-neighbor around B at m. 124 and the following D. For that interpretation, one has to consider that the G in the bass is a tonic pedal. I'm not used to seeing pedal points that brief, even less so with such sharp dissonances (the G-F# really pops out to my ear), hence the discomfort with the current analysis. Is this a common in the classical style? Am I missing something here?
Comment: mm 123 is just a sequence of mm 122 and in fact just continues to mm 124. These are all just extending the cadence and are filler and ellipses. Clearly there is a G pedal and that is to ground the half bar figure that is being tossed around. The figure clearly goes G(on B) then G(on G) then C(onE) then D(onC). It continues in octaves on B and G(essentially repeating mm122) There is nothing out of the ordinary. The F# there is to supply the harmonic color(to imply a D7). The G there is to maintain the tonic ground. All of it is just style. Any number of different things could be done.
Comment: You can have tonic pedals as brief as one chord. E.g., a typical 6/4 chord can be considered a  dominant pedal if preceded by a V. The progression is just a I - IV V I - IV - I - all functioning over a G tonic(why a G tonic, because he wanted it that way, probably to give a strong resolve on the tonic). He could have used the roots of the chord as bass notes instead, it would have worked just as well but that entire last 4 bars is just a tonic tag. There is no understanding "why". He did what he liked and what sounded good to him. Everyone is different.
Comment: Of course the F# in the baritone is important so that we hear a dominant sound so it is a strong color. What is relevant here is the figure being used, not the harmony. The figure being used is what makes it work(it is a sequence that ties everything together). He doesn't go outside harmonic extremes because he wants the feeling of resolution(he's not starting something new he's ending something). If he had too much dissonance then we would want it resolved(well, typically CCP music controls the consonance and dissonance in a typically stylistic way).
Comment: It would probably be more helpful to you as not to try to analyze music based on your preconceived notions of what should and shouldn't be but analyze it as "Oh, you can do that!". Let the "masters" be your guide. most of the time we have our box and we try to fit everything in to it... but, in fact, we should be trying to fit our box in to everything else. (this has the effect of enlarging our box and so we are not so "closed minded") If you want to sound like Mozart then imitate Mozart(copy him, change some things, do it enough and you'll learn to speak his language).
Comment: There is no "logic" to things except the internal logic. *Why* someone did something is irrelevant. Knowing what they did is not. This way if you want to do the same thing you can imitate it and if you don't then you don't. It's best not to get hung up trying to figure out some universal laws because you won't. Only with experience(which takes time and dedication) will you start to develop some deeper understanding of how things work. Trying to force it won't work. [Historically people would learn through apprenticeships but today with our "capitalism" people try to get to the top too fast]
Comment: @Gupta There are some wild guesses there about how I am trying to analyze music and I think they are  related enough to the question as to warrant a response here. I am going to comment on the more relevant issues.
Comment: I am not familiar with the notion of 'fillers', 'ellipses' or 'grounding'. I hardly think it useful to think of a common bass note between two chords as being a pedal, as in the case of a I64-V. I believe that restricting the concept to a context where the bass note lasts for longer and supports more diverse harmonies is more fruitful.
Comment: In the first comment I meant 'and I think they are _not_ related enough to the question as to warrant a response here.
Comment: But that is my point. You are projecting your beliefs of what and how you think things should be to understand them. You can continue doing that but I'm telling you that it will slow down your progress significantly. I speak from experience.  You've learned some theory and are trying to force everything into that theory so you can "understand" them. that is natural but wrong because those things didn't come from those theories. Music theory is not a theory but a descriptive taxonomic language.  Ultimately you get to do what you want...
Comment: I do not agree with your interpretation about how and why I am trying to understand this piece or music in general. But, again, I do not think those are relevant issues to be discussed in the comments of this question.
Answer: Interestingly, the edition I have is like this one...

...apparently the first edition is the one you have. The later editions make the tonic pedal more obvious, at least the F# actually resolving up to G feels more complete.
There is a formula called the "quiescenza" by Robert Gjerdingen which involves a melodic formula of ♭7 ^6 ♮7 ^8 over a tonic pedal, and this seems pretty close to the harmony of this passage.
You can see examples of the quiescenza in Mozart in K.281 and K.283...

...notice the E natural against F and the C# against D.
If the K. 309 example had an F natural in m. 122 leading to the subdominant IV6/4, it would be the complete quiescenza formula.
Comment: Yes, quiescenza is in the book. It's a great book. Took me a while to catch on because Gjerdingen talks a lot about older methods like figured bass, the hexachord system, and earlier forms of solfege. But that's a big part of the book, ditching the current college type Roman numeral analysis and embracing the old methods of the 18th century.
Comment: Interesting indeed! Actually, I am not using a published edition, but a copy of one of the editions, which adds the much needed measure numbers. As the recording I am listening to matched my score, I didn't bother to look for another source.
Comment: I looked at a couple other editions and they all match the one you copied. I wasn't able to find the first edition.
Comment: Thanks for the 'quiescenza' examples. I am planning on reading Music in The Galant Style by Robert Gjerdigen for some time now, I imagine that formula mentioned there.
Answer: I don't think you're missing anything at all; the G is a pedal tone that's dissonant with the chord-tone F♯, exactly as you've surmised.
The G has been a pedal for one-and-a-half measures at this point, and that's relatively common. It's just that this final half note of m. 123 is the first time the G is a non-chord tone: obviously the G is in the G chord of m. 122, and it's the fifth of that C chord in the first half of m. 123.
This tactic of a pedal creating a sharp dissonance is very common in the Classical style, so hopefully your discomfort is short-lived :-)


Every infinite abelian group has at least one element of infinite order?

Question: Is the statement true?

Every infinite abelian group has at least one element of infinite order.

I am searching for an infinite abelian group with all elements having finite order.
Please help me to find such groups.
Answer: Let $G=\{z\in \mathbb{C}:z^n=1$ for some positive integer $n\}$. Then $G$ with complex multiplication is an infinite abelian group but every element has finite order.
Comment: Rather $G=\{e^{2\pi ir} :r\in \mathbb{Q}\}$.
Comment: No, $|G|\not = n$, the $n$ in the definition of $G$ is not fixed. It says "for some $n$". Thus, $\alpha \in G$ and $\beta \in G$, even if $\alpha^3 = 1$ and $\beta^5 = 1$. $G$ consists of all possible such powers you can have.
Comment: |G|=$n$, i think... as it has n soln in $\mathbb C$? is n varying on $\mathbb Z$?
Comment: $G=\{e^{ir}\,|\,r\in\mathbb{Q}\}$
Answer: Take an infinite number of generators, and specify that any element squared is the identity.
Comment: @bof Who said anything about $\mathbb N$? This generates groups of any cardinality with only elements of order $1$ and $2$!
Comment: Or take the set of all finite subsets of $N$ with the operation of symmetric difference, where $N$ is an infinite set.
Answer: Consider $(\mathbb{Q},+)$ and the subgroup $(\mathbb{Z},+)$. Now take the quotient $\mathbb{Q}/\mathbb{Z}$.
Comment: This is isomorphic to your other answer; perhaps it would be better to edit it in there.
Comment: This is the only answer I gave, perhaps you are confusing me with another user.
Comment: Oops, my bad. (The answer I got confused with was the one by alphad, which is indeed isomorphic to this one)
Comment: What is this group?.....I dont understand.
Comment: @yiokk, this is the group of all elements of the form $p/q + \mathbb{Z}$ under addition. Each element has order at most $q$.
Comment: @iHubble If `(p, q) = 1`, it should even be of order exactly `q`.
Answer: Define the set $G$ to be the collection of all functions $f:\mathbb{N}\to \mathbb{Z}/2\mathbb{Z}$. We can then define $f+g$, for any two $f,g\in G$, in the natural way. Define $e$ to be the map such that $e(n) = 0$ for all $n\in \mathbb{N}$. It is not hard to see that $f+f = e$ for all $f\in G$.
Answer: There are many counter examples, some of the more natural ones are:

$( \mathbb{N}, \oplus )$ where $\oplus$ is bitwise Exclusive OR of the binary representations between two natural numbers. Every non-zero numbers has order $2$.
Consider any polynomial rings over any finite field.
If we strip away its multiplication, we get an infinite abelian group with respect to the addition. Every non-zero element has order $p$, the characteristic of the underlying field.
Comment: More precisely, to Meelo's answer *for countable number of generators.*
Comment: "1." is identical to @Meelo's answer and, moreover, is a case of "2." with **F₂** as the ground field.
Answer: As mentioned in various answers it is not true that every infinite abelian group contains an element of infinite order; let me try to structure the examples a bit along a standard distinction.
An abelian group in which every element has finite order is called a torsion abelian group; more generally, the subsets of elements of finite order form a subgroup called the torsion subgroup.
Thus what you are looking for are infinite torsion abelian groups.
A further thing to observe is that even  when the order of each element is finite, it can still happen that there is no common bound for the order of the elements.
This is the case in, e.g., $\mathbb{Q}/\mathbb{Z}$ and $\oplus_{n\in \mathbb{N}^{\ast}} \mathbb{Z}/n\mathbb{Z}$ (note the direct sum, the direct product would not be a torsion group).
A torsion abelian group where there is a common bound for the order of the elements is called a bounded abelian group and the maximal order of an element, which is in fact the least common multiple of all orders, is called the exponent of the group.
There are also examples of infinite bounded abelian groups, such as $(\mathbb{Z}/n\mathbb{Z})^{\mathbb{N}}$ for some positive integer $n$.
Answer: The statement is false
Consider the Power Set of Natural number with group operation of symmetric difference.Then the Group clearly is infinite,abelian,and no element is of infinite order more so each element has order $2$.
Answer: The most natural example to me is $\prod_{n=1}^\infty\mathbb Z_2$, where every element has order $ 2$.
Comment: Notice that this coincides with the example posted by "I Love Mr. Paul".
Comment: And also with achille hui's second example, if the field is $\mathbf{F}_2$. (Of course, every *non-identity* element has order $2$.)
Comment: @fkraiem: the "∏" operation results in **continuum cardinality,** if I remember correctly. The example of Meelo–achille hui has countable cardinality.
Comment: Oh, yes, silly me, a polynomial has only finitely many non-zero coefficients...
Answer: Consider $(\mathbb{F}_p[X],+)$, the polynomial ring over $\mathbb{F}_p$ under addition. This is an abelian infinite group with exponent $p$, which means that $a^p=0$ for every $a \in \mathbb{F}_p[X]$. Since we're looking at "$+$"
$a^p$ is actually $p \cdot a$ in this case.
Notice that this is a stronger property, than "every element has finite order".
Comment: Why to repeat same things for *p* th time where *p* is definitely greater than 1?

Every inﬁnite abelian group has at least one element of inﬁnite order?


Why I can't set PrimeNG p-calenar component CSS style?

Question: I am working on an Angular project using PrimeNG and I am finding the following problem trying to give the correct CSS style to a p-calendar component into my page.
Basically into my HTML code I have something like this:

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'name', 'startsWith')" placeholder="Search by Name" class="p-column-filter">

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'company.name', 'startsWith')" placeholder="Search by Company" class="p-column-filter">

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'company.BU.name', 'startsWith')" placeholder="Search by BU" class="p-column-filter">

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'dettaglio_ordine.commessa.code', 'startsWith')" placeholder="Search by Commessa" class="p-column-filter">

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'dettaglio_ordine.cliente', 'startsWith')" placeholder="Search by Cliente" class="p-column-filter">

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'dettaglio_ordine.cliente_finale', 'startsWith')" placeholder="Search by Cliente Finale" class="p-column-filter">

    <input pInputText type="text" (input)="dt.filter($event.target.value, 'dettaglio_ordine.importo_contratto', 'startsWith')" placeholder="Search by Importo Contratto" class="p-column-filter">

As you can see the second th tag contains this p-calendar component:

I am going crazy trying to set a style for this component. Differently from the other following input tag I am not able to corretly set the style (basically the width and the font size).
I was trying to do as shown here: https://forum.primefaces.org/viewtopic.php?t=2610
So into my CSS code I put:
.dateTimeField {
  width: 80% !important;
}

I also tried to set the styleClass="dateTimeField" on the p-calendar component tag and then set the:
.dateTimeField input {
  width: 80% !important;
}

but it still not working and I obtain this wrong visualization:

As you can see it is too large, it is not taking my CSS settings. The strange thing is that if using the Chrome tools I can set the correct width by:
input.ng-tns-c59-5.dateTimeField.ui-inputtext.ui-widget.ui-state-default.ui-corner-all.ng-star-inserted {
    width: 80% !important;
}

but if I try to copy and paste this CSS settings into the CSS file of my Angular component still not work.
How can I try to fix this issue?
Answer: I believe that the problem is the encapsulation.
You should put your css rules in your global style.css, otherwise
Angular by default will hide the styles of one component to another when view-encapsulation has it's default values in the components.
That's the reason you see the ng-tns-c59-5 inside your dev tools.
See that example: https://stackblitz.com/edit/p-calendar-svpn8n?file=src/styles.css
For more info: https://angular.io/api/core/ViewEncapsulation
Answer: Solved by myself...I put the style related this particular component into the CSS of the specific component global defining it as:
:host ::ng-deep {
  .dateTimeField {
    width: 80% !important;
  }
}

Comment: @StPaulis in any case I accepted your ansewr because I had the inspiration reading it (I am not a real frontender...more a backender...when I read it I undertood the cause of the error and how I fixed something similar in the past
Comment: Didn't the answer above satisfied your needs?
Comment: @StPaulis I used this other way that in some way is based also on your answer... I think that in this way I handle better the CSS style because I want avoid to modify the global style for a style that is related only to a specific component. If you add my solution to your question I will be happy to accept it :-)
Comment: It is OK... I just wanted to know If there was a problem with my solution.
I understand your point of you, you could play with the encapsulation of your component, to avoid `:host` and `::ng-deep` and have your styles inside your component as you want. Thank you for your quick response.


Upload image on TwitPic using Twitter OAuth

Question: I know this may be the repeated question as there are many questions related to this one on SO. I have referred the below ones:
References:
Uploading image on twitter using twitpic
Posting image to twitter using Twitter+OAuth
using TwitPic + OAuth to upload a photo + tweet to Twitter (.NET C#) - why no tweet?
It works fine as an individual. But, in that "OAuth_token" has been used and it is given statically like 3xxxxxx1-KxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxY. So in this case, it will upload an image on the same accout for which this OAuth_token is used.
I have also referred https://github.com/Gurpartap/GSTwitPicEngine.... but in this [_accessToken key] returns NULL.
I want to upload image on currently logged in account. Means, if I logged into another account next time, image must be uploaded on that account.
Problem:
If I give OAuth_token static as specified earlier, then it will upload image on that account each time though I have logged into another account.
Question:
Is there anyway to generate dynamic OAuth_token or any other way that solves this problem??
Any help would be appreciated.
Answer: Image uploading to twitter no need to use Twipic api .Twitter API provide itself a URL for upload image
https://api.twitter.com/1.1/statuses/update_with_media.json
for Documentation you can follow this URL
https://dev.twitter.com/docs/api/1.1/post/statuses/update_with_media
Comment: Yes, I know that without TwitPic we can upload image. But, it is the requirement that image must be uploaded on TwitPic.
Comment: @Narayana: Do you have any code example how we can upload images using REST API 1.1? I have been trying for a couple of days, but it's not working for me. See my code here: http://stackoverflow.com/questions/21518280/twitter-api-1-1-update-with-media-returns-500


Método POST Web API retornando null

Question: Estou fazendo uma Web API em C# ASP.NET e no método POST o valor está me retornando null.
Estou usando o Postman para jogar um JSON dentro de valor mas ainda me retorna null.
public string Post([FromBody]string value)
{
    return value;
}

No Postman estou fazendo o seguinte
{
    "value" : "ana"
}

Comment: Na assinatura do método está esperando receber e retornar uma string, e você está enviando um objeto, pode ser isso. Reproduzi no .Net Core aqui e o Kestrel nem aceita a requisição. Você pode usar ```dynamic``` para aceitar objetos com estrutura indefinida, mas recomendo apenas para fins de estudo ou casos muito específicos.
Answer: No Postman você deve enviar uma string e não um objeto.
Ou seja, o payload deve ser:
"ana"

Método POST Web API retornando null


Network latency and speed of light

Question: This was kinda of covered by the following Is minimum latency fixed by the speed of light? , but i would like to add the follow up a bit.
The scenario is as follows; we have  two opposing sites one on the West Coast of the US and one in Ireland.  The customer is in central Europe, and has requested a latency test.  Ireland gives responses of ~65-70ms. However the West Coast guys claim to be faster with a response of 60ms.
Now a quick check says that light in fiber would take about 42ms to make the trip to the States and 8.5ms to Ireland. So obviously this is a single hop and does not include routers, switches, firewalls, protocol overhead etc.
Would I be right to call BS on their figures?
As a final note I tested a ping to Google IP address that was allegedly on the west coast from a site that covered a similar distance and was amazed to get a response time of 20ms. Suggesting ICMP packets that travel twice the speed of light.
So A) what am I missing B) Am I right to suspect shenanigans?
UPDATE: Guys thanks so far for your help and I have been reading various previous questions on this.  About 5 years I had an issue where the hop from the UK to Ireland added 10ms of latency no matter what we did. In the end I moved the servers; So imagine my surprise when I have guys that claim they are 5ms faster with a transatlantic trip.
So again should I call BS? Oh and assume both sites are normal mortals that don't have access to Google magical routing, warp dives or flux capacitors. :)
UPDATE 2:  Final update after hearing the arguments below and reading the various other articles would you call BS on his times??
Comment: Google makes heavy use of anycast addresses, so that probably got answered by a server much closer to you.
Comment: Related: [How much network latency is typical for east-weast coat USA?](http://serverfault.com/questions/137348/how-much-network-latency-is-typical-for-east-west-coast-usa)
Comment: Be weary of the path taken by the fibre; I have a fibre link between to data centres 3km apart, the fibre route is 10km, tripple!
Comment: Yeh I guessed that Google was using some fancy Routing or other tricks\magic because a trace route to the IP that was allegedly on the west cost showed a trace time of '00s of ms then jumped to 20ms...
Answer: It is common for recent models of switches and or routers to introduce only single digit
microseconds of latency, so the number of hops is not so important for this ping test.
You are right about the speed of light, and your numbers do not seem so odd. If the distance for this latency is about 40ms away (according to my math, it is 30ms by straight line), so having 20ms added by other impediments is certainly normal. I am more curious to know why Ireland is so slow.
One more thing to note is that when someone is talking about "link latency", they may very well be talking about the time for a packet to get to the other side. ping reports round trip latency so it is quite likely to see the number double.
And regarding Google, I wouldn't know where it is really located. Are you sure the server is on the west coast?
And here is a real-life example of me (my home in Tokyo) pinging an US kernel mirror (that would be a little short of 9000km by straight line) and getting a decent 110ms round trip response time, which would be 55ms one way link latency.
> ping  -i0.2 -c5 mirrors.us.kernel.org
PING mirrors.us.kernel.org (220.127.116.11) 56(84) bytes of data.
64 bytes from mirrors2.kernel.org (22.214.171.124): icmp_req=1 ttl=52 time=109 ms
64 bytes from mirrors2.kernel.org (18.104.22.168): icmp_req=2 ttl=52 time=115 ms
64 bytes from mirrors2.kernel.org (22.214.171.124): icmp_req=3 ttl=52 time=109 ms
64 bytes from mirrors2.kernel.org (220.127.116.11): icmp_req=4 ttl=52 time=110 ms
64 bytes from mirrors2.kernel.org (126.96.36.199): icmp_req=5 ttl=52 time=117 ms

--- mirrors.us.kernel.org ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 839ms
rtt min/avg/max/mdev = 109.654/112.563/117.892/3.350 ms

Comment: +1 Light doesn't travel at 300MM/s in glass though, it travels about 197MM/s.  By "straight" line, it's about 42.1ms from Dublin to LA. Also, while it might be possible that the routers introduce only a few microseconds of latency, it's not likely. Getting 60ms pings on that sort of distance would be quite hard.
Comment: Can you show any real world data that supports any network in existence that has latencies between the West Coast and Central Europe of 40ms?  Because that would be wildly faster (4x) than any network I have ever seen. 150-180ms would be more in line.
Comment: 60ms would be quite hard, but not impossible. Certainly less unlikely in a situation where it sounds that people pride themselves for having a fast connection. And just now I pinged mirrors.us.kernel.org and got 100-110ms of latency from my home which should be about 9000km away. Why would not someone with a better network be able to get it even faster.
Answer: The rule of thumb is that the speed of light in SMF is ~.6c (same neighborhood as Chris S' description).  The port-to-port latency introduced by routers and switches is going to average out in the low double-digit range once any kind of buffering or fancy features are thrown into the mix.  There's also a nominal amount of serialization delay that's introduced every time a packet is mapped onto the media itself.  This value decreases as a function of link bandwidth - so there will be measurable differences between, say, an OC3 link and an OC768.  This also tends to run in microseconds.
The rule of thumb I've generally used is about .25ms per 100km of actual link (one-way) with minimal hardware involved (i.e. DWDM equipment).  This estimate has served very well in the construction of private metro networks and even a few long-haul dedicated runs.  That said, the relationship between this number and reality in the circumstance of carrier MPLS clouds, the public Internet, etc is pretty much a toss-up.  I'd suggest something like this for establishing the minimum practical latency.
That said...
First - the actual physical path taken by a given circuit is sometimes only tangentially related to actual geographic distance.  Backhauling a circuit by hundreds of kilometers to the west and south only to send it hundreds of kiometers to the north is not unheard of.
Second - Nor, indeed, is the process of sending IP traffic through one or more exchange points that may, or may not, really be on the way.  Economics of both circuit construction and carrier hand-off locations drive practical engineering more so than absolute minimization of latency.
Finally - when running a traceroute take the naming of the intermediate nodes with a grain of salt unless you personally know the network you're crossing.  Naming conventions with airport codes (for example) can give a hint, but there's no way to conclusively know what you're looking at without some measure of additional knowledge.
Comment: So based on points 1&2)  my absolute min for Europe to the US of 40 odd ms is going to be a large under estimation. On 3) I understand what you are saying but I have been to the actual physical location of both servers....
Comment: Sorry and want to call BS on the West Coast guy....
Comment: Europe is a good example - the cables themselves don't take the absolute straightest route but are going to be constrained to an extent by the lay of the sea floor.  A run between locations that are 3000km apart might have 4500 or 5000 km of actual cable.
Answer: Try an IP address like 220.127.116.11 (It is for Sun Microsystems) that definitely is in US. You can't get to a clue by just PING. Maybe ICMP packets are shaped in some sites., although Google ping sounds weird because it's less than expected not more!

Network latency and speed of light


Show that there is $x \in S^1$ s.t. $f(x)=f(-x)$ for $f \in C^0(S^1, \mathbb{R})$

Question:
Let $f: S^1 \subset \mathbb{R}^2 \to \mathbb{R}$ be a continuous function on the unit circle $S^1$.
Show that there is $x \in S^1$ s.t. $f(x)=f(-x)$

Intuitively this is quite clear since I can imagine if this does not hold, we should have sort of a spiral that is not continuous at one point. But I'm not sure how to show this exactly. Any ideas?
Comment: Use the intermediate value theorem
Answer: Hint :
The function $g :[0,\pi] \rightarrow \mathbb{R}$ defined by
$$g(t)=f(e^{it})-f(-e^{it})$$
is continuous and satisfies $g(0)=-g(\pi)$. Then apply IVT to $g$.
Comment: @paxtibimarce Actually you can check any point that are opposite on the circle ! The fact is that the function $h : x \mapsto f(x)-f(-x)$ satisfies $h(x)=-h(-x)$ for every $x \in \mathcal{S}^1$.
Comment: Thanks, got it.
Could you explain how you got the intuition to check $0,\pi$ in particular? I also defined the same $g$ but didn't notice this.


Erro de sintaxe em sistemas if and elif

Question: while True:
ret,img=cam.read();
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect.detectMultiScale(gray,1.3,5);
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
    id, conf= rec.predict(gray[y:y+h,x:x+w])
    if(id ==1):
        id = "Tiago"
    cv2.cv.PutText(cv2.cv.fromarray(img),str(id), (x,y+h+30),font, 255)
    cv2.cv.PutText(cv2.cv.fromarray(img),str(genderTiago), (x,y+h+60),font, 255)
    cv2.cv.PutText(cv2.cv.fromarray(img),str(occupationTiago),(x,y+h+90),font,255)
    cv2.imshow("Face",img)
    elif(id ==2):
        id = "Obama"
if (cv2.waitKey(1) == ord('q')):
    break;

Estou a fazer um programa de reconhecimento de face e eu estou a ter um problema no ultima elif. O python diz que é erro de sintaxe. O que está mal?
Answer: A indentação no código que você postou está errada pois todos os "cv2." deveriam estar começando na mesma coluna do "id".
if (id == 1):
    id = "Tiago"
    cv2.cv.PutText(cv2.cv.fromarray(img),str(id), (x,y+h+30),font, 255)
    # ...
elif (id == 2):
    id = "Obama"

Erro de sintaxe em sistemas if and elif


Python flask_caching, Generate Unique page Dependent on Passed Cookies

Question: For my Flask application I currently have the following
from flask import Flask, request
from flask_caching import Cache

app = Flask(__name__)
app.config.from_mapping({'CACHE_TYPE' : 'filesystem', 'CACHE_DIR' : 'CACHED_PAGES'})
cache = Cache(app)

@app.route('/some_url', methods=['GET'])
@cache.cached(timeout=0, query_string=True)
def some_url():

If my application returns a few variations of the page, depending on what cookies are set, how can I allow a page to be cached specific to what cookies are set?
I'm supposing that the cache_key, or file name for the cache file should be generated with the inclusion of the passed cookie data.
Can somone provide a code example of how this would work?
Comment: Sounds like you're after the `memoize` function in flask-caching [link](https://flask-caching.readthedocs.io/en/latest/#memoization). You'd need to parse your cookies somehow before passing them to the function.
Comment: @PGHE I actually read that page before posting the question, but I don't quite get how it can be done. Any tips?
Answer: Not entirely sure what you're trying to cache, but memoization may work for you with smaller methods rather than an entire view.
from flask import Flask, request, render_template
from flask_caching import Cache

app = Flask(__name__)
app.config.from_mapping({'CACHE_TYPE' : 'filesystem', 'CACHE_DIR' : 'CACHED_PAGES'})
cache = Cache(app)

@cache.memoize(50)
def method_1(cookie_1):
   return cookie_1

@cache.memoize(50)
def method_2(cookie_2):
    return cookie_2

@app.route('/some_url', methods=['GET'])
def some_url():
    result_1 = method_1('a cookie value')
    result_2 = method_1('another cookie value')
    render_template('template.html', result_1=result_1 , result_2=result_2)

To cache a view with memoziation you'd have to rely on the url parameters passed into the view function rather than cookies.
Comment: I'm going to try this out
Comment: basically I wish to cache an html page generated from a view, including specific url parameters "/go?option=variablevalue"... I can already do this, but my website also has 4 view tabs which the user can select. When a tab is selected, a cookie is set so later when they visit the page they are automatically returned 1 of the 4 versions of the page.


NTFS Permissions - Access Denied even though Explicit Allow and no Deny

Question: I'm hoping someone can help me with this NTFS permissions problem. The short version is that I can't write a new file in F:\SomeDir even though I seem to be granted full permissions via both the "Domain Admins" group and a second unprivileged group. The "Effective Permissions" tab in the explorer permissions UI shows that I have full control, and there are no "Deny"s anywhere in the ACL or anything else that looks unusual. I am logged into the machine over RDP and accessing the disk directly as a local drive, not through a share.
<code>F:\SomeDir>set U
USERDNSDOMAIN=THEOFFICE.LOCAL
USERDOMAIN=THEOFFICE
USERNAME=thisisme
USERPROFILE=C:\Users\thisisme

F:\SomeDir>icacls .
. BUILTIN\Administrators:(I)(F)
  CREATOR OWNER:(I)(OI)(CI)(IO)(F)
  THEOFFICE\Domain Admins:(I)(OI)(CI)(F)
  NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
  BUILTIN\Administrators:(I)(OI)(CI)(IO)(F)
  BUILTIN\Users:(I)(OI)(CI)(RX)

Successfully processed 1 files; Failed processing 0 files

F:\SomeDir>net group /domain "Domain Admins"
The request will be processed at a domain controller for domain THEOFFICE.local.

Group name     Domain Admins
Comment        Designated administrators of the domain

Members

-------------------------------------------------------------------------------
Administrator        thatguy                  thisisme
The command completed successfully.

F:\SomeDir>echo "whyUNoCreateFile?" > whyUNoCreateFile.txt
Access is denied.
</code>
I searched for answers and came across similar problems that lead to UAC (ex. Why does removing the EVERYONE group prevent domain admins from accessing a drive? ). I can't turn off UAC at the moment, so I try a "regular" group that I'm also part of. This group has no special rights assignments and is not part of any administrative groups. Still no dice:
<code>[***** This one command executed in an elevated shell *****]
F:\SomeDir>icacls . /grant THEOFFICE\iteveryone:(OI)(CI)F
processed file: .
Successfully processed 1 files; Failed processing 0 files

F:\SomeDir>net group /domain "iteveryone"
The request will be processed at a domain controller for domain THEOFFICE.local.

Group name     ITeveryone
Comment

Members

-------------------------------------------------------------------------------
Administrator       thatguy                    thisisme
otherguy                someitguy
The command completed successfully.

F:\SomeDir>echo y > u
Access is denied.
</code>
As you can see, using a "regular" group didn't help. I have logged out and back in to the server to ensure my login token is up to date, and at any rate I belonged to these groups before the server was created.
If I grant explicit permission to myself, it does allow me to write files:
<code>[***** This one command executed in an elevated shell *****]
F:\SomeDir>icacls . /grant THEOFFICE\thisisme:(OI)(CI)F
processed file: .
Successfully processed 1 files; Failed processing 0 files

F:\SomeDir>echo y > u

F:\SomeDir>type u
y
</code>
My requirement is for the "Domain Admins" group to have Full Control, or if that's not possible without disabling UAC, then a second group will do, but I can't get either to work.
I'm really stumped. Can someone please point out what I could be overlooking?
Comment: Just to clarify, F: is a local drive and not a mapped drive. Correct?
Comment: Yes, F: is a local drive
Answer: So it turns out that this problem was exactly the UAC based problem described in the other article; the "ITeveryone" group didn't work for me because it was a "Distribution" group, not a "Security" group. I tried the same thing with a security group to which I was also a member and it worked as expected.


$interval not repeating task in Angular

Question: I'm writing a test for my web app so people can click a button and see the application run with some randomly generated values. This is an angular application and this test function lives inside a controller. I'm trying to slow down the function execution because my server / browser can't keep up if I just let it run. I am trying to use $interval to run my function once every 500 ms, but I click the button and it only runs once, then stops.
Here is the test function:
<code>$scope.test = function (){
      console.log('in the test function')
      $interval($scope.sendData(), 500, 100)
}
</code>
and here is $scope.sendData():
<code>$scope.sendData = function () {
   console.log('send Data')
   var val1 = parseInt(Math.random()*1000)
   var val2 = parseInt(Math.random()*1000)
   var val3 = parseInt(Math.random()*1000)
   var val4 = parseInt(Math.random()*1000)
   var val5 = parseInt(Math.random()*1000)
   var val6 = parseInt(Math.random()*1000)
   var str = 'val1=' + val1 + '&val2=' + val2 + '&val3=' + val3 + '&val4=' + val4 + '&val5=' + val5 + '&val6=' + val6
   $http.get('http://localhost:3002/sendFootData?'+str)
}
</code>
I also tried setInterval and setTimeout, but they did not slow down the function execution and my browser locked up because it couldn't keep up with the server responses.
Answer: You need to pass function reference to the <code>$interval</code>:
<code>$interval($scope.sendData, 500, 100);
</code>
In case you need to pass additional parameters you can to use additional anonymous function:
<code>$interval(function() {
    $scope.sendData(param1, param2);
}, 500, 100);
</code>
Comment: `$scope.sendData()` executes the function immediately: `()` is an invocation operator. However `$interval` expects a function passed as the first argument. In your case you are passing `undefined` since `sendData` doesn't return anything.
Comment: why no brackets and what if I need to pass params with it in the future? Also, I replaced $scope.sendData with a function literal and that works, so what the difference between that and $scope.sendData()?

$interval not repeating task in Angular


ZFS checksum errors, when do I replace the drive?

Question: I'm fairly new to ZFS and I have a simple mirrored storage pool setup with 8 drives. After a few weeks of running, one drive seemed to generate a lot of errors, so I replaced it.
A few more weeks go by and now I'm seeing small errors crop up all around the pool (see the zpool status output below). Should I be worried about this? How can I determine if the error indicates the drive needs to be replaced?
# zpool status
  pool: storage
 state: ONLINE
status: One or more devices has experienced an unrecoverable error.  An
        attempt was made to correct the error.  Applications are unaffected.
action: Determine if the device needs to be replaced, and clear the errors
        using 'zpool clear' or replace the device with 'zpool replace'.
   see: http://zfsonlinux.org/msg/ZFS-8000-9P
  scan: scrub repaired 22.5K in 1h18m with 0 errors on Sun Jul 10 03:18:42 2016
config:

        NAME        STATE     READ WRITE CKSUM
        storage     ONLINE       0     0     0
          mirror-0  ONLINE       0     0     0
            enc-a   ONLINE       0     0     2
            enc-b   ONLINE       0     0     0
          mirror-1  ONLINE       0     0     0
            enc-c   ONLINE       0     0     0
            enc-d   ONLINE       0     0     2
          mirror-2  ONLINE       0     0     0
            enc-e   ONLINE       0     0     2
            enc-f   ONLINE       0     0     1
          mirror-3  ONLINE       0     0     0
            enc-g   ONLINE       0     0     0
            enc-h   ONLINE       0     0     3

errors: No known data errors

ZFS helpfully tells me to "Determine if the device needs to be replaced..." but I'm not sure how to do that. I did read the referenced article which was helpful but not exactly conclusive.
I have looked at the SMART test results for the effected drives, and nothing jumped out at me (all tests were completed without errors), but I can post the SMART data as well if it would be helpful.
Update: While preparing to reboot into Memtest86+, I noticed a lot of errors on the console. I normally SSH in, so I didn't see them before. I'm not sure which log I should have been checking, but the entire screen was filled with errors that look like this (not my exact error line, I just copied this from a different forum):
blk_update_request: I/0 error, dev sda, sector 220473440
From some Googling, it seems like this error can be indicative of a bad drive, but it's hard for me to believe that they are all failing at once like this. Thoughts on where to go from here?
Update 2: I came across this ZOL issue that seems like it might be related to my problem. Like the OP there I am using hdparm to spin-down my drives and I am seeing similar ZFS checksum errors and blk_update_request errors. My machine is still running Memtest, so I can't check my kernel or ZFS version at the moment, but this at least looks like a possibility. I also saw this similar question which is kind of discouraging. Does anyone know of issues with ZFS and spinning down drives?
Update 3: Could a mismatched firmware and driver version on the LSI controller cause errors like this? It looks like I'm running a driver version of 20.100.00.00 and a firmware version of 17.00.01.00. Would it be worth while to try to flash updated firmware on the card?
# modinfo mpt2sas
filename:       /lib/modules/3.10.0-327.22.2.el7.x86_64/kernel/drivers/scsi/mpt2sas/mpt2sas.ko
version:        20.100.00.00
license:        GPL
description:    LSI MPT Fusion SAS 2.0 Device Driver
author:         Avago Technologies <firstname.lastname@example.com>
rhelversion:    7.2
srcversion:     FED1C003B865449804E59F5

# sas2flash -listall
LSI Corporation SAS2 Flash Utility
Version 20.00.00.00 (2014.09.18)
Copyright (c) 2008-2014 LSI Corporation. All rights reserved

    Adapter Selected is a LSI SAS: SAS2308_2(D1)

Num   Ctlr            FW Ver        NVDATA        x86-BIOS         PCI Addr
----------------------------------------------------------------------------

0  SAS2308_2(D1)   17.00.01.00    11.00.00.05    07.33.00.00     00:04:00:00

Update 4: Caught some more errors in the dmesg output. I'm not sure what triggered these, but I noticed them after unmounting all of the drives in the array in preparation for updating the LSI controller's firmware. I'll wait a bit to see if the firmware update solved the problem, but here are the errors in the meantime. I'm not really sure what they mean.
[87181.144130] sd 0:0:2:0: [sdc] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87181.144142] sd 0:0:2:0: [sdc] CDB: Write(10) 2a 00 35 04 1c d1 00 00 01 00
[87181.144148] blk_update_request: I/O error, dev sdc, sector 889461969
[87181.144255] sd 0:0:3:0: [sdd] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87181.144259] sd 0:0:3:0: [sdd] CDB: Write(10) 2a 00 35 04 1c d1 00 00 01 00
[87181.144263] blk_update_request: I/O error, dev sdd, sector 889461969
[87181.144371] sd 0:0:4:0: [sde] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87181.144375] sd 0:0:4:0: [sde] CDB: Write(10) 2a 00 37 03 87 30 00 00 08 00
[87181.144379] blk_update_request: I/O error, dev sde, sector 922978096
[87181.144493] sd 0:0:5:0: [sdf] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87181.144500] sd 0:0:5:0: [sdf] CDB: Write(10) 2a 00 37 03 87 30 00 00 08 00
[87181.144505] blk_update_request: I/O error, dev sdf, sector 922978096
[87191.960052] sd 0:0:6:0: [sdg] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87191.960063] sd 0:0:6:0: [sdg] CDB: Write(10) 2a 00 36 04 18 5c 00 00 01 00
[87191.960068] blk_update_request: I/O error, dev sdg, sector 906238044
[87191.960158] sd 0:0:7:0: [sdh] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87191.960162] sd 0:0:7:0: [sdh] CDB: Write(10) 2a 00 36 04 18 5c 00 00 01 00
[87191.960179] blk_update_request: I/O error, dev sdh, sector 906238044
[87195.864565] sd 0:0:0:0: [sda] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87195.864578] sd 0:0:0:0: [sda] CDB: Write(10) 2a 00 37 03 7c 68 00 00 20 00
[87195.864584] blk_update_request: I/O error, dev sda, sector 922975336
[87198.770065] sd 0:0:1:0: [sdb] FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_OK
[87198.770078] sd 0:0:1:0: [sdb] CDB: Write(10) 2a 00 37 03 7c 88 00 00 20 00
[87198.770084] blk_update_request: I/O error, dev sdb, sector 922975368

Update 5: I updated the firmware for the LSI controller, but after clearing the ZFS errors and scrubbing, I'm seeing the same behavior (minor checksum errors on a few of the drives). The next step will be updating the firmware on the drives themselves.
Update 6: I replaced the PCI riser after reading in some forums that other people with the U-NAS NSC800 case have had issues with the provided riser. There was no effect on the checksum errors. I have been putting off the HDD firmware update because the process is such a pain, but I guess it's time to suck it up and make a bootable DOS flash drive.
Update 7: I updated the firmware on the three of the Seagate drives. The other drives either didn't have a firmware update available or I wasn't able to get it (Western Digital told me there was no firmware update for my drive). No errors popped up after an initial scrub, but I'm going to give it at least a week or two before I say this solved the problem. It seems highly unlikely to me that the firmware in three drives could be effecting the entire pool like this.
Update 8: The checksum errors are back, just like before. I might look into a firmware update for the motherboard, but at this point I'm at a loss. It will be difficult/expensive to replace the remaining physical components (controller, backplane, cabling), and I'm just not 100% sure that it's not a problem with my setup (ZFS + Linux + LUKS + Spinning down idle drives). Any other ideas are welcome.
Update 9: Still trying to track this one down. I came across this question which had some similarities to my situation. So, I went ahead and rebuilt the zpool using ashift=12 to see if that would resolve the issue (no luck). Then, I bit the bullet and bought a new controller. I just installed a Supermicro AOC-SAS2LP-MV8 HBA card. I'll give it a week or two to see if this solves the problem.
Update 10: Just to close this out. It's been about 2 weeks since the new HBA card went in and, at the risk of jinxing it, I've had no checksum errors since. A huge thanks to everyone who helped me sort this one out.
Comment: Can you tell us more about the hardware? Having those errors on multiple drives seems to indicate a backplane/controller/cabling problem more than a disk issue.
Comment: That it's most likely the controller is blatantly obvious at this point. Actually it was blatantly obvious some time ago, with "Update 4".
Comment: Is your RAM okay? I've had similar errors when a memory module was bad - no disk errors, but some (low) amount of checksum errors on all drives.
Comment: You're welcome @hak8or. The people on this site have helped me so much, so it's nice to hear my example might help someone else.
Comment: Thanks @Michael for the help. Could you elaborate a bit on why you are thinking it's the controller instead of the backplane or cabling? Does something in those error messages point to a controller issue?
Comment: I hadn't thought of that. The drives are in a [U-NAS NSC-800 chassis](http://www.u-nas.com/xcart/product.php?productid=17617) that came with a built in SATA/SAS backplane. That is connected via 2 mini-sas connectors to an [LSI SAS 9207-8i](https://smile.amazon.com/gp/product/B0085FT2JC/ref=oh_aui_search_detailpage?ie=UTF8&psc=1) HBA. That is connected via a PCI riser that came with the chassis to a [Supermicro MBD-X10SDV-4C](http://www.supermicro.com/products/motherboard/xeon/d/X10SDV-4C-TLN2F.cfm).
Comment: Thanks for the tip. I'll run memtest86 tonight and see what I get. I haven't had any other issues that might point to a memory problem, but you never know.
Comment: After 18 hours and 2 complete passes of memtest86+ with no errors I feel pretty confident that we aren't looking at faulty RAM here. I'm at a loss now for what could be causing the errors.
Comment: Not sure if this helps you, but I seem to have far more in terms of "odd" behavior of SATA HDDs on a LSI 9211 than with SAS HDDs on the same controller and cabling, with ZoL.
Comment: @MichaelKjörling, thanks that's definitely something to keep in mind for the future.
Comment: I just wanted to pop in and say thanks for doing the updates. I know of someone who was having similar issues and did a similar flow of tests (memtest, etc) but is dead set on thinking it's not the controller. Hopefully this will help convince them that it may be the issue.
Answer: Having those errors across multiple drives seems to indicate a backplane/controller/cabling problem more than a disk or RAM issue.
Comment: Thanks for the help. I am not able to swap out all of those components at the moment. Do you have a suggestion on how I could narrow it down or what might be the most likely culprit?
Comment: Try firmware updates of all impacted components. Are these SATA disks?
Comment: Will do, thanks. I'll start with the firmware update on the controller because I have seen elsewhere that the firmware and driver versions should match (see update 3 on my question). Yes, they are all 1TB SATA disks, and I remember that `smartctl` said there was a firmware update available for some of the Seagate disks I'm using, so I'll update them as well.
Answer: My general rule of thumb is that if the errors are continuing to rise unexpectedly, the disk needs replaced; if it's static, there might have been some transient condition that caused the error, and the system's not reproducing the conditions that caused problems.
A few checksum errors doesn't necessarily indicate anything bad mechanically with the drive (bit rot happens, ZFS just happens to detect it while other filesystems don't), but if those errors have happened over the course of an hour, then it's a much different situation than if they've happened over the course of a year.