How to grant userpoints to users who perform a login 5 days consecutively?

Question: I need to know if a user has performed a login, for example, 5 days consecutively. The reason for this is I want to award User points to them.
For example:

User A performs a login on Monday, Tuesday, Wednesday, Thursday and Friday. (granted 10 points)
User B performs a login on Monday, Tuesday, Thursday, Friday and Saturday. (no points)

I'm trying to do this with Rules but failed miserably. Any ideas?
Note: I'm trying to use Rules condition to compare my_last_login values against today's date with an offset of -1 days but it always return False.
Comment: Where are you failing exactly? Rules can definitely hook into user logins. However you might have to code a custom action to do the counting.
Comment: I'm trying to use rules _condition_ to compare my_last_login values against today's date with an offset of -1 days but it always return False.
Comment: @BetaRide : IMO the key challenge is "5 days consecutively" ... check my answer for more details (why only Rules is not enough).
Answer: Statistics module in the core would work in this case.
Answer: Actually, this is what I am trying to build right now. Use the hook_user_login() with the following code:
global $user;
$last_access = $user->access;
// if last_access is today, do nothing
$yesterday_start    = mktime(0, 0, 0,date('m'), date('d')) - (60*60*24);
$yesterday_end  = $yesterday_start + (60*60*24)-1;

// if last access is yesterday, increment counter
if ($last_access > $yesterday_start && $last_access < $yesterday_end) {
  //increment counter
}
// if last access is before yesterday, set counter = 1
else if ($last_access < $yesterday_start) {
  $counter = 1;
}

if ($counter == 5) {
  // put you magic code here
  // set the counter to 1
}

The $counter can be something like variable_get(). Alternatively, I guess that you can put the code above in your Rules, if you don't want to write a module. In both cases, however, the code will not be executed if the user leaves his browser logged in.
Comment: This looks very promising. I wonder where should i put this? In the Rules action and set the trigger to 'User has logged in'?
Comment: I have put this inside a hook_user_login() hook. I guess that this will also work if you do what you describe. In both cases, however, the code will not be executed if the user leaves his browser logged in.
Answer: Using the Rules module to solve this challenge is indeed part of the solution. But the key part of your challenge is that you want a Rules Action to be triggered, for a Rules Event (= user performs a login) which:

has to be repeated
within a specified timeframe
which don't all happen at the very same moment.

Rules is great (actually amazing), but it does not support any of the 3 bullets above. So far the bad news ...
However, your question seems like a perfect case for using the Goals module (disclosure: I'm the maintainer of it). Below is a possible configuration for it, using Goals.
Configure a goal
Navigate to the relative path admin/config/goals/manage and use the link "Add a goal" to define just 1 goal, with a description (say):
Perform a login, 5 days consecutively.
Configure a task
To achieve the above goal, define the Task(s) to be completed. Even though there could be multiple tasks to be completed for a single goal, in your case you just need 1. It's simply  Perform a login.
Obviously, that doesn't take into account the 5 days consecutively-part of your question. For that you would use some of the more advanced ways to use (configure) Goals, i.e. by using these optional configuration options for this specific task:

this task has to be repeated multiple times: in your case 5 times.
this task requires some amount of time to expire in between any 2 similar tasks: in your case, if a user performs a login/logout multiple times a day, only the first one of every day counts.
this task must be completed within a specific time frame (a number of times, expressed in hours, days or weeks): in your case 5 days.

Track progress while performing tasks
To track the progress made by a single user to complete this task, you only have to write an appropriate rule, using the Rules module, to record relevant events happening in your site, which are related to the completion of the task to reach the goal.
For the goal/task described above, you'd only need 1 (extremely basic) rule, which would look like so:

Rules Event = After a user performs a login.
Rules Action = Record a task for Goals (obviously, the task to be recorded is "Perform a login"). This is where part of the Goals magic happens, such as verifying the requirements in the optional task configuration options for a task (only once a day, etc).

Note: if the user leaves his/her browser logged in, then using this Rules Event might not be the most appropriate event. If you'd replace that event by "Drupal is Initializing" (within "System"), then such rule will be triggered for any path that the user visits. Optionally you may want to combine that Rules Event with an extra Rules Condition "User has role, with role = authenticated", so that the Rules Action(s) are only performed for logged in users.
Use Rules to process completed goals
After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. But, that's where it gets really interesting: you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user. With that, the answer to your question is extremely easy: perform a Rules Action to "... grant userpoints to the user who completed the goal" ... which is exactly what your question is about, no?
More info
Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.
Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).
Answer: Enable the PHP Filter module.
Add a two fields to user profile (admin/config/people/accounts/fields): for the login counts (name: cons_login_counts, type: integer, default value: 0, permissions: custom(only for admin)) and for the last login date (name: cons_last_login_day, type: text, permissions: custom).
Create a new rule with reacting on event "User has logged in". Add an action "Execute custom PHP code" and put this code:
$user = entity_metadata_wrapper('user', $account);
$login_counts = $user->field_cons_login_counts->value();
$last_login_day = $user->field_cons_last_login_day->value();

$today = date('Y-m-d');
$yesterday = date("Y-m-d", time() - 60 * 60 * 24);

if ($last_login_day == $today)
  return;

if ($last_login_day == $yesterday) {
  $login_counts++;
} else {
  $login_counts = 1;
}

$last_login_day = $today;

if ($login_counts == 5/* and not gived a points to user*/) {
  // give them point
}

$user->field_cons_login_counts = $login_counts;
$user->field_cons_last_login_day = $last_login_day;

$user->save();

Comment: Wow thanks for being very thorough :) This is very helpful.
Answer: Rule has to be triggered when a user is logging in and
you need to write Custom PHP Code in the Do Action part of Rule.
Like
if(check_user_logins($uid)){
  db_query("UPDATE
 set points = points + 5 WHERE uid = %d", $uid);
}

function check_user_logins($uid){
  // Code to check consecutive user logins goes here
  if($logins >= 5){
    return TRUE;
  }else{
    return FALSE;
  }
}

Comment: This only checks for 5 logins in general - OP is asking for *consecutive* logins.
Comment: @Chapabu Well I didnt write the entire code ! `$logins` should be consecutive logins count, thought that was implied and change 5 to X as required.


Why is AWS shutting down automatically all the instances launched after the fifth?

Question: I cannot start more than 5 instances. Is this normal behaviour for an AWS Educate account on us-east1?
Comment: What kind of instances? There are some limits for the "bigger" ones so you don't generate a VERY large expense (possibly without realizing). Check out the page for quota limits on EC2 and open a support ticket if you need more. https://docs.aws.amazon.com/general/latest/gr/ec2-service.html
Comment: Not even more than 5 t2-micro ones which are supposedly free tier
Comment: One thing to realize about AWS is that it's not a basic hosting provider, it's a complex enterprise grade platform with hundreds of services. I've spent at least 500+ hours on AWS training over the past six or seven years, maybe triple that, not including partner training. I've also worked full time in AWS full time for a few years and I learn something new every day. AWS is fairly complex :)
Answer: Yes, this is normal. AWS has Service Quotas for a few reasons, including protecting their service, protecting new customers against bill shock, and preventing huge bills if an account is compromised.
As accounts get older and pay their bills the limits increase automatically, or you can request a limit increase.
The AWS Service Quotas dashboard shows you your current limits, and makes it fairly easy to extend those limits.
Here's the dashboard for standard instance for my account, which is probably at least five years old. We can see the default limit is 5, but because my account is old and fairly well trusted I can launch 1848 instances. I'd actually rather it stayed at five, I could probably request that if I wanted to.
Comment: Thanks for your reply. Is there somewhere where I can verity that it's specifically 5 instances. Apparently some of my classmates didn't have this issue, so I'm trying to dig out the reason.
Comment: Thanks!! I see it now. I wonder how my classmates didn't have this issue then :/ is there a workaround?
Comment: In my post I link to service quotas which tells you exactly how to find the information, and I added a screenshot. It will differ between accounts. I did an AWS training course a few years ago, they gave us all new accounts, the limits varied between the accounts. Like I said in my answer you can request a higher limit, that can take from minutes to days.


Find where line intersects sine function

Question: Here we have sin((x+1)*(pi/2)):

Now let's say we have a point at (x=2, y=1)...

And we draw a line to the origin (x=0, y=0)...

If we create a point where the line intersects the sine function, we get a new point.
Is there a way to find out the (x,y) of this new point?
Comment: The line has equation $x = 2y$, so this reduces to find $y$ such that $y = \sin((2y+1)\frac{\pi}{2})$. It can be solved numerically with Newton's method.
Answer: The $x$ coordinate of the point of intersection is the unique positive number such that $\sin(\pi(x+1)/2) = x/2$.  This equation cannot be solved in closed form but Newton's method shows the solution is approximately $0.7539340187865513$.
To apply Newton's method, define $f(x)=\sin(\pi(x+1)/2) - x/2$.  Then
$$N(x)=x-\frac{f(x)}{f'(x)} = x-\frac{\sin \left(\frac{1}{2} \pi  (x+1)\right)-\frac{x}{2}}{\frac{1}{2} \pi  \cos \left(\frac{1}{2}
   \pi  (x+1)\right)-\frac{1}{2}}.$$
Iterating $N$ from the starting point $x_0 = 1.0$, we generate the sequence
$$
\begin{array}{l}
 1.0000000000000000 \\
 0.7585469929947761 \\
 0.7539390100743306 \\
 0.753934018792478 \\
 0.7539340187865515 \\
 0.7539340187865514 \\
 0.7539340187865513 \\
 0.7539340187865514 \\
 0.7539340187865513 \\
\end{array}
$$
Thus, it appears the solution is between $0.7539340187865513$ and $0.7539340187865513$.
Comment: You meant between 0.7539340187865513 and 0.7539340187865514, right?
Answer: The line through $\;(2,1)\;$ and through the origin is $\;y=\frac12x\;$ , so you need to solve
$$\sin\left(\frac\pi2(x+1)\right)=\frac12x$$
This yields a transcendental equation which would hardly have a simple, nice-looking zero, but:
$$h(x)=\sin\left(\frac\pi2(x+1)\right)-\frac12x\implies\begin{cases}h(0)=1\\{}\\h(1)=-\frac12\end{cases}$$
Now apply the Mean Value Theorem (=Lagrange's Theorem) to $\;h\;$ and deduce the existence of a point like the one you're interested in. If you want the actual value of the point's coordinates you may need to repeat the above several times, or use some other approximation methods (say, Newton's)
Comment: +1 Exactly my approach, which will not be posted (has now been "discarded", as you beat me to it!) ;-)


How to properly use QLayouts (hbox, vbox, etc)?

Question: I am building a custom widget based on QGraphicsWidget
Inside the widget, I need various other widgets in line with the size of the window. For this I am using
Layout = new QGraphicsLinearLayout();
Layout->setOrientation(Qt::Horizontal);
setLayout(Layout);

So I have a layout, and on each side of the layout I have a widget. So a widget on the left side, and a widget on the right side.
 QGraphicsLinearLayout() below

      500 px wide x
|--------------------------------|
|                                |
|left widget         right widget|   100 px tall y
|--------------------------------|

I want the behaviour that when the window gets bigger, the widgets stay within x pixels of the edge. So if the window were to be resized to 10,000 pixels wide, left widget would always be 1 pixel from the left edge and right widget would always be 1 pixel from the right edge.
                10000 px wide x
|---------------------------------------------------|
|                                                   |
|left widget                            right widget|   100 px tall y
|---------------------------------------------------|

The current behaviour is that left widget will stay in place and never move, and right widget will move away from the right edge.
To achieve this behaviour, I have tried the following:
Layout->setAlignment(leftWidget, Qt::AlignLeft);

That does absolutely nothing.
I also tried
Layout->addItem(leftWidget);

Layout->setStretchFactor(leftWidget, 0);

Layout->addItem(rightWidget);

Which gives the desired effect but overlaps the rightWidget with the border like so
      500 px wide x
|--------------------------------|
|                                |
|left widget                 right widget   100 px tall y
|--------------------------------|

So how can I get my desired behaviour? QLayouts seem very confusing and the API's misleading thus far.
Answer: Solution
Use QGraphicsLinearLayout::addStretch between the left and right widgets in order to keep them to the sides and QGraphicsLayout::setContentsMargins to add a space between the widgets and the edges:
auto *l = new QGraphicsLinearLayout();

l->addItem(leftProxy);
l->addStretch();
l->addItem(rightProxy);
l->setContentsMargins(25, 1, 1, 1);
l->setSpacing(1);

Example
I have prepared a minimal example for you of how to use the proposed solution:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    auto *view = new QGraphicsView(this);
    auto *widget = new QWidget();
    auto *leftWidget = new QPushButton(tr("Left"));
    auto *rightWidget = new QPushButton(tr("Right"));
    auto *leftProxy = new QGraphicsProxyWidget();
    auto *rightProxy = new QGraphicsProxyWidget();
    auto *l = new QGraphicsLinearLayout();
    auto *sizeGrip = new QSizeGrip(widget);

    leftWidget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
    rightWidget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);

    widget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    widget->setMinimumSize(sizeGrip->sizeHint().width()
                           + leftWidget->sizeHint().width()
                           + rightWidget->sizeHint().width(),
                           leftWidget->sizeHint().height());

    leftProxy->setWidget(leftWidget);
    rightProxy->setWidget(rightWidget);

    l->addItem(leftProxy);
    l->addStretch();
    l->addItem(rightProxy);
    l->setContentsMargins(25, 1, 1, 1);
    l->setSpacing(1);

    view->setScene(new QGraphicsScene(this));
    view->scene()->addWidget(widget)->setLayout(l);

    widget->resize(400, 200);

    setCentralWidget(view);
    resize(640, 480);
}

Comment: This doesn't work, when I resize my widget leftWidget & rightWIdget don't move.
Comment: Isn't addStrect(0) & setStretchFactor(leftWidget, 0) the same thing?
Comment: @IhaveAquestion, no, they are not. And in order to know why this does not work for you and offer you a solution, you have to prepare a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
Comment: addStrech(1) gives me the effect I need but it's overdrawing the widget like I described.
Comment: @IhaveAquestion, it would be faster if you show the cause instead of trying to come up with a solution. Prepare a MCVE.
Comment: This answer is technically correct, I will mark as such, but when you're resizing custom widgets there's more to it than this, honestly don't feel like typing it out but this is correct answer. SHort version is that when resizing you must setMin/MaxWidth accordingly on the underlying parent widget and QGraphicsLinearLayout, or else it will stop at the last or initial setMaximumWidth value


XPCOM stub files

Question: 1- Is there any XPCOM stub files (javascript) that can be used by PHPStorm for code completion?
2- Is there any way to facilitate FireFox plugin development in PHPStorm?
3- How can I set FireFox as the only browser target for syntax checking? Currently for each() construct is displayed as a syntax error but it is correct in Firefox.
Answer: You should set your JavaScript version in preferences\JavaScript to 1.7 or above to use let and for each.

XPCOM stub files


How many unordered pairs $A$ and $B$ are there?

Question: Let $S=\{1,2,3,...,10\}$ . How many unordered pairs $A$ and $B$ are there, where $A$ and $B$ are non empty disjoint subsets of $S$ ?
Any approach for such questions ?

Total number of unordered pairs of disjoint subsets of S
This is one related question, but using the same approach as given in the above link, I am getting
$\left(\frac{3^n - 1}{2} + 1 \right) - 2^n$ for my question

But, I need a confirmation here ?
Comment: Yes.  There are $2^n$ unordered pairs of subsets where one of the subsets is the empty set.
Comment: I'm getting the same result as yours. See my answer.
Answer: First assume that we need ordered pairs $A$ and $B$, where $A$ and $B$ are disjoint subsets of $S$. For this, an element can either go to A or B or to neither of them. There are $3^n$ ways of doing this.
Now let's remove the case when A or B is empty.
Case 1: One is empty, other is not. There are $2 \times (2^n - 1)$ such cases.
Case 2: Both are empty: There is only $1$ such case.
We need to remove these $ 2^{n+1} - 1 $ cases from $3^n$.
So we are left with $3^n - 2^{n+1} + 1$ possibilities.
But since we need unordered pairs of $A$ and $B$, we divide this by $2$ to get $\boxed{\frac{3^n + 1}{2} - 2^n}$.
One approach for solving such questions is to start with a broader case that has less restrictions and then apply restrictions on it.
Comment: @MarkusScheuer fixed mistake.
Comment: Well done! (+1)
Comment: @shauryagupta Thanks for confirming :-)
Answer: Here is a proof of your second question.
Consider a set $E$ containing $n$ elements ($\mathrm{card}(E)=n$) and $q=\mathrm{card}(F)$ where :
$$F=\{(A,B)\in\mathcal{P}(E)^2;\,A\cap B=\emptyset\}$$
Since the single subset $A$ of $E$ verifying $A\cap A=\emptyset$ is $\emptyset$ itself, the answer to your question will be $1+\frac{q-1}{2}$.
Since the elements of $F$ can be classified according to their cardinal, we have :
$$F=\bigcup_{k=0}^nF_k\qquad\mathrm{where}\quad F_k=\{(A,B)\in\mathcal{P}_k(E)^2;\,A\cap B=\emptyset\}$$
where $\mathcal{P}_k(E)$ denotes the set of all subsets of $E$ whose cardinal is $k$.
This is the union of pairwise disjoint sets, and therefore :
$$q=\sum_{k=0}^n\mathrm{card}(F_k)$$
We see that $\mathrm{card}(F_k)={n\choose k}2^{n-k}$. Thus :
$$q=\sum_{k=0}^n{n\choose k}2^{n-k}=3^n$$
Finally, there are $1+\frac{3^n-1}{2}$ unordered pairs of disjoint subsets.
Comment: We are looking for *non-empty* subsets $A,B$. Here we consider  $\{\{a\},\{b\}\}$ as the only solution.
Comment: Yup! In fact OPs formula is correct. :-)
Comment: @MarkusScheuer, Jon Garrick - In didn't meant that the OP was wrong :-) Just proposed a proof of what I had understood.
Comment: @mathophile: We have six partitions, each consists of a two-element subset and two one-element subsets. In compact notation: $(1,2|3|4),(1,3|2|4),(1,4|2|3),(2,3|1|4),(2,4|1|3),(3,4|1|2)$.
Comment: It seems your formula should be revised.  When setting $n=2$ it produces $5$ instead of $1$, when setting $n=3$ it produces $14$ instead of $6$.
Comment: @Markus Scheuer : I don't see what's wrong with the case $n=2$. Consider  $E=\{a,b\}$; here are the $5$ unordered pairs of disjoint subsets of $E$ : $\{\emptyset,\emptyset\}$,  $\{\emptyset,\{a\}\}$, $\{\emptyset,\{b\}\}$, $\{\emptyset,\{a,b\}\}$, $\{\{a\},\{b\}\}$.
Comment: Ok, so I have to subtract the $2^n$ pairs of the form $\{\emptyset,A\}$ for any $A\subset E$, which leads to $1+\frac{3^n-1}{2}-2^n$.
Comment: @MarkusScheuer Thanks :-)
Comment: @JonGarrick: You're welcome! :-)
Comment: @epi163sqrt Can you show me $6$ cases when $n=3$ because I am getting Only $5$ unordered Disjoint Non-empty Pair.
Answer: We reformulate the problem somewhat and verify OPs formula
\begin{align*}
\frac{3^n - 1}{2} + 1 - 2^n
\end{align*}
by  showing that the  question asks  in  fact for   famous numbers.

We consider  the set $S_n=\{1,2,3,\ldots,n\}$ and ask for the number of non-empty partitions of the set
  \begin{align*}
S_{n+1}=S_n\cup\{n+1\}
\end{align*}
  into three non-empty
  sets.

Note, this number is the same as OPs question  is  asking  for, because whenever we consider an unordered pair $(A,B)$ with $A,B\subset S_n,  A\cap B=\emptyset$ we have one of two cases:

$A\cup B=S_n$: This corresponds to  the partition $S_{n+1}=A\cup B\cup\{n+1\}$ and vice versa.
$A\cup B \ne S_n$: This corresponds to the partition $S_{n+1}=A\cup B\cup \left(S_{n+1}\setminus (A\cup B)\right)$ and vice versa.

The number of ways of partitioning a set of $n$ elements into $k$ nonempty sets is called Stirling number of the second kind and denoted with ${n\brace k}$. They admit the  representation
\begin{align*}
{n\brace k}=\frac{1}{k!}\sum_{j=0}^k(-1)^{k-j}\binom{k}{j}j^n
\end{align*}

Here we are looking for ${n+1\brace 3}$, the number of ways of partitioning a set of $n+1$ elements into $3$ nonempty sets. We obtain for $n>0$:
  \begin{align*}
{n+1\brace 3}&=\frac{1}{3!}\sum_{j=1}^3(-1)^{3-j}\binom{3}{j}j^{n+1}\\
&=\frac{1}{6}\left(\binom{3}{1}1^{n+1}-\binom{3}{2}2^{n+1}+\binom{3}{3}3^{n+1}\right)\\
&=\frac{1}{2}\left(3^{n}+1\right)-2^n
\end{align*}
  which coincides with OPs result.

Note: The sequence $$\left({n\brace 3}\right)_{n\geq 0}=(0,0,0,1, 6, 25, 90, 301, 966, 3025, 9330, 28501,\ldots)$$ is archived in OEIS as A000392.


NoSuchElementException: Message: Could not locate element with index 1 executing select_by_index in loop through Selenium and Python

Question: Page has the following selection box,

  <select name="gender" class="my-dropdown 115px option" data-field="gender" data-type="dropdown">
    <option value="female">Woman</option>
    <option value="male">Man</option>
    <option value="">All</option>
  </select>

Python code
wait = WebDriverWait(driver, 100)
while True:
...
    # status off
    status_btn = wait.until(EC.element_to_be_clickable((By.NAME, "status")))
    if not(status_btn.is_selected()): # If checkbox is unticked
        status_btn.click() # to tick it

    # no photos
    photo_btn = driver.find_element_by_name("photo")
    if photo_btn.is_selected(): # If checkbox is ticked
        photo_btn.click() # to untick it

    #index gender
    # 0 woman
    # 1 man
    gen_select = Select(driver.find_element_by_name('gender'))
    print(gen_select)
    gen_select.select_by_index(1)

It works fine for the first few passes though the loop and then produced this error, the print shows it got the select element and the "object at" is not the old object but it's failing to select it.
<selenium.webdriver.support.select.Select object at 0x000001B2DB740438>
<selenium.webdriver.support.select.Select object at 0x000001B2DCF189B0>
<selenium.webdriver.support.select.Select object at 0x000001B2DB753F98>
Traceback (most recent call last):
  File "LFmale2.py", line 94, in <module>
    gen_select.select_by_index(1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\support\select.py", line 103, in select_by_index
    raise NoSuchElementException("Could not locate element with index %d" % index)
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with index 1

Comment: Turns out there is nothing wrong with the code other than I've split the select by index. Select(driver.find_element_by_name('gender')).select_by_index(0) is correct. I had a large number or orphaned headless browsers from every run that had an error. As they accumulated it made it more likely to fail.
Answer: This error message...
selenium.common.exceptions.NoSuchElementException: Message: Could not locate element with index 1

...implies that the WebDriver instance was unable to locate any element with index 1
I am a bit surprised at the fact that ...works fine for the first few passes though the loop... due to the following reasons:
select_by_index(index)
select_by_index(index) selects the option at the given index. This is done by examing the index attribute of an element, and not merely by counting.
The HTML which you have provided doesn't reflects the index attribute. So ideally the following line:
gen_select.select_by_index(1)

Should have raised an exception in the very first iteration.
Solution
The relevant HTML contains visible_text for all the three options:

Woman
Man
All

So as per best practice you should use the select_by_visible_text(text).

Code Block:
gen_select = Select(driver.find_element_by_name('gender'))
print(gen_select)
gen_select.select_by_visible_text("Man")

Comment: The ``s don't have `index` attribute in the html, but the [option object](https://www.w3schools.com/jsref/dom_obj_option.asp) behind it does.
Comment: @Guy **index** is one of the `Option Object Property`. You have to assign some **value** to this property for _Selenium_ to realize/detect this property before performing any action. Hence the documentation mentions _...done by examing the index attribute of an element, and not merely by counting..._. let me know if that answers your question.
Comment: It wasn't a question. Selenium doesn't realize anything, each `option` has `index` attribute based on its position in the drop down list as part of `option object` properties. Selenium just read this property.


nth Time's The Charm

Question: So, a question came up recently regarding an image macro shared in my work HipChat:

Considering the above statement, each Time i has an equal probability P(i) of being The Charm, but we want The Charm to occur at least once in the set of n Times.
Following this, how would we model the equation to determine the probability of at least one Time i between 1 and a given n being The Charm? I'd assume it's a series with a limit of 1 as n approaches infinity, but it's been too long since college, and I've forgotten how to solve this.
Answer: I hope I understood your question.
I also didn't understand why you were thinking about infinity. Do you want to calculate the probability that you have at least one "successful time" out of "$n$ times", each time independent with probability $p$?
If so - this is a binomial variable. The complement to getting at least one successful time is not getting any successful times at all, therefore you get:
$$P(\text{getting the charm at least once out of n tries}) =1-P(\text{not getting the charm at all}) = \ \ \ 1 - (1-p)^n$$
Comment: Oh, I edited the equation after I noticed that you asked for **at least** 1 and not exactly 1 (you can see the text inside the $P()$ that correspands with that. I will edit the text above as well.
Comment: This explanation doesn't make that much sense; while it matches the equation in @jvdhooft 's answer, the question asked for any successes, rather than exactly one success. Luckily, the equation is correct, so upvotes for you.
Answer: As I understand it, you are looking for the probability that the event $i$ occurs at least one time in $n$ consecutive events. This probability equals 1 minus the probability that it does not happen in $n$ consecutive events, and since this probability is always the same, we have:
$$1-(1-P[i])^n$$
Comment: This answers the question clearly and correctly! Thanks!
Answer: In the abscence of real numbers I am going to model this akin to a dice roll:
Let 6 = "the charm", the odds of this happening for any given dice roll is of course 1/6, but over time we can add these up:
roll 2: the odds are 5/6 * 1/6 + 1/6, this is because it relies on the first roll not being a 6, and then getting a 6, plus the original possibility of getting a six.
Now this is just a matter of series: with each dice roll the odds is 5/6 * (odds of previous dice roll) which is a convergent series, emaning we can use the sum to infinity equation: a/(1-r) where a is 1/6 and r is 5/6, which gives 1, as expected.

nth Time's The Charm


Como faço para alinhar varias divs dentro de um contêiner?

Question: Eu estou com um problema, estou tentando alinhar varias divs dentro de um contêiner, mais especificamente 3, o que desejo é deixa-las todas alinhadas uma do lado da outra, porém uma acaba indo para baixo e não sei como resolver isso, segue o código:

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

html, body{
    height: 100%;
}

.clear{
    clear: both;
}

.container{
    width: 100%;
    max-width: 764px;
    margin: 20px auto;
    padding: 40px 0;
    border: 3px solid rgb(220, 220, 220);
    ;

}

.img-wraper{
    width: 33.3%;
    margin: 10px;
    padding-top: 23.3%;
    padding-left: 23.3%;
    float: left;
   /* background-color: #ccc; */
    position: relative;

}

.img{
    border: 2px solid black ;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;

}

Comment: @RicardoPontual ele até criou um exemplo 100% reproduzível. Mas faltou a formatação. Ele ainda não tem muita intimidade com o site. Ajudei editando a pergunta dele. Ficou filé!
Comment: Essas `` possuem `margin` que influência no **Box Model** (*Modelo de Caixa*, https://developer.mozilla.org/pt-BR/docs/Web/CSS/box_model) e acaba que a largura e altura do elemento sejam todas somadas, assim não cabendo no contêiner pai. Isso é a mesma coisa que você querer entrar de carro pela porta, seguindo o raciocínio o carro é grande e a porta é pequena, então o carro não vai entrar, a mesma coisa acontece no seu exemplo.
Comment: crie um exemplo funcional mostrando como está para entendermos melhor
Comment: agora sim, quando vi a pergunta só havia o codigo
Answer: O problema é que você dividiu o espaço exato do container entre as três div.
Até aí, tudo bem. O espaço de cada delas uma pode ser 33.3%. Se quiser mais preciso, recomendo usar 33.33%. Mas o principal problema é que você colocou uma margem de 10px nessas div.
Para solucionar isso, pode usar a função calc() do próprio CSS. A ideia é que as suas div ocupem 33.3% - 20px. Lembre-se que a margem é de 10px em cada borda! Logo, a largura deve-se considerar 10px à esquerda e 10px à direita. Finalmente chegamos em calc(33.3% - 20px).

Dica #1: pela sintaxe do CSS, não deve-se omitir os espaços entre o operador. Isso é um erro de sintaxe: calc(33.3%-20px).
Dica #2: quando esse espaço extra é relacionado ao padding ou border, você pode simplesmente considerar essas propriedades no dimensionamento geral do elemento com box-sizing: border-box;.

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

html, body{
    height: 100%;
}

.clear{
    clear: both;
}

.container{
    width: 100%;
    max-width: 764px;
    margin: 20px auto;
    padding: 40px 0;
    border: 3px solid rgb(220, 220, 220);
    ;

}

.img-wraper{
    width: calc(33.3% - 20px);
    margin: 10px;
    padding-top: 23.3%;
    padding-left: 23.3%;
    float: left;
   /* background-color: #ccc; */
    position: relative;

}

.img{
    border: 2px solid black ;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;

}

Leitura recomendada: CSS calc()


How do I show the size of an Image file in media2 after selecting the image?

Question: After selecting an Image field using the media browser, in the edit form the selected shows image, an edit button, a delete button, and an "include file in display" checkbox.
How Do I add the size of the image in the same display?
Q2:
In a colourbox popup display, which seems to only pick the "title" , I cant get this to read html. Is there a way of enable html as I need some text in Italics, and in Bold?
Thanks.
Comment: Please ask one question per post. This is Q&A site, not a forum, questions should be separate entities.
Comment: Have made the adjustment.
Answer: I found the solution. Somehow undocumented is the fact that this uses the "Preview" view mode. Editing that and ensuring its the one selected in image view changed everything to working normally.
Thanks.


Will lighter strings extend an acoustic guitar's life?

Question: Will lighter strings extend an acoustic guitar's life?
I just sold an old acoustic I acquired in bad condition and restrung with new nut and saddle, whose bridge was beginning to lift out of the body. I traded it in for a different guitar whose bridge I checked is not lifting.
The new guitar has a set of .10 gauge steel strings on it - unusually light for an acoustic. This got me thinking, if the string gauge and thus tension is lower, would this help avoid pulling the bridge out?
Here's a bonus part of the question, the converse of the title. I normally use .12s on an acoustic, would changing this guitar from .10 to a heavier set, say .11 or .12, be likely to reduce its lifespan? I understand it would probably need a truss adjustment after changing size but even after that how would my working life be affected?
A good answer would probably cite material from luthiers or manufacturers as well as giving from personal experience.
Addition: (Following Scott's answer): The guitar in question is a Yamaha F-310, which is a dreadnought with spruce top, Meranti B&S, all laminate, Nato neck, Rosewood board and bridge. The bridge is quite wide and the guitar has a reputation for having brittle wood.
Comment: Sounds like it needs some restoration work.
Comment: Rob- from your description, my guess would be that your guitar would take the heavier strings with no problems.  But that's just my guess- I haven't seen an F-310 and have no information of other's experiences with them.  You should probably ask someone who knows the instrument and can check yours out.  But even then, there are always imponderables no one can know about.  Sorry I can't give you a definitive answer.
Comment: I may provide an answer when time permits but I would suggest that a reasonable quality guitar such as the Yamaha F-310 should not have any problem with medium strings as long as you are careful to keep it stored in a guitar friendly environment with humidity levels within optimal range.  The bridge on most steel string acoustics (including the Yamaha) have a bridge plate inside the body directly under the bridge and the balls of the strings should actually be secured by this plate so the tension is not directly on the bridge.  Nylon string guitars where the strings are tied - not the case.
Comment: SDsolar you may be confusing the old guitar with lifting bridge in the first paragraph (sold) with the guitar I'm asking about (2nd paragraph on). If you do mean the Yamaha needs work, what sort did you have in mind?

Scott, don't worry, I learnt some new things and I understand absolutions aren't possible as every model and piece is different, so thanks :)

Cowboy, it is on the cheaper end in materials but the workmanship seems good. My usual humidity control is a sponge in half-open bag tucked in the case. I'll watch for any shrinkage etc. When I restring it I'll check under the bridge.
Answer: Okay, here's your answer from a luthier.  Yes, if you change from .10 gauge to .12 gauge strings, assuming that all strings are thicker in this proportion, then there will be 44% more tension on the guitar for the same tuning (because tension is a square factor of diameter at the same pitch).  It's a logical consequence that this means more wear and tear on the instrument.
But what that means as far as the bridge pulling up, or the truss needing adjustment, goes, is not so simple to say.  It obviously depends on the construction of the instrument.  My experience is that guitars (like violins and all other stringed instruments) eventually bend under the tension of the strings, and the more tension, the faster.  That's why we luthiers have to continually reset necks, or adjust truss bars, or whatever.  Lighter strings will slow the process, but perhaps not sound as good for your needs.  There are no simple answers.


How do you write "The sum of all the elements in set A"?

Question: I was in class and the teacher started talking about the mean average. That got me thinking: how would I mathematically represent this? The worded defenition of the mean of set A is "the sum of all elements in set A divided by the amount of elements in set A". I started off with the "amount of elements in set A" bit, which I represented as n(A), though |A| could also work. But I got stuck when it came to the "sum of elements in set A" bit. How would I mathematically represent this?
Comment: $\sum_{a\in A} a$ $(?)$
Comment: @SineoftheTime Assuming that this notation means "the sum of elements in set A", then this perfectly answers my question! Thank you! :D
Comment: @SineoftheTime Do you think you could write your question as an answer? Thanks in advance!
Comment: The comment above is an answer to the question, not just a comment. Please post your answer as an answer. This brings extra visibility to the answer und puts the question off the unanswered list (otherwise it will be bumped up periodically). Also notice that comments are not indexed by the full text search and don't offer all the features that answers enjoy. Comments should only be used to clarify the problem.
Comment: @MartinBrandenburg Ah, I see. Thank you for telling me this
Comment: If he/she doesn't add the question as an answer, am I allowed to? (using the "answer your own question" feature)
Answer: As long as we know that there is a way to add up elements of $A$, then writing $\sum_{a \in A} a$ is perfectly acceptable, as pointed out in the comments—but if you want to have an actual routine (or algorithm) for performing this sum, it would be valuable to have some sort of indexing on your set $A$.
Since you seem to be assuming that $A$ is finite, as you are talking about the cardinality/size $|A|$ of $A$, then it might be natural to think about the set $A$ as an indexed set, meaning that we attach a label to every element which tells us "which" element of $A$ we are looking at. So, if $|A| = n$, we might write $A = \{a_1,a_2,a_3,\dots,a_n\}$.
Now if you want to add up all the elements, this can be written as $\sum_{i = 1}^{n} a_i$. This is the same sum as $\sum_{a \in A} a$, but might fit more naturally with some notation you have seen in previous courses.
Answer: What about the following notation:
$$\sum_{a\in A}a$$
Answer: if the summation operation is defined, then the sum of all the elements in the set can be defined with the set-inclusion relation as follows
$$\sum_{a\in A} a$$


How to compute the adjoint action?

Question: I have some matrix lie algebra $\mathfrak{g}$ and I want to compute the matrix of the adjoint action of $x\in\mathfrak{g}$, $\mathrm{ad}_x:\mathfrak{g}\rightarrow\mathfrak{g}$ given by $y\mapsto[x,y]$. How can I proceed?
I have been told that it should be $\mathrm{ad}_x = x\otimes\mathrm{id} - \mathrm{id}\otimes x$, so I tried to compute it by fixing a basis of $\mathfrak{g}$, computing the tensor of the matrices $x$ and $\mathrm{id}$ and multiplying by the vector representation of some $y\in\mathfrak{g}$. This works fine until I use the canonical basis
$$e_1 = \left(\begin{array}{cc}1 & 0\\0 & 0\end{array}\right),\ \ e_2 = \left(\begin{array}{cc}0 & 1\\0 & 0\end{array}\right),\ \ e_3 = \left(\begin{array}{cc}0 & 0\\1 & 0\end{array}\right),\ \ e_4 = \left(\begin{array}{cc}0 & 0\\0 & 1\end{array}\right)$$
but when I try with a different basis it doesn't work anymore.
Comment: What specifically is $\mathfrak g$?
Answer: You find the matrix of the adjoint action the same way you find the matrix of any linear operator.  Choose a basis $\{v_1,\dots,v_n\}$ of $\mathfrak{g}$ (I'm assuming your Lie algebra is finite-dimensional here).  Now apply your operator to each basis element.  That is, compute $[x,v_j]$ for $j=1,\dots,n$, and express it as a linear combination of your basis elements: $[x,v_j] = \sum_i a_{ij} v_i$.  Then the matrix of $\mathrm{ad}_x$ in the basis $\{v_1,\dots,v_n\}$ is the matrix $(a_{ij})$.
Let's compute a specific example.  Take the Lie algebra $\mathfrak{sl}_2(\mathbb{C})$, with basis
$$
e = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}, \quad
f = \begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix}, \quad
h = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}.
$$
Let's say we want to compute the matrix of $\operatorname{ad}_e$ in this basis.  We have
$$
\operatorname{ad}_e(e) = [e,e] = 0,\quad
\operatorname{ad}_e(f) = [e,f] = h,\quad
\operatorname{ad}_e(h) = [e,h] = -2e.
$$
Thus, the matrix of $\operatorname{ad}_e$ in the basis $e,f,h$ is
$$
\begin{pmatrix} 0 & 0 & -2 \\ 0 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}.
$$
Comment: Is this true for any matrix, $A$  such that  $\text{ad}_A := \bf{a} $,  where $[A, v_j] = \sum_i \text{a}_{i j} v_j$. Could you give a reference for this representation ? I am struggling to find any explicit working examples.
Comment: @user91411 I've added a specific example.  I hope that helps.
Comment: thanks, that helped. So by basis we mean just the elements of the algebra; we do not include the identity element. right ?
Comment: @user91411 By basis, I mean a basis as a vector space.  Lie algebras don't have identity elements.

How to compute the adjoint action?


Relative importance of predictors - Standardized coefficients in Ordinal Logistic Regression

Question: I am a 4th year psychology student. I need some help in understanding the coefficients in ORDINAL logistic regression. According to Williams (2009) "Using Heterogeneous Choice Models To Compare Logit and Probit Coefficients Across Groups", the predictor variables and residuals are already standardized to the logit distribution (variance = π*π/3 ), and, therefore, so are the reported coefficients in SPSS. Therefore, in order to compare the relative predictive strength of my variables in the model, I should just be able to directly compare the coefficients (or the odds ratios). However, how do I account for the differences in CI/standard error in my comparisons?
For example,
variable 1: B=.021, std error = .0068,  Exp(B) = 1.022, 95% CI = 1.008 to 1.035
variable 2: B=.051, std error = .0174,  Exp(B) = 1.052, 95% CI = 1.017 to 1.089
From comparison of Bs - Variable 2 is the stronger predictor, but the std error and CI are much larger. So, what conclusion can I make?
Comment: An addendum: I am thinking of simply converting my variable 1 and Variable 2 to z-scores and comparing their coefficients. Unfortunately, one of the variables has a skewed distribution. Although normality is not an assumption of ordinal regression, I wonder whether it will still bias the betas and the CIs?
Answer: In general, if your predictors are on different metrics, then the subjective assessment of variable importance can not be easily made by simply comparing the raw sizes of the odds ratios.
If all your predictors are continuous, then I think converting the variables to z-scores would be useful for getting a sense of their relative importance. You mention that you have a skewed numeric predictor. I don't think changes anything too much for whether z-scores are appropriate. Ultimately, you have a separate issue of whether you want to apply a shape transformation (z-scores just change mean and variance). If your variable is highly skewed, then consider a transformation, and then z-score the transformed variable.
Some times, you have binary predictors. In that case, the 0-1 scoring is quite intuitive, especially if you have a few such variables.
Answer: If i understand you correctly, and if you have two models to choose from with relatively different Betas, the important is too choose the model based on its accuracy rather than merely strength of Betas... I suggest you compare the models based on other fit indicators such as AIC, BIC as well as the classification accuracy.
The confidence interval and std errors of Individual Betas, are not a good indicator when it comes to what model to choose.
But if you are speaking about two Beta's within the same model, the predictive power is measured through it's coefficient and it's P- value rather than its CI or Std Error of betas.
Also there's a good reponse to similar question of yours here: How to interpret coefficient standard errors in linear regression?
Comment: Thank you for your answer, but my model is an Ordinal regression (cumulative logistic model) not Linear regression - completely different beast, In linear regression, I can make a comparison using Betas, which are standardized coefficients. I can also use the adjusted R^2 as effect size.

For Ordinal Regression, I am not entirely sure that the beta coefficients reported are standardized - although Williams (2009) indicates that it is so.
Comment: However, e.g. Kaufman (1996) - Comparing Effects in Dichotomous Logistic Regression: A Variety of Standardized Coefficients", indicates that it is not so. Williams also suggests full-standardization as a way of addressing this issue, but he employs a program in Stata, and I don't have access to Stata, nor time to learn it, unfortunately.

I am currently looking at whether I can use Kaufman's formula to calculate the standardized coefficients for a series of binary logistic regression models that I broke my original cumulative logistic model into. Maybe that'll give me the response I need.
Comment: ... So I've played with the Kaufman's formula for standardized coefficients, and I can't get it to work for cumulative logistic regression. The coefficients that it produces are very different to the coefficients I get if I run my original model using predictors converted to z-scores. I'd expect the coefficients from Kaufman's formula to be at least somewhat in the ballpark of z-score predictors. Instead, they are closer to the non-standardized betas.
Comment: Yes.. you are right the coefficient in ordinal or logit regression are not standardised... try this.. there is a formula for standardized logit regression Betas (manual calculation, not sure if this formula is the same as the one you used from Kaufman): https://www3.nd.edu/~rwilliam/stats3/L04.pdf


Minimal Lync 2013 Setup

Question: I would like to install a Lync 2013 server at home. What would be the minimum requirements for it? I've seen the requirements and they seem pretty hefty, just want to know what I need for a basic set up. This will be for up to 5 users. I would like users to be able to connect from outside the network as well.
From what I've been able to find, it looks like I'll need 3 servers. A domain controller, a lync front end server, and an edge server (for external connectivity, and it will need 2 network cards). Is that really all necessary? And how would they need to be connected (I've never connected a machine with multiple network cards)? Do they all have to be separate machines, or can I use VMs?
Answer: The requirements you have seen are right :

Lync needs Active Directory : so you need to setup a domain
controler with DNS Role.
You need a Lync Standard Edition Front-End Server (for Mediation
role with SQL Server Express for backend database included).
You need a separate Edge Server (in a DMZ) for external user access (Edge role
cannot be installed on Front-End server).
The Edge server needs 2 network cards : one on DMZ side, the other one on Lan side (how             to setup this is a full other question).
A firewall
For best practices : a Reverse Proxy

Of course, assuming you don't want archiving, monitoring, Persistent Chat, WAC, Enterprise voice nor Exchange UM role.
For Lync servers, install 64 bits OS.
You need an internal Certification Authority Server and external certificates (or you could provide your internal certificates to your external users).
You also need a domain name and public DNS records.
Every servers can be Virtual Machines.
IMHO :
Lync is not really designed to be installed on-premise "at home". It is not a home toy but an enterprise tool. Except if you want to play and learn i would suggest Lync Online.
As a note : this site is dedicated to professional system and network administrators, not for home or development environment.

Minimal Lync 2013 Setup


Is there a method for studying music theory through chiptune?

Question: is there a music course or preferably a book to learn the fundamentals of music but through chiptune and electronic music? something that makes you study, exercise and experiment through these "instruments"?
I admit that the question is a bit particular, so I'll try to add some more detail. It's true it's exactly the music that was made in the old consoles (@Albrecht). If we see it from a musical point of view, it is a very simple genre and on which I think that the theory exercises may not be complicated (and for my ear the sounds remain very distinguishable), if we see it from a more specific point of view, chiptune refers to music reproduced by sound chips such as the commodore, and therefore highly related to its physical limits. I'm intrigued by the idea of learning in this experimental way.
Comment: @YourUncleBob Correct me if I'm wrong, but I was under the impression that chiptune is a very specific subset of electronic music, and I'm not sure how much your recommendations would apply to that specific genre (to be honest, if this question had been asked a year or two ago, I'd have had to google "chiptune").
Comment: Asking for external resources is not wanted here. You should ask for the actual content itself. "How to study music theory using such and such instruments and devices" or something. Though then it might be off-topic for some other reason.
Comment: By "fundamentals" are you excluding how to play music in real time, like through a synthesizer's keyboard?  Will you use only sequencers and software?  Because if you play a keyboard, it hardly matters whether what makes the sounds is hammers hitting strings or wind blowing through organ pipes or current going through a YM2203 chip.  You can use any method at all.
Comment: A quick search on everyone's favourite book shop website reveals titles such as: "Music Theory for Electronic Music Producers", "Simple Music Theory for Electronic Music Production" and "Music Theory for Computer Musicians".
Comment: @ user 45266: I had to google now.  But I just didn't know the term. But we have used this kind of sound 30 years ago on Commodore and Atari .... ;)
Comment: So this must be the sounds I got using Atari and sounds or waves. I don't whether I'll find it. But this must have been a quite different language than programs for OS or Windows.
Comment: Maybe you are looking for links like these: http://www.chrisdonnellymusic.com/adventures-in-chiptunes-part-1-an-introduction/ ...https://journal.transformativeworks.org/index.php/twc/article/view/96/94 ...http://micromusic.net/
Answer: All theory-links (and most questions and answers of this SE)  are giving information and exercises that you can train on any  instrument, especially on keyboards. Look up fundamental theory.
I'll post you the very first best link I'll find when looking for music fundamentals
http://courses.missouristate.edu/MikeMurray/FundPrimer/PDFs/FundPrimerComplete.pdf
Update
This link is no longer valid, but the original can be found here:
http://web.archive.org/web/20201111204310/http://courses.missouristate.edu/MikeMurray/FundPrimer/PDFs/FundPrimerComplete.pdf
Comment: I don't understand why this answer gets a vote. I've looked it up and find it has nothing to do with the question. Nothing at all... I focussed on primer instead of chiptune!


How to load two div from two different div (from html) by clicking the same link

Question: I want to click on a#lanostracasa to take two different divs from an external .html and load it in another two div (the #fotoCasa from the external file havePicture)( http://frostcode.altervista.org and http://frostcode.altervista.org/db.html for the external HTML.)
I'm going crazy because I see the text in the container while I see it loading, and all the text disappears and no content was loaded.

          blablablablablablabla

The link I want to to click:

La Nostra Casa

and the JavaScript that doesn't work:

I also use this call in jQuery for the same link but I don't think it affect the JavaScript:
$("#cssmenu a#lanostracasa").click(function(){
$('#container').load('db.html #lanostracasa-ita')
});

Answer: So you have two events bound to the same element that are, by themselves, contradictory.  You cannot bind the same event (click) twice to the same element.  In this case you have a precedence problem that needs to be addressed.  One function is being fired and one is not, choose which one to use.  Furthermore, if you think of this from a logical perspective...what's the point of binding the same event twice?  If ONCLICK you want two things to happen, just put them both in one function.
Also, you must remember that when binding events to elements, the elements themselves must EXIST prior to binding.  I can't see your HTML to verify that your second .click() event is wrapped in a function closure or $(document).ready() but that may also be a source of confusion.


Diminished Scale Piano Fingering

Question: I'm going to start practicing diminished scales on the piano, but don't want to ingrain incorrect fingerings into my muscle memory. I've found major and minor scales to have pretty standard fingerings for instance C Major is shown as 12312341 most everywhere I look.
Surveying diminished scale fingerings however has confused me as the first 3 websites I found all had different fingerings:
This site says to think of them as two stacked tetrachords and to play them that way ie. 12341234
And then this site and this site have completely different fingerings.
I realize in some cases fingerings are subjective or different depending on hand size (I have longer than average fingers). Is that the case with the diminished scales or what are the advantages for a particular fingering? ie speed, theory, etc..
Comment: I would say that it is very context dependent: do you start or finish half-way the scale, where do the black keys come up in the fingering etc. Regarding black keys, for example, I like to put my longer fingers there (2, 3 and perhaps 4). Try and find what works good for you, in particular with respect to relaxedness: the less cramped things feel, the better.
Answer: There are no rules on this sort of thing, it's far too subjective. Why rely on someone else's idea? Why not try out a few of your own. There are not that many options.Usually, thumbs come in far more usefully on white keys, whereas the longer fingers, usually middle and ring work more effectively on the farther away black keys. But that's not a rule, and rules can be broken.
Whatever works best for your hands and fingers is YOUR best way, so give some options a go. I've seen what I would consider really weird fingerings for some piano playing, often used by self-taught players, but actually they work for those people, and I sometimes think 'actually, that's very effective, but no traditional teacher would show that, as it's not the norm'.
Has the internet taken all of the pioneer spirit out of us?
Comment: I think there's a valid idea behind this question: experts might see pitfalls that beginners want to avoid. For example, once a beginner's technique improves, a certain fingering might limit their speed. That's the sort of info I think apricity is seeking. (While the ultimate decision might be personal, it's not all subjective. For example, no one will suggest a fingering of 1-2-1-2-1-2, etc. and there are objective reasons to avoid it.)
Comment: I agree somewhat. To become an expert needs one to try out all possibilities, eventually finding a personal best way, and realising other ways that could be better for others. Being passive, and relying on others isn't as effective as eliminating all the possibilities. It's called experience. Discovering what works for you is part of the journey, and while that can have shortcuts, there's no reason why some of those missed out ideas wouldn't work for someone. Thus - 'diy'. Obviously some fingerings don't work well - for everybody - but that's part of the fun, finding out yourself. Downvoted?
Comment: We agree on a lot, but I did downvote because I don't think there are "no rules" or that it's "far too subjective." To me it sounds like you're saying there are universally bad fingerings and there's a finite number of fingerings that could work. I think it would be really helpful to list the fingerings that generally work (excluding the ones that definitely don't work), and perhaps explain the reasons why someone would prefer one finger over the other.

Diminished Scale Piano Fingering


Proving an idempotent binary operation where $(x\ast y)\ast z=(y\ast z)\ast x$ is commutative

Question: Let $S$ be a set and $\ast$  be a binary operation on $S$ satisfying
1) $x\ast x=x$ for all $x\in S$,
2) $(x\ast y)\ast z=(y\ast z)\ast x$ for all $x,y,z \in S$.
Show that $x\ast y=y\ast x$.
I haven't got any idea for solving this problem.
Comment: Do we know if $\ast$ must be associative?  If so, note that $(x\ast y)=(x\ast y)\ast (x\ast y)$ and use property $2$ on that.
Comment: @JMoravitz No need to *assume* associativity, that follows from condition 2 after we prove commutativity.
Answer: $$(xy)x=(yx)x=(xx)y=xy$$
$$xy=(xy)(xy)=(y(xy))x=((xy)x)y=(xy)y=(yy)x=yx$$


Algebraic properties of conjugates

Question: I see that normal subgroups are closed w.r.t conjugates (Pinter, A book of abstract algebra, pg. 140).
I would like to ask what are some of the algebraic properties shared by conjugates ($xax^{-1} $ where $x \in G$) of an element $a$ in a group $G$ ? For instance I could observe that conjugate elements share the same order.
And also, how can such properties be derived. For instance how can I show that the order of an element and its conjugate is the same?
I guess this might help in giving an idea about the type of elements contained in a normal subgroup.
Answer: If $b=gag^{-1}$ and $a^n=1$, then $b^n=1$.
Therefore, the set of exponents that kill $a$ is contained in the set of exponents that kill $b$.
Since $a=g^{-1}bg$, we have the reverse inclusion and $a,b$ have the same set of exponents. In particular, their order is the same, being the minimum of the set.

Algebraic properties of conjugates


How can I use GAP to collect words into a normal form?

Question: I would like to be able to give GAP some relations and a word, and have it collect that word into a normal form (say with collection from the left).
For instance, I would tell GAP $ [x_{2},x_{1}]=x_{3} $ and then have it collect $ x_{2}x_{1} $ to obtain $x_{1} x_{2} x_{3} $.
The reason I am interested in this is that I have some large pc-presentations that are not consistent (but which I would like to be be consistent).
I would like to use GAP to do the word collections in the consistency algorithm (Wamsley/Vaughan-Lee), and then to try to use this to inspect where things go wrong so I can try to tweak my presentations.
Here is a small example:
$ G = \langle x_{1},x_{2},x_{3} | x_{1}^{2}=x_{2}, x_{2}^{2}=x_{3}, x_{3}^{2}=1, [x_{2},x_{1}]=x_{3} \rangle $.
Collecting by hand we can see that:
$(x_{1}^{2})x_{1}=x_{2}x_{1}=x_{1}x_{2}x_{3}$
but
$x_{1}(x_{1}^{2})=x_{1}x_{2}$
and hence we deduce this is not a consistent presentation, and that $x_{3}=1$.

Is it possible to do these computations within GAP, and if so, how?
Could you demonstrate how one might do the example above, using GAP.

Thank you
Answer: This functionality is in GAP, but it is not exposed through nice functions. You will want to look at the function GROUP_BY_PCGS_FINITE_ORDERS in lib/pcgs.gi and the functions calles by it. In particular GroupByRws in lib/rwsgrp.gi, as well as the confluence test in lib/rwspcgrp.gi.
There is a bit of description in the manual https://www.gap-system.org/Manuals/doc/ref/chap46.html#X8581887880556E0C
but it will require some trial and error. It would take me a couple of hours to extract a meaningful example, thus the vague answer.
Comment: This answer was helpful to point me to relevant functions and hence I have made it best answer. If I manage to construct a meaningful example I will post it here in future. Thank you.


converting multiple BAM files to BED files

Question: I have BAM files in the external hard drive. Want to convert them into BED.
Am using
cd /media/amit/LaCie/mdc_work/chigozie/pool1/bam
for x in *.bam ; do
    echo "print current:$x";
    bedtools bamToBed -i "$x" > "${x%.bam}.bed";
done
echo "done"

it writes the BED files in the directory, but they are all empty. My BEDtools is installed in
/home/amit/miniconda3/bin/bedtools

Can someone tell me where I am going wrong?
regards.
Comment: cross posted: https://www.biostars.org/p/473555/  : the command should be `bamtobed`.
Answer: Empty bed files could be caused by bam files with no reads. The bam files could still have non-zero file size due to headers. Find the number of reads in the bam file using samtools:
samtools view -c input.bam

or sambamba:
sambamba view -c input.bam

This should output into STDIN the number of reads in the bam file. Both of these could be installed using conda, for example like so:
conda create -n my_env_name samtools sambamba


Can varnish serve from a port and clone the request to another port?

Question: I have a problem to solve in my current deployment. The current one looks like this.
Varnish on port 80 in front of Nginx on port 8000 backed by uWSGI
The problem here is, The client want to implement some in house analytics which are required for business logic, implemented in Python served with uWSGI. Most of the varnish hits are gone uncounted (Hits are Anonymous). Two solutions came up are.

Hit a non cached server from clients (Here clients are Android devices. Two Requests per request are very costly in terms of battery usage
Proxy or clone the requests at varnish to another server where the analytics server can ingest the request. May be with UDP.

Is the 2nd solution relevant? Is it possible to do this? If yes, how can someone do this?
Answer: vmod_curl
It is possible to send an extra request to an external endpoint. I would advise you to do this through vmod_curl, a cURL module for Varnish.
See https://github.com/varnish/libvmod-curl for more information.
However, sending an extra call for every incoming request can be quite taxing on your analytics system. The reason why you're probably using Varnish is to avoid that your origin systems get overloaded.
Varnish's logging & statistics tools
And when it comes to analytics, the tools that Varnish provide are second to none.
Here are some references regarding Varnish's logging & statistics tools:

http://varnish-cache.org/docs/6.0/reference/varnishlog.html
http://varnish-cache.org/docs/6.0/reference/varnishncsa.html
http://varnish-cache.org/docs/6.0/reference/varnishstat.html
http://varnish-cache.org/docs/6.0/reference/varnishtop.html

The logging (varnishlog, varnishtop & varnishncsa) tools are based on VSL, so here are some VSL references:

http://varnish-cache.org/docs/6.0/reference/vsl.html
http://varnish-cache.org/docs/6.0/reference/vsl-query.html

And finally, here's a reference to the counters that are used by varnishstat: http://varnish-cache.org/docs/6.0/reference/varnish-counters.html


Contact form module for different users

Question: I am looking for a contact form module for different users logged in to the website.
E.g.,
1) a website that has different authors
2) the user clicks on the author's page there is a contact form for that specific author on their page
Any suggestions?
Comment: Welcome to Drupal Answers. Have you looked at the contact form module that is part of the core? It seems to fulfill your requirements. And if that does not do what you want, please explain what extra features you're looking for.
Comment: Can the contact forum module send out to specific users? And not just the default user? And can this be embedded on a specific user page?
Comment: Yes, yes, and almost - it is not *embedded* in the page, but it put's a "Contact" tab on the user's page.
Answer: You should be able to use the core contact form for this.
Basic documentation about setting it up can be found in the user contributed documentation on Drupal.org.
The contact form let you have a site contact form (sent to the default user), and a contact form tied to each individual user. When you enable the latter option, a tab "Contact" will appear when someone visit's that user's page (provided they're permitted to see it).
Individual users may disable other's access to their contact form, but the administrator may override this.
The core contact form can be configured through options and permissions.  It is very flexible, but it may take some tuning to get the exact behavior you want.
Answer: The Privatemsg and Message Private allow your site's visitors to send private messages to each other. Using these modules you can allow users to send private messages to the authors.
you can also use webform module.

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

In this module you can add an author field which lists all of the authors and on every author page, only displays its name. using hook_form_alter you can set the current author as the value of the author field.
As another solution, You can create a unique form for every author, in this way you can configure the form for every author (including unique email address).
It is easy to display different webforms in authors page. The following code loads and displays a webform with client-block-852 id
<?php
    $block = module_invoke('webform','block_view' ,'client-block-852');
    print render($block['content']);
?>

so in hook_preprocess_page check for the current page (using url or anything else) if it is an author page, loads its appropriate webform.

Contact form module for different users


Sistema de pesquisa PHP sem MySQL

Question: Eu tenho um site com vários arquivos HTML, e pretendo fazer um sistema de busca em PHP, que me procure por palavras nesses arquivos HTML, e que me mostre a página ou as páginsa em que elas se encontrem mas sem usar MySQL.
Como posso fazê-lo?
Comment: Não estou com tempo de escrever uma resposta, mas uma ideia inicial seria listar todos os arquivos .html de determinada pasta, e então percorrer cada um deles usando `strpos` pela sua busca.
Comment: com `file_get_contents` + `stripos` (ou preg_match) é possível fazer, porem *provavelmente* o desempenho será "bem ruim", para isto você deverá indexar as pesquisas ou os arquivos e neste caso será necessário um estrutura de banco de dados, não precisa ser sql, pode ser um ficheiro que trabalha por linhas, não posto uma resposta pois é um pouco demorado de montar tal sistema, mas este é o caminho.
Answer: "Em PHP" é o problema maior aqui, a meu ver.
Se o site usa somente arquivos HTML, pode até ser razoavelmente simples, mas independente de como você faça você provavelmente vai ter problemas com tags HTML sendo indexadas para a busca, sem contar na velocidade da busca e n outras questões. Sistema de busca é um negócio bastante complicado e tem muitas "nuances" a serem consideradas.
Algumas questões relevantes pro seu caso específico:

Isso precisa rodar em Linux ou em Windows?
Esses arquivos são 100% estáticos ou possuem conteúdo gerado por PHP?
Caso sejam estáticos, quão comum é alterar esses arquivos?

Minha sugestão é bem simples:
Faça uma caixa de busca que usa o Google, usando "site:minha.url.com ".$search_params para ter os melhores resultados mais rápido.
Se você precisar fazer esse buscador do zero ou tiver outras exigênncias, desenvolva melhor o objetivo que você quer atingir e o porquê, para podermos nos aprofundar no assunto.
Comment: Ele deixou claro na pergunta que são arquivos html, então provavelmente são `.html`, em outras palavras, estáticos. Se é Windows ou like-unix sinceramente não vejo por que levar isto em consideração se estamos geralmente usando as APIs do PHP.
Comment: @GuilhermeNascimento, ele disse que tem vários "arquivos HTML", e eu posso usar `.html` na extensão, chamar de html, e rodar PHP, Ruby, LISP ou o diabo no arquivo se eu quiser. A questão era se havia dinamicidade de conteúdo. Sobre ser Windows ou Unix, é porque uma das características do PHP são as funções `exec()`, `shell_exec()` e similares, que permitem aproveitar APIs do sistema, e que são uma ótima opção se você precisar percorrer um número razoável de arquivos com performance mais próxima à nativa, rodando a partir de uma linguagem interpretada.
Comment: ok, parece legal.
Answer: Essencialmente, o que pretendes é usar PHP para localizar uma string dentro de ficheiros.
Duas opções, cada uma mais adequada para a versão de PHP que estejas a utilizar:
PHP > 5.0
Fazendo uso da classe DirectoryIterator, podemos percorrer uma pasta cheia de ficheiros e um a um localizar a string pretendida:
// Palavra a localizar
$string = 'bubu';

// Iterar caminho para a pasta que contém os ficheiros
$dir = new DirectoryIterator('minhaPastaCheiaDeFicheirosHTML');

// Por cada ficheiro
foreach ($dir as $file) {

    // Ler conteúdo do ficheiro para variável
    $content = file_get_contents($file->getPathname());

    // Ver se encontramos a string para fazer algo
    if (strpos($content, $string) !== false) {

        // Ena, encontrei, e agora?
        echo $file->getPathname();
    }
}

PHP >4.3.0
Para versões mais antigas, podemos fazer uso da função glob(), um pouco mais lenta que a solução em cima, mas perfeitamente eficaz:
// Palavra a localizar
$string = 'bubu';

// Caminho para a pasta que contém os ficheiros
$dir = 'minhaPastaCheiaDeFicheirosHTML';

// Por cada ficheiro localizado
foreach (glob($dir."/*") as $file) {

    // Ler conteúdo do ficheiro para variável
    $content = file_get_contents($dir."/".$file);

    // Ver se encontramos a string para fazer algo
    if (strpos($content, $string) !== false) {

        // Ena, encontrei, e agora?
        echo $dir."/".$file;
    }
}

Sistema de pesquisa PHP sem MySQL


how to get new mysql connector for c#

Question: I have an application that has been using the MySQL connector without problem until recently.  I have been packaging MySql.Data.dll with each client app installation.  Now I get error:  Unable to connect to any of the specified MySQL hosts.  So I'm thinking I need new MySQL connector.  So I go to http://www.mysql.com/products/connector/ and see there is no longer one for c sharp.  Then I go to http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html and see that I have to install MySQL on my developer box and possibly every client this application is installed on.  I really hope I'm missing something.  How do I get a new MySql.Data.dll to include as a reference in my c sharp app?  Thanks in advance.
Comment: Make sure you read the licensing restrictions for the MySql connector, they are pretty strict and has pretty broad implications for your app.
Comment: well it won't matter much if I can't use them right now.
Answer: You can get MySQL.Data from NuGet:
<code>Install-Package MySql.Data
</code>
If you must get it from MySQL's website directly, it's still there.  It's actually the top item on the page you linked, it's just called "ADO.NET Driver for MySQL (Connector/NET)".
Comment: I'd rather get it from MySQL if possible.  How is this different that what is at MySQL site?
Comment: That *is* from MySql, they publish the package and is the recommended way to get it. The difference is you don't have to make your users run an installer. NuGet is preferred, its easy to update packages and move from one development system to the next.
Comment: It's a lot easier to get it from NuGet (as Ron mentions, it's still from MySQL!), but you can still get it from MySQL: http://dev.mysql.com/downloads/connector/net/
Comment: ok ok I'm sold ... so I assume I need to install the nuget package manager?  then when I do an install-package MySQL.data ... does a MySql.Data.dll pop out somewhere that I include with my app or is it different now?
Comment: You don't need to install MySql.Data.  It will be in your bin directory, along with the other references.  An installer should package it up automatically.

how to get new mysql connector for c#


Cannot update modules with drush – needs higher bootstrap level

Question: As stated in this answer Drush needs to find the settings.php file in order to work. My problem is that the settings.php file is indeed in the right folder (and I have navigated to the Drupal root folder before issuing the Drush commands), but it still does not work to update modules with drush. I just get the message that Command pm-update needs a higher bootstrap level to run. It even states itself that the Drupal settings file is located in sites/default/settings.php.
This is the error message:
C:\wamp\www>drush ups
Command pm-updatestatus needs a higher bootstrap level to run - you      [error] will need to invoke drush from a more functional Drupal environment
to run this command.
The drush command 'ups' could not be executed.                           [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

I have also followed the instructions in this post, with no luck.
What else can I try?
Comment: Yes I am. In my case it's C:/wamp/www
Comment: try with sudo, ex: `sudo [your drush command]`
Comment: Sorry, I should have mentioned that I am on Windows 7. No sudo command available. But I will try to run as admin...
Comment: And no, that didn't do the trick either.
Answer: Finally I found an answer that I could adapt to my WAMP environment here. I simply added C:\wamp\bin\mysql\mysql5.7.14\bin to the PATH, and then Drush worked also for updates.


Validação de formulário ASP.net mvc!

Question: Tenho um formulário que faz a validação dos campos ao tentar enviar informações, só que tenho uma opção de "novapagina" onde eu não gostaria de validar os campos, seria isso possível?
Na views

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.ValidationSummary(true)

                @Html.TextBoxFor(x => x.login, new { placeholder = "correo electrónico", @class = "form-control input-lg" })
                @Html.ValidationMessageFor(x => x.login)
                @Html.TextBoxFor(x => x.senha, new { placeholder = "password", @class = "form-control input-lg", type = "password" })
                @Html.ValidationMessageFor(x => x.senha)

                <button class="btn btn-lg btn-block btn-primary " type="submit" name="opcao" value="pesquisar" >Login...</button>
                <button class="btn btn-lg btn-block btn-warning " type="submit" name="opcao" value="novapagina" >¿Olvidó la contraseña?</button>

    if (TempData["msg"] != null)
    {

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
            @TempData["msg"]

    }
    else if (TempData["erro"] != null)
    {

            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
            @TempData["erro"]

    }

}

No Controller
        [HttpPost]
        public ActionResult Index()
        {
            string opcao = Request["opcao"];

            if (opcao == "novapagina")
            {
              return RedirectToAction("index", "RecuperaSenha");

            }
            else
            {
                //aqui vai pesquisar o login é senha
                return View();
            }

        }

Comment: Você tem um formulário e dependendo de uma opção dele, você irá ou não solicitar autenticação? Você está controlando esta opção através de dois submits na página razor?
Answer: Qualquer controle da página que for do tipo "submit", vai passar pelas validações. O que você pode fazer é mudar o seu botão de redirecionamento, para um href, e deixar apenas o outro como "submit", fazendo o redirecionamento pelo Razor. Tenta assim:

 <button class="btn btn-lg btn-block btn-primary " type="submit"
     name="opcao" value="pesquisar" >Login
 </button>

    Nova Página

Comment: sua resposta foi perfeita, muito agradecido pela ajuda.
Comment: opa, fico feliz por ajudar =)

Validação de formulário ASP.net mvc!


Capacity of a communication channel

Question: I'm trying to find the capacity of a discrete memoryless communication channel with the following probabilities:

This example is completely worked out in my course. But I'm having trouble understanding some parts of it. The complete example is:
We have to find the input distribution that maximizes $I(X;Y)$ in order to find this channel's capacity. We know that:
$I(X;Y) = H(Y) - H(Y|X)$.
$H(Y|X)$ can be found like this:
$H(Y|X) = P(X=a)*H(Y|X=a) + P(X=b)*H(Y|X=b) + P(X=c)*H(Y|X=c)$
Based on the input-output relationship of the given channel, it is clear that for all 3 cases X = a, X = b and X = c, Y a ternary random variable is with probabilities 0.25, 0.25 and 0.5. This means that:
$H(Y|X=a) = H(Y|X=b) = H(Y|X=c) = 1.5$.
The example goes on after this, but I'm having trouble understanding why Y is a ternary random variable with probabilities 0.25, 0.25 and 0.5. I also don't understand where the values $H(Y|X=a) = H(Y|X=b) = H(Y|X=c) = 1.5$ come from?
Answer: $H(Y|X=x)$ is just the entropy of $Y$ conditional on the knowledge that the realised value of $X$ is $x$. Hence:
$$H(Y|X=a) = \Pr(Y=a^\prime | X=a) \log \Pr (Y=a^\prime | X=a) + \Pr(Y=b^\prime | X=a) \log \Pr (Y=b^\prime | X=a) + \Pr(Y=c^\prime | X=a) \log \Pr (Y=c^\prime | X=a) $$
Notice, however, that
$$ \Pr(Y=a^\prime | X=a) = \frac{1}{2} $$
$$ \Pr(Y=b^\prime | X=a) = \frac{1}{4} $$
$$ \Pr(Y=c^\prime | X=a) = \frac{1}{4} $$
And so on.
Comment: Ah I see :) Thank you very much!

Capacity of a communication channel


Adding/ Editing list of people with photos

Question: I've created a content type called 'Cast'. Authorized users need to have ability to create a different list of cast members, add/edit their info, upload photo. Essentially, it's a team roster problem.
I'm having hard time figuring out how to solve this problem? What module is most suitable for this purpose?
Answer: You can do it using Drupal Core itself with out using any module. Just follow below steps to solve the problem.

Login as Super Admin
Go to admin/people/permissions/roles
Add a new role called "Cast Manager"
Give Edit any and Create new "Cast"  Content Type permission to "Cast Manager" role in admin/people/permissions/roles

That's it ! Now, users who have "Cast Manager" role can edit any cast content and manage them !


Data augmentation

Question: In many papers on CNN,I have read that data augmentation is carried out on a per epoch basis. My thoughts regarding this were that data augmentation is carried out prior to starting the training procedure on the train set. What I mean is that split the data into train and test, and then augment the train data. Is carrying out augmentation on a per epoch basis the recommended method, and are there any flaws/drawbacks regarding my understanding of the augmentation procedure?
Answer: Usually when training deep networks, it is common to use mini-batches for training. Data augmentation is applied on these mini-batches. This in-effect causes you to have almost infinite data as in each epoch a new example is seen by the network and thus enables the network to generalise well.
If you just augment the training data before starting the training, it could still be useful in increasing the size of the dataset ( for example if you combine augmented and non-augmented sets). But in this case, after each epoch the network would see exactly the same training examples as it saw in the previous epoch and so might not generalise as well as it would in the first scenario.
Refer to this paper http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf

Data augmentation


Exclude more then one date

Question: I'm new to Drupal. I'm trying to make a work calendar.
I need to make weekly events in the calendar. And that's working real well but now I want to exclude dates from an event.
Is there a way to select more than one date at time?
Answer: I think there are 2 possible approaches, as further explained below (I'm assuming you're using Drupal version 7, not 6).
Use a boolean field to exclude from the calendar
For the content types that you want to include in your calendar, add a boolean field like "Exclude from Calendar" (Y/N). When creating your view, filter out the nodes that have a value of "Y" for this field.
Use 'Views Contextual Filters OR'
Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

... provides a views plugin which modify query to support OR conditions for contextual filters.

With that, you might be able to specify the various dates to be excluded, with something like date1 OR date2 OR ... (if you only have a few dates to be excluded o course).
Does this help?

Exclude more then one date


StackExchange.Redis: No connection is available to service this operation: SET

Question: I created a Console Application running on .NET Core 1.1 and I'm referencing the StackExchange.Redis NuGet package, version 1.2.3
When running the code below, I get the following error:
It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING
using StackExchange.Redis;
using System;

namespace RedisConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase db = redis.GetDatabase();
            db.StringSet(BitConverter.GetBytes(5), "asdf");
        }
    }
}

If I change the Connect string to "localhost,abortConnect=false", then I get this error message:
No connection is available to service this operation: SET \u0005\0\0\0; SocketFailure on localhost:6379/Subscription, origin: Error, input-buffer: 0, outstanding: 0, last-read: 1s ago, last-write: 1s ago, unanswered-write: 27780s ago, keep-alive: 60s, pending: 0, state: Connecting, last-heartbeat: never, last-mbeat: -1s ago, global: 20s ago
I followed the Basics guide to get started using this library but I keep getting the errors above.
Am I missing some code or configuration?
Comment: The error in both cases means that the client cannot connect to your redis server. On which port is your redis server running on your local host? Do you have configured a password? Can you connect with redis-cli?
Answer: It sounds like you might have only set up the StackExchange.Redis client, did you install and start up your local Redis server? If not, use HomeBrew to download and install Redis on your machine
brew install redis
brew services start redis

and start the server with
redis-server

Answer: Try adding ssl=True,abortConnect=False,sslprotocols=tls12 under your connection string


Google Wallet for digital goods - building the tutorial

Question: So I'm working on getting Wallet for Digital Goods going and running into a few problems getting a Java sample up and running.
Problem #1 - I was trying to build jsontoken package and it references other packages and therefore the problem. Fortunately someone posted a jar file and am now using that.
Problem #2 - Am using the sample java snippet at link below to get the getJWT() function to work:
https://developers.google.com/commerce/wallet/digital/docs/tutorial#2
Using the above mentioned jsontoken lib.
I'm getting undefined for

JsonObject
The type org.joda.time.Instant cannot be resolved. It is indirectly referenced from required .class files    main.java   /jsontoken/src  line 1  Java Problem
I can also see some other problems ISSUER, SIGNING_KEY, Issuer class etc.

After some searching, I added:
gson-2.2.4.jar and guava-gtw-14.0.1.jar files.
and am now down to undefines for
org.joda.time.Instant
ISSUER
SIGNING_KEY

Before I invest too much time, I just wanted to make sure I was headed in
the right path.
I'm planning to sell digital-goods over the web (not in-app) and was planning
to use WALLET FOR DIGITAL GOODS api - correct???
Looking at the state of these sample tutorials - is it a little bit too early
to look at it or hold off a few months.
Comment: _"digital-goods over the web (not in-app)..Digital Goods API"_ Yes. Correct. I can't help with hour JAVA questions, but if you want to see how it works on the web - [here's a sample (.Net)](http://code.edchavez.com/simple_demo) just so you see the flow.
Answer: The "Resources -> Samples" section of the documentation contains a fully working sandbox Java sample including the source code. Give it a try at:
https://developers.google.com/commerce/wallet/digital/docs/samples#iap-java


How does one enable system paste in vim using zsh shell in Ubuntu?

Question: I've recently changed shell from bash to zsh and I'm having a problem in vim, in that my system paste no longer works. Before changing shell, I was able to paste from my system clipboard using =+p but now for some reason, unknown to me, the - and + keys are now bound to go up a line and down a line respectively, stopping paste from working.
I'm also using oh-my-zsh plugin manager for zsh and my operating system is Ubuntu Linux.
I can post my .zshrc and .vimrc on request, although there are no recent changes to my .vimrc.
I'm not sure what is causing the + and - key mappings and I would like to know how to re-enable system paste functionality?
Any help would be greatly appreciated.
Comment: When you said `=+p` did you mean `"+p`?
Comment: Yes! That was my mistake all along, I don't know what I was thinking.
Comment: Why is this off-topic?  What is more pertinent to programming than the editor one uses to write programs with?
Answer: A "safer" way to paste from the system clipboard is to use the OS-wide paste-combo shiftinsert. It's equivalent for copying is ctrlinsert. It works on pretty much every platform and doesn't care how you've set up your clipboard. I'm not sure if it plays nicely with Gvim though, atleast it doesn't on Windows.
Adding to that, you may want to toggle paste mode when doing a paste so it doesn't try to interpret and align whatever you're pasting. Toggle it insert mode by pressing F3:
set pastetoggle=<F3>

This does however not answer your question as to why the behaviour has changed, but it might be nice to know anyway.
Comment: @silleknarf If it pastes anything, it's working as intended, even if it'll indent whatever is pasted in an odd way. This is because Vim interprets it as normal input and tries to understand it, but in most cases fails. Thank you for the accept, but it'd be interesting to see why zsh/ohmyzsh could break something like this. If you find out why, do post why :-)
Comment: Thanks for the tip, I've added that to my `.vimrc`. Using the OS-wide paste combo doesn't always work properly, without that, in vim. I think I'm going to accept your this question because it has somehow resolved itself and returned to normal behaviour. Although, I would still be interested to know what might have caused it.
Comment: See the comment on the question, silly error on my part!


Do a find but make its replace elsewhere

Question: I want to search for the variable name in a file and see if it is present in the format preceded and succeded by <%= and remove it if it is
eg.find the variable name from below(i.e invalidChars) and search if it is present in format <%=invalidChars%> and convert it to invalidChars
Example
var invalidChars = "getText('po.number.has.invalid.chars')" />';

/* Some random text */

alert('<%=invalidChars%> ')

I used var (.*?\w+).* to find variable name i.e invalidChars but now how do I replace this at the postion later in file  i.e convert alert('<%=invalidChars%> ') to alert('invalidChars') in a single or multiple operation ,how do I use this value obtained in my next search as I cant use find <℅=$1=℅> with $1
Comment: So what's the expected output?
Comment: You can't do that in a single find-and-replace. That's two operations you need to perform.
Comment: What is wrong with `<%=(\w+)%>`? See https://regex101.com/r/uB2vQ2/1
Or am I missing something completely?
Comment: @user3820163  you can use following to match ONLY word. `(?<=<%=)\w+(?=%>)`
Comment: hi I have edited my question , hope it makes easier to understand now
Answer: Try this regular expression replace.

Find what: (var\h+)([^\h=]+)(.*)<%=\2%>
Replace with: \1\2\3\2
check in the lower left: Regular expression and . matches newline

Click a few times Replace, if you are sure it does what you want (also in complexer scenarios involving several variables): click Replace All. If it does not work use Undo.
In case that several var definitions and the position of their usage overlaps: Replace All will only replace the outer var. Keep clicking Replace or Replace All until no more replacements are done (watch the statusbar of the replace dialog).


Howto redirect all SSDP packets to a specific interface via iproute2?

Question: I have a faulty app which is sending SSDP packets on the wrong interface. I made the dev aware of the problem and it will be fixed in the new release but in the mean time I was hoping I could use iproute2 as a stop-gap measure to shore up this problem.
Basically, any SSDP packets going out on interface 'eth0' I want to go out on interface 'br0' instead.
In case it matters, all of these packets are destined for 220.127.116.11
Answer: Found out the answer is:
<code>ip route add 188.8.131.52/32 dev br0
</code>


Javascript ativando o action do formulário

Question: Situação:
Tem o formulário e uma das opções que eu quero é que ele de um resultado da soma de variáveis automaticamente clicando num botão ou pode ser sem clicar, apenas o usuário só digitando os valores.
O problema é:
ele já esta ativando o action para a pagina de processamento em php sem o usuário terminar de completar o formulário. Como poderia fazer para mostrar o resultado da soma em baixo do botão somar (o mesmo que está ativando o action)?
código no header:

agora o código dentro do formulário html que chama a função acima:
<legend>Calcular total.</legend>
<button id="calcular" onclick="calcula()">Calcular</button>

Aceito sugestões para se fazer de outra forma ou outra linguagem.
Comment: Nada nesse código está acionando o action, mas o `document.write` está sobrescrevendo o documento inteiro.
Comment: O usuário coloca os números nas variáveis, gostaria de um botão ou mesmo que a soma desses campos fossem feitos e mostrados. o código ai faz parte dentro do formulário em HTML, eu poderia usar `alert(soma);` ele mostra o resultado (como eu quero) só que depois o formulário da o action para eu tratar as informações em outra pagina PHP, mas eu não quero isso. Quero apenas mostrar o resultado dessas variáveis somadas automaticamente dentro do próprio formulário que o usuário está preenchendo.
Comment: Uma coisa q tb pode ser feita é colocar a chamada da função calculo no onchange dos input dos valores, assim vc tem o valor da soma antes de pressionar o botão.
Answer: Por defeito, o <button></button> submete o formulário quando se carrega no botão.
Este comportamento pode ser alterado indicando type="button" (jsfiddle).
<button id="calcular_btn" type="button" onclick="calcular()">X</button>

Alternativamente, pode-se suprimir a submissão devolvendo o valor false no evento do botão (jsfiddle 1, jsfiddle 2).
<button id="calcular_btn" onclick="calcular(); return false;">X</button>

Existe ainda uma terceira forma de suprimir a submissão: através do preventDefault (jsfiddle DOM simples, jsfiddle jQuery).
$('#calcular_btn').click(function (e) {
    calcular();
    e.preventDefault();
});

Comment: Excelente! bastou um simples `return false` dentro do botão.
Então removi o `document.write` e ao invés dele usei `document.getElementById("soma").value = soma;` ele retorna o resultado para um campo de texto HTML `` que fica em baixo das outras variáveis  como eu queria.
Answer: Se o que você precisa é cancelar o envio do formulário o ideal é adicionar o código abaixo ao seu javascript
document.getElementById('id-do-form').onsubmit = function() {
    return false;
}


How to set a tmp env variable from inside a bash script

Question: I have a simple bash script:
#!/bin/bash

export MONGOMS_DOWNLOAD_URL="https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1804-4.2.8.tgz"
export MONGOMS_VERSION="4.2.8"

but when i run this './preinstall.sh' and then echo $MONGOMS_VERSION the var is not set.
If i export these vars directly in the terminal there is no issue.
https://stackoverflow.com/questions/496702/can-a-shell-script-set-environment-variables-of-the-calling-shell#answer-496777
According to this post, a shell script has read only access to the parent and any vars set will be lost.
Is there a way around this?
Answer: Use:
source ./preinstall.sh

or for better portability:
. preinstall.sh

source is a synonym for dot/period '.' in bash, but not in POSIX sh,
so for maximum compatibility use the period.
. (source or dot operator)

Read and execute commands from the filename argument in the current
shell context.

See: . (source or dot operator)
Answer: You need to source ./preinstall.sh. There are two ways to do that:
source ./preinstall.sh

or
. ./preinstall.sh

Bash, as does ksh and zsh  supports both . and source. It reads and executes the contents of the specified file in the current shell as opposed to in a new process.
Using the bash shell:
$ type source
source is a shell builtin
$ type .
. is a shell builtin
$ source --help
source: source filename [arguments]
    Execute commands from a file in the current shell.

    Read and execute commands from FILENAME in the current shell.  The
    entries in $PATH are used to find the directory containing FILENAME.
    If any ARGUMENTS are supplied, they become the positional parameters
    when FILENAME is executed.

    Exit Status:
    Returns the status of the last command executed in FILENAME; fails if
    FILENAME cannot be read.
$

POSIX specifies the dot (.) special builtin but is silent about source. From the standard:
NAME
dot - execute commands in the current environment
SYNOPSIS
. file

DESCRIPTION
The shell shall execute commands from the file in the current environment.

If file does not contain a <slash>, the shell shall use the search path specified by PATH to find the directory containing file. Unlike normal command search, however, the file searched for by the dot utility need not be executable. If no readable file is found, a non-interactive shell shall abort; an interactive shell shall write a diagnostic message to standard error, but this condition shall not be considered a syntax error.

OPTIONS
None.

For maximum shell script portability you should only use the dot command with no arguments.
As an aside, I recommend you use absolute paths instead of relative paths if you are sourcing from scripts whose location may change.


Nginx SSLInsecureRenegotiation equivalent

Question: I'm currently migrating our ssl setup from apache to nginx, but I've hit a roadblock. In our apache config we have SSLInsecureRenegotiation on due to some incompatibility issues with safari. I can't find the equivalent command in nginx. Is there one?
Comment: That renegotiation vulnerability is from 2009 - are you sure you still need to support the old broken version?
Comment: All I know is we were finding that current safari on osx wasn't working, and then we added that and it was fixed, but it could be we were doing something else wrong.
Answer: You should look into the viability of just losing that particular option. As the name suggest it's insecure!
Nginx currently (since 0.8.23) does not do TLS renegotiation at all, anyway.
Also, while I realize you seem to be in a position where compatibility with broken clients seems to be more important than security (unfair argument: why are you using TLS, if you're going to poke holes in it?), I suggest checking your site with Qualys SSL Labs's SSL Server Test.
Comment: With nginx the problem doesn't seem to occur. Could be a fault of faulty testing on our part previously, but who knows. Anyway, sometimes ignoring the problem is the best solution :)


Zip file uploaded through Lambda+API gateway with POSTMAN is corrupted

Question: I am doing following steps:

I have API gateway ( PUT Method) which integrated with AWS lambda.
It is direct mapping in multipart/form-data ( so big logic is happening here )
Now through POSTMAN, file is being uploaded.
File is getting uploaded.
When I download this ZIP file, It says "End-of-central-directory signature not found.  Either this file is not a Zip file, or it constitutes one disk of a multi-part Zip file."
Then I opened the ZIP in notepad++ ( yes i did that ), I can see only few line with binary data, on other hand my original file has lot of it.

Please help, let me know if some more needed.
Comment: Hi Anand, Can you please share your code i'm trying to do something similar (i'm a newbie in nodejs)
Answer: I had the same issue and it turned out I was sending the request without all needed headers. It worked fine with Postman. Please check if your request contains these postman-headers