Adding a webform in a webform confirmation

Question: I've been given a requirement to allow for a webform to be inserted into another webform's confirmation page.
At first I tried this with a token I could insert into the confirmation message, the form appears fine, but of course, the new webform is inside of the "parent" webform, which strips out the form tag.
So now I have overriden a few of the webform and webform submission entities handlers, so I can write my own custom getCustomForm function, I can get the new form appearing, but the submit behaviours are weird.
I've tried many things including:
<code>return Webform::load(
    $webform->getThirdPartySetting('my_module', 'webform')
)->getSubmissionForm();
</code>
and
<code>$form['confirmation'] = [
    '#type' => 'webform',
    '#webform' => $webform->getThirdPartySetting('wwf_fields', 'webform'),
    '#source_entity' => $webform,
    '#message' => [
        '#type' => 'inline_template',
        '#template' => $webform->getSetting('confirmation_message')
    ]
];
</code>
Is there some combination of code I'm missing, or am I trying to bend the system a little too much?
Thanks!
Answer: Could you not just redirect after a submission so it goes to a node page that has the other form on it? Rather than trying to put the webform into the message? As that message content could be in a drupal message rather than page content
Comment: I could, but thats something I've been asked to avoid if possible.


ntp.conf pool vs server directives

Question: I came across an ntp.conf file that specifies pool directives:
# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
# on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for
# more information.
pool 0.ubuntu.pool.ntp.org
pool 1.ubuntu.pool.ntp.org
pool 2.ubuntu.pool.ntp.org
pool 3.ubuntu.pool.ntp.org

Yet it also has server directives in the same file, which I am more familiar with.
Reading about pool, I see it is meant to be used instead of server. You should use one or the other.
However, what happens if ntp.conf has both? Does one set take precedence over the other, or will all be used?
This is on Ubuntu 14.04, ntpd is version 4.2.6p5.
Answer: As far as I can see in the sources, ntpd handles both a member of a pool and individual servers roughly in the same way: it adds them to the list of peers.
All these peers are used by ntpd.
The magic of the pool mechanism is in round-robin DNS: as ntpd resolves the pool name through DNS, the response from the DNS query is a single node, which may be different every time resolution is asked.
Comment: This is mentioned in the file `discover.html` which I believe is bundled with ntpd documentation. See [the bottom](https://www.eecis.udel.edu/~mills/ntp/html/discover.html#pool) of the file
Comment: @Vincent  I downloaded source files. Can you point to exactly where I should look to verify this?
Comment: @mboehn In that doc and the file it references, I don't see any mention of what happens with newer versions of ntpd that support both pool and server directives when both are specified.  If I'm overlooking something, please enlighten. Thanks.
Comment: See ntp/ntp_config.c:3776. That's where the resolution of peers from the config file happens. After, look at ntp/ntp_peer.c:554 for peer_config and ntp/ntp_peer.c:730 for new_peer. You will see that both are eventually added to the peer hash table at the end of new_peer.
Comment: THis doesn't help someone who doesn't know what server does.  Can you explain what server does so that I can compare with your last sentence of what pool does.
Answer: The answer was given by mboehn. To clarify more: See the document he mentioned. Especially the last lines:

The pool scheme is configured using one or more pool commands with DNS
  names indicating the pool from which to draw. The pool command can be
  used more than once; duplicate servers are detected and discarded. In
  principle, it is possible to use a configuration file containing a
  single line pool pool.ntp.org. The NTP Pool Project offers
  instructions on using the pool with the server command, which is
  suboptimal but works with older versions of ntpd predating the pool
  command. With recent ntpd, consider replacing the multiple server
  commands in their example with a single pool command

My config is:
# Specify one or more NTP servers.
pool 0.pool.ntp.org iburst
pool 1.pool.ntp.org iburst
pool 2.pool.ntp.org iburst
pool 3.pool.ntp.org iburst

# Provide your current local time as a default should you temporarly lose Internet connectivity
server 127.127.1.0
fudge 127.127.1.0 stratum 10

I now have multiple ntp servers close to my geographic location (The Netherlands) when I check
$ ntpq -4np

     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 0.pool.ntp.org  .POOL.          16 p    -   64    0    0.000    0.000   0.000
 1.pool.ntp.org  .POOL.          16 p    -   64    0    0.000    0.000   0.000
 2.pool.ntp.org  .POOL.          16 p    -   64    0    0.000    0.000   0.000
 3.pool.ntp.org  .POOL.          16 p    -   64    0    0.000    0.000   0.000
 127.127.1.0     .LOCL.          10 l    -   64    0    0.000    0.000   0.000
-188.8.131.52   184.108.40.206   2 u    5   64  177    6.937    1.588   1.645
-184.108.40.206      22.214.171.124    3 u   64   64   77    8.907    1.197   1.635
-18.104.22.168   184.108.40.206    2 u    5   64  177    8.447   -0.042   0.894
+18.104.22.168    188.8.131.52    2 u    1   64  177    7.463    0.168   0.297
*188.8.131.52   126.96.36.199     2 u    2   64  177    8.593    0.070   0.384
+22.214.171.124    126.96.36.199      2 u    2   64  177   10.497    0.454   0.213
+22.214.171.124 126.96.36.199    2 u   67   64   77    8.793    0.455   2.391
#22.214.171.124   188.8.131.52    3 u   66   64   77    9.129   -0.911   1.541
#188.8.131.52 188.8.131.52    2 u   66   64   77   11.766   -7.330   1.501
+220.127.116.11  220.127.116.11    2 u    4   64  177    8.496    0.121   0.538
-18.104.22.168    220.127.116.11    2 u    2   64  177    7.026   -0.782   1.253
#18.104.22.168   18.104.22.168     3 u    4   64  177    7.338   -3.859   0.964
-18.104.22.168   18.104.22.168    2 u    -   64  177    8.347    2.797   1.019

Answer: In order for NTP to properly be soliciting a pool of timeservers, and make use of the availability of timeservers in any failover scenario, ntp.conf should be configured as such:

declare the pool's domain name with a pool command (and not server)
allow the pool to mobilize an association (i.e. add a "restrict source ..." line that does not include the nopeer directive)

ntp.conf pool vs server directives


Problem with the application of the pigeonhole principle.

Question: A football team plays at least one match per day in a month of $30$ days , but no more than $45$ matches in that month. Is it true that in some consecutive days in the month, the team will play exactly $14$ matches ?
Comment: Consider one of the possibilities: first 15 days -- 1 match each day, next 15 days -- 2 matches each day. So, there can be 14 consecutive days with exactly 14 matches.
Comment: Let $a_i$ - number of matches played on day $i$. Let $s_i=a_1+\cdots+a_i$.

$$1\le s_1j$ such that $s_i=s_j+14$.
Comment: Above comment summarizes N.F.Taussig's answer in a hint. It's not the first time I'm seeing this problem and it's probably the best way of solving it. No one upvoted his answer, so maybe it's a bit too lengthy for others and no one bothered to read it.
Answer: Let $a_k$ denote the number of football matches the team has played after $k$ days.  Since the team plays at least one match per day, the sequence $\{a_k\}$ is strictly increasing.  Moreover, since the team plays at most $45$ matches in the month of $30$ days, $a_{30} \leq 45$.  Consider the sequence defined by $b_k = a_k + 14$.  Then the sequence $\{b_k\}$ is also strictly increasing.  Moreover, $b_{30} \leq 45 + 14 = 59$.  Consider the union of the sequences $\{a_k\}$ and $\{b_k\}$.  It has $60$ terms, each of which is a positive integer which does not exceed $59$.  Hence, by the Pigeonhole Principle, there exist $i, j$, with $i > j$, such that $a_i = b_j = a_j + 14$, which means that there is a stretch of $i - j$ consecutive days in which the team plays exactly $14$ matches.


In a 4/4 instrumental, do I have to write stressed syllables to land on the beats of the bar so that my lyrics can be "in time"?

Question: In a 4/4 instrumental, do I have to write stressed syllables to land on the beats of the bar so that my lyrics can be "in time"? If not, how can I make my lyrics be "in time"? Please write as much of a technical answer as possible.
Comment: This is an unusual use of the phrase "in time". Could you add more description of what you're asking?
Comment: I mean that for example if I'm singing to a backtrack, other than singing on key, what do i need to do to reach a sense of belonging with the instrumental.
Comment: Instrumentals don't have words. Do you mean using a backing track to sing along to?
Comment: Yes, I do mean a backing track.
Answer: You don't have to. You should want to be aware of when the stressed syllables of the lyrics are lining up with the stressed beats and when they aren't.
When they don't line up, it can make the lyrics harder to understand and it can make the whole song sound awkward and amateurish. At the same time, when they don't line up, they can also make the moment stand out.
The overall topic of where the lyrics fall in the music and where the line breaks and stanzas are is called prosody and it's a very important aspect of songwriting.
If you're just learning to write songs, it's probably best to write so the stressed syllables in the lyrics line up with the stressed beats. If you write many songs like this to the point where it becomes part of your natural, instinctive process, then you'll have mastered an important skill of songwriting, and you'll find that working on prosody improves other aspects of your songwriting.


What is an acceptable R squared range for cross sectional data linear regressions?

Question: May I know an acceptable R squared range for a cross sectional data analysis using linear regression?
I think the requirement for this is lower than time series or panel data but would like to know even a rough idea on this.
For my straightforward question, is r squared of 0.16 or 0.17 acceptable under this condition?
Comment: You can edit comments for 5 minutes. I have been author, reviewer and journal editor. If my paper had a particular $R^2$ and a reviewer said "only such and such $R^2$ is publishable", I'd protest to the editor. If I commissioned a review and that was the comment, I would find another reviewer. No regression should ever be judged on $R^2$ alone. Is the result scientifically interesting and well-defended or practically useful in the present state of the field? These are some of the questions to be answered, not whether $R^2$ is big enough. That's a puerile criterion.
Comment: I don't think this question has a general answer outside of a precise context.
Comment: In many fields of physical science, $R^2 < 0.9$ would imply incompetence of researchers and/or a useless theory. In many other fields, $R^2 < 0.1$ might still be interesting depending on the state of the art in an otherwise intractable problem (e.g. as indicating possible agents or influences). So, I suggest that there are no useful general criteria. Literature in your own field should tell you what is publishable. Otherwise, what do you mean by acceptable? (Genuine question as well as an easy rhetorical device.)
Comment: For example, is 0.16 or 0.17 acceptable for this?
Comment: Acceptable for dependent variable prediction and my paper publication
Comment: The reviewers will tell you. Sorry, but it's like how much string do I need?
Comment: What about referring to the following source? http://users.wfu.edu/lawlor/Regression%20Basics.ppt

It says over 0.15 shows strong evidence

in case of cross sectional data

while time series data are like 0.8
Comment: If I have an R-squared value of 97% from my panel data but its Durbin-Watson test says no significant autocorrelation exists, shall I still assume this R-squared value of 97% to be still safe?
Answer: Sure. All too many people get really hung up on this issue. In an applied environment with technically illiterate or even semi-literate people, it's usually the first question any modeler gets, "What's the r-square?"
Back in the 80s, Don Morrison, a prominent marketing scientist, published an article discussing how r-squares (or pseudo-rsquares) approaching zero can still provide predictive lift. In addition, Herbert Gans, a Columbia sociologist, wrote a separate paper that classified r-squares by the type of data used as inputs.
Here is a summary of those insights and observations. Note that all results are almost entirely dependent on the type of information under analysis:

In direct marketing and/or CRM industries, r-squares in the low single digits can still provide predictive lift.
o One example of this is a logistic regression predicting the likelihood of an email campaign driving magazine subscriptions. By ranking and partitioning the potential recipients into deciles (or ventiles) and selecting the top loading buckets, the recipients most likely to subscribe can be targeted, minimizing campaign costs.
In cross-sectional modeling based on survey data, Gans felt that r-squares around 10%-20% were the norm. If the results are much higher than that, then there is a strong possibility that a regression assumption is being violated.
In business settings using, e.g., panel data models based on financial information, r-squares of 40%-60% are the norm.
In marketing science if you have product sales time series with a full set of "causal" factors -- e.g., price, promotion, distribution, marketing spend by store and/or markets -- then r-squares approaching 100% are not unusual since most of the variance is being explained.
Comment: Great! So I'm safe!
Comment: But if I have an R-squared value of 97% from my panel data but its Durbin-Watson test says no significant autocorrelation exists, shall I still assume this R-squared value of 97% to be still safe?


How to display a link field with its link text in a twig template

Question: A content type includes a link field link that accepts Link text.
A user inputs the URL /target with the Link text "Go to target".
How do I get twig to generate
   `<a href="/target">Go to target</a>`

I have tried what I've found by reading, including

{{ node.field_link }} (crashes)
{{ node.field_link|render }} (crashes)
{{ node.field_link.value }} (does nothing)
{{ node.field_link.0.url }} (displays /target but not as a link and ignores the link text)
{{ node.field_link.uri }} (displays internal:/target but not as a link and ignores the link text)

Seems like there must be a one-step way to accomplish this.
Comment: Doesn't twig just output this by default?
Answer: {{ node.field_link }} and {{ node.field_link|render } crashes because node.field_link of type FieldItemList not a rendered array.
Instead of using node variable use content variable like {{ content.field_link }} or even {{ content.field_link.0 }} it works.
Comment: Helped a lot! In my case that was link field in paragraphs, worked like: `paragraph.field_link.0.url|render`
Comment: Perfect. So simple, and yet I couldn't find it. Thanks!


JavaScript: onmouseout event not working after onmouseover

Question: I'm trying to write code for a ToolTip, where when the mouse goes over it the text shows, and when it moves away it goes away. I'm trying to do it by changing classes (tipHide in css has display:none, and tipShow has display: block), but the onmouseout event doesn't change the class back (which I know from seeing the generated source after).
How can I fix it so the onmouseout event will trigger if the onmouseover event already has changed the class.
My HTML:

Text Shown

and JavaScript:
function toolTip() {
    document.getElementById('qmark').onmouseover = function() {
        var toolTip = document.getElementById('toolTip');
        toolTip.className = 'tipShow';
    }
    document.getElementById('qmark').onmouseout = function() {
        var toolTip = document.getElementById('toolTip');
        toolTip.classname = 'tipHide';
    }
}

Also I'd like to do it without using JQuery
Comment: Apart from the typo, the function name might conflict with the `id` of the `p` element (in the case `tooltip` function is global).
Comment: Ok, thank you I'll fix that
Answer: Maybe a typo on the className property? In your onmouseout you got this:
toolTip.classname = 'tipHide';

Which should be(the same you did on onmouseover):
toolTip.className = 'tipHide';
             ^

Comment: Damn, you're right. I was so busy looking for the difficult answer I missed the obvious
Comment: @cfleming93 its fine, it happens all the time.


Number of Integer Composition with the number which is in a specific list

Question: Each positive integer n has 2^(n−1) distinct compositions. what If I want the number of composition which is only have specific number which is in my list:
for example composition of 4 is
4
3 1
1 3
2 2
2 1 1
1 2 1
1 1 2
1 1 1 1

but if I want the number of composition of 4 which it has only 1 and 2,
How could I calculate the NUMBER of distinct compositions?
2 2
2 1 1
1 2 1
1 1 2
1 1 1 1

Edited:
Here Haskell code which calculate the number, But I think It takes too long even IF I add memorization for Number 70
main :: IO ()
main = do
     putStrLn "Enter the integer number"
     num' <- getLine
     let num = read num' :: Int
     putStr ""
     let result= composition num
     let len=length result
     print len
      --print result

composition 0 = [[]]
composition n = [x:rest | x <- [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800,900,1000],x<=n ,rest <- composition (n-x)]

Comment: https://en.wikipedia.org/wiki/Partition_(number_theory)
Comment: @miku But in partitioning [1,2] and [2,1] are the same which is not what I want.
Comment: @17slim I already develop a haskell program which build all composition but I think it will take very long time to find a number.
Comment: @AmirAghajanzadehGheshlaghi Fair enough, retracted my close vote.
Answer: You can use dynamic programming to calculate the number of needed compositions.
Example of recursive relation for your example:
 P(4, [1,2]) = P(3, [1,2])  + P(2, [1,2])

here P(N, [list]) is the number of variants to make N from the list
Try to generalize formulas and use top-down memoization or bottom-up table filling DP to quickly find the result.
Delphi example:
var
  A: TArray<Integer>;
  Mem: TArray<Int64>;
  N, i: Integer;

  function Calc(N: Integer): Int64;
  var
    i: Integer;
  begin
    if Mem[N] >= 0 then
      Exit(Mem[N]);

    i := 0;
    Result := 0;
    while A[i] <= N do begin
      Result := Result + Calc(N - A[i]);
      Inc(i);
    end;
    Mem[N] := Result;
  end;

begin
  //should be sorted
  //-1 - sentinel value to stop
  A := TArray<Integer>.Create(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60,
    70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, -1);
  for N := 10 to 64 do begin
    SetLength(Mem, N + 1);
    for i := 1 to N do
      Mem[i] := -1; //not initialized yet
    Mem[0] := 1;
    Memo1.Lines.Add(Format('%d   %d', [N, Calc(N)]));
  end;

Comment: I already developed the software which can calculate the compositions but I think It's take too long because It has over 2^50 distinct composition.
Comment: I don't know Haskell and cannot see whether memoization is realized right . My Delphi program with memoization works a millisecond for your example list and all N values up to 64 (max value to avoid long arithmetics) giving for N=64 result `8978045929416305555`
Comment: Can you share your delphi sample?


Crash with UICollectionView and custom flow layout

Question: I've implemented sticky section headers for a collection view, using http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using as a jumping off point, and they work.
But I'm seeing a very weird crash.
When I push an editor detail view, change the item's name such that it moves from one section to another ( think, changing the last name of a person in a contacts list which is grouped by first letter of last name), and then pop back to the collection view it crashes with a complaint
UICollectionView received layout attributes for a cell with an index path that does not exist

Here's the flow of execution:
In the editor detail view, I change the item's name such that it will move from section X to section Y.
The item's model emits a "name changed" notification.
The root view controller which owns the collection view catches that "name changed" notification, rebuilds its internal indexes, and then calls -reloadData on the collection view. This is all good.
I hit the Back button in the UI, and the following flow happens ( confirmed via debugger and caveman NSlog calls )

numberOfSectionsInCollectionView: is called, and my code returns correct number of sections
collectionView:numberOfItemsInSection: is called for each section, and correct number of items is returned
my custom flow layout's -layoutAttributesForElementsInRect: is called. The first thing I do in there is call [super layoutAttributesForElementsInRect] to get a baseline layout.

Logging the the inherited baseline layout I see attributes for the previous arrangement of cells, not the current one. E.g., the layout is for the arrangement before the edits I just made. So, incorrect sections and or cells in incorrect sections.
Now here's what blows my mind.
If I comment out the entire implementation of -layoutAttributesForElementsInRect, it still crashes. But, if I comment out:
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound {
    return YES;
}

Then, it works correctly.
This tells me that the collection view, or something in flow layout is caching results, but only if the flow layout shouldInvalidateLayoutForBoundsChange
Note, if I just use a vanilla UICollectionViewFlowLayout everything works fine.
TLDR
Custom UICollectionViewFlowLayout, if -shouldInvalidateLayoutForBoundsChange returns YES, gets out-of-date layout attributes from [super layoutAttributesForElementsInRect]
Any ideas?
Comment: Did you figure this out? I think I'm having pretty much the exact same problem.
Comment: Make sure that you are storing layoutAttributes for each type of element against respective indexPath in separate dictionaries in prepareLayout method. Return the same layoutAttribute for respective index from respective element dictionaries.
Comment: I did "fix" it, but in a hacky manner. I ended up having my collection view note if it was /hidden/ when changes came in, and to defer a call to reload data in this situation to viewDidAppear:
Answer: I solved this by removing the shouldInvalidateLayoutForBoundsChange: override, and instead implementing scrollViewDidScroll: on the collection view's delegate to invalidate layout:
override func scrollViewDidScroll(scrollView: UIScrollView) {
    collectionView?.collectionViewLayout.invalidateLayout()
}

This keeps the sticky headers but stops the crashing.


new installation of windows 2008 R2 ... having permissions issues (everyone has access)

Question: I can not limit access to the IUSR user nor the IIS_IUSRS group at all....not even a different user that I tried for anonymous access.
When I say IUSR below, I also mean I've tried adding the group IIS_IUSRS with the same result.
Things I've tried:
1) Removing the anonymous access user from the NTFS permissions (security tab) in windows explorer - user can still browse anything in the folder.
2) specifically denying IUSR read access (this works but I can't do this on all of my sites) - user can't browse anything in the folder
3) changing the anonymous user to a local account and removing their permissions on the folder - user can still browse anything in the folder
4) changing the Application Pool user identity to a local account that does not have permission to the folder - user can still browse anything in the folder
5) allowing IUSR read access to the folder but specifically denying write access - user can still upload files to the folder.
6) setting the site to use Windows Authentication and giving IUSR read permission to the folder - prompts for a UN/PW combo...that won't work
7) setting the site to use Windows Authentication AND anonymous access and removing IUSR from the security tab - user can still browse anything in the folder.
I'm pulling my hair out here!!!!  I've checked and tried everything I can think of, but nothing seems to allow me to restrict access to anonymous users.
Answer: Try a virus scanner. The symptoms you're describing could be FunLove related.


nginx geoip redirect for first time only leads to redirect loop

Question: I'm trying to configure nginx to perform geoIP checks on first-time visitors only.
The idea is that first-time visitors should be redirected to the page version which has been customised for their language/country.
I'm able to check whether or not a certain cookie exists. If it does, then nginx can proceed and not redirect.
This set up means that all first-time visitors will be redirected to what it's likely to be the most appropriate version of the page for their country/language. And at the same time, those users that wish to, can still browse freely all versions available afterwards.
I believe Google recommends this type of set up for multilingual/multisite webpages too.
The problem is that I get a redirect loop if the rewrite directive is placed outside the root location. Yet, because the US version is the same as /root, rewrites within locations have proven even more difficult to configure.
The geo_IP values are passed OK via fastcgi to php if no rewrite is specified, so I don't think there is anything wrong with the setup apart from the rewrite itself.
This is my config:
map $geoip2_data_country_code $country_url {
  default example.com; ##This is the US version
  GB      example.com/uk;
  CA      example.com/ca;
}

server {
    listen 443 ssl spdy default_server;
    server_name example.com;
    root /var/www/html;

    if ($http_cookie !~ "cookie_to_check") {
       rewrite ^ https://$country_url break;
       #Appending $request_uri to the rewrite yields very similar results
    }

    location / {
    try_files $uri $uri/ /index.php?$args;
    }

    location /uk {
    try_files $uri $uri/ /uk/index.php?$args;
    }

    location /ca {
    try_files $uri $uri/ /ca/index.php?$args;
     }

##Other locations
}

Comment: I don't see where you set cookie
Comment: Use separate hostnames, not directories.
Comment: @MichaelHampton That was good to try but nginx doesn't seem to accept subfolders for a server_name. Nginx moans that there are suspicious characters (the forward slash), and although the server starts, the redirect has the same behaviour. I guess this makes sense as a subdirectory would be a location, not a server on its own
Comment: @AlexeyTen the cookie is set in the backend with the php application (magento) but thanks for pointing this out. As it turns out, nginx would get confused with the backend cookie. I'll post a full solution with nginx setting a cookie
Comment: With this nginx config your backend never get a change to set up cookie.
Answer: After a lot of trial and error, this is the configuration that would work and perform as expected.
The problem with my previous version was double:

Nginx rewrites outside locations were messy and they would just refuse to work by creating nasty loops
Nginx was checking the existence of a cookie which is set by a php application behind nginx. Thanks to @AlexeyTen for pointing this out. Setting an extra cookie conditionally with nginx did the trick
map $geoip2_data_country_code $country_url {
     default example.com; ##This is the US version
     GB      example.com/uk;
     CA      example.com/ca;
}

server {
    listen 443 ssl spdy default_server;
    server_name example.com;
    root /var/www/html;

    location / {
        try_files $uri $uri/ /index.php?$args;
        if ($http_cookie !~ "country=set") {
            add_header Set-Cookie "country=set;Max-Age=31536000";
            rewrite ^ $scheme://$country_url$request_uri break;
            }
    }

    location /uk {
        try_files $uri $uri/ /uk/index.php?$args;
        if ($http_cookie !~ "country=set") {
            add_header Set-Cookie "country=set;Max-Age=31536000";
            rewrite ^ $scheme://$country_url$request_uri break;
            }
    }

    location /ca {
        try_files $uri $uri/ /ca/index.php?$args;
        if ($http_cookie !~ "country=set") {
            add_header Set-Cookie "country=set;Max-Age=31536000";
            rewrite ^ $scheme://$country_url$request_uri break;
            }
    }

    ##Other locations
    }


Are blisters first time wearing soccer cleats normal, or does it mean bad shoes?

Question: I played soccer last saturday for the first time in a loooong time. We played for two hours. The day after, I couldn't walk because of my legs .... but my feet were fine. I played in regular sneakers.
This saturday we played again, and I had bought some soccer cleats for the first time in my life. I felt they were maybe slightly thight, but not overly much, and I was told that's how they are supposed to feel anyways.
Now, I have blisters on both feet, and I got them after already an hour of playing today.
Question:
Is this an indication of bad cleats/size and I should get new ones, or is this just how it is the first time you wear cleats and my feet just need time to get used to it?
Answer: Blisters on your feet can be caused by several reasons, but mostly they are caused by wearing the wrong shoe size or not wearing them in properly.
When buying new shoes they must not be too tight. They should fit well already in the store. Also if they're too big and your foot is slipping in them that's almost guaranteed a blister.
And before actually playing with them it is necessary to wear them in. It also helps to wear thicker socks to avoid blisters and with some materials it is easier to wear them in when they're wet (wet leather is softer and the shoe will fit easier).
Answer: Blisters happen when your shoes don't fit you well. You can get some Blister balm to heal your blister.
To prevent happening to them again:

Get yourself antiperspirants(not deodorants) and spray it on your
feet, let it dry and then wear your new shoe.
Before heading to the ground for playing, first wear your shoes in
the house and try to locate your trouble areas and wear paddings in
your feet where you fill discomfort.

Or you can purchase new shoes; you can go for Cowhide leather shoes if you want super protection, durability, and water resistant.
If you want high tensile strength and the ability to mold perfectly around your feet go for kangaroo leather.
Whatever shoes you buy, make sure they fit you properly and don't promote excessive sweating along the foot.
Answer: Since you haven't played in a "long" time, you're feet were probably not ready along with having new shoes. Some socks are very rough on the inside, so one strategy to prevent this from happening again is to wear two pairs of socks: one pair inside out and then another pair over them the normal way. It gets rid of the roughness and also may fill in any spaces between the shoe and your foot where it's not fitting well.


Unset fields as required for a Form

Question: In my drupal-based project, we make a difference between laptop users and tablet users: Laptop users can skip some fields when registering, whereas tablet users have to fill in all of them. The trick is easily done by hiding or showing those fields from the signup form with jQuery and Modernizr. And I say trick, because it works, despite some of those hidden fields being marked as required, they are still allowed to signup without filling on them.
The problem comes when users forget their password and request a link to create a new one.
When they get to the screen of "Enter new password and confirm it", users who have initially signed up via laptop (i.e., not filling on some of the required fields), cannot continue because they get the error "Fields X and Y cannot be left blank", or sth similar.
I want to disable these 2 fields from being required for Drupal (not from the signup form, where I have already "hidden" them), but I am not sure how to proceed. Where should I do this?
Answer: I would suggest, you use hook_form_alter() and then check for laptop users. If laptop users are on form then make #required false for these two fields.
Example:
$form['title']['#required'] = FALSE;

Note: FYI Avoid using unset() in such type of scenario either set the #access property or #required property to FALSE. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.
Comment: I am afraid I am a bit newbie for your answer... I would need something more like "go to this table in MySQL, search for X in field F and set 'required' to FALSE"... Either in the MySQL or in the Drupal admin panel. But I would definitely disable for all users.
Comment: @Jago first you look into https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7 and keep in mind never change in db directly there are number of options available to deal with such type of options. In your case you create custom module, create hook_form_alter and print the $form array and then do override respective fields as I suggested. You simply make field optional to avoid validation issue. Once you do all this stuff then share your code with us, if problem persists.
Comment: Ok, fair enough. Can you point me to some good example of usage of this? The module is already developed, I just need to locate where and how to use the function. So, can you provide a good example of usage? Thanks
Comment: I am adding to `hook_form_FORM_ID_alter()` the following: `$form['card_holder_name']['#required'] = FALSE;` but it does not seem to work. I always get the message that the field is still required...
Comment: I also tested this code at my end it works for me after clearing cache. I am sure it would also work for you, can you share your complete module code with me. And also confirm you are using correct form field name. If still you find issue with this, then please share your code I would fix this for you.

Unset fields as required for a Form


When i hit the space bar a dot comes up in search bar place?

Question: when the user search on the  search bar with blank space after entering some text then a dot is coming. For example when the user types:
Qq<spacebar><spacebar>

The result is:
Qq.

in the output we can see one dot. how its coming how we can remove the dot
Answer: This is a shortcut built into iOS. From Apple's iPhone 4 Tips and Tricks page:

Tap the space bar twice, and iPhone adds a period and capitalizes the next word.

See these two questions for potential solutions.
Answer: It's the standard behavior of the input fields in iPhone. You can modify this behavior in your settings under:

General ⇛ Keyboard ⇛ "." Shortcut ⇛ OFF

If you want to turn it off programmatically see @Chris' answer.


Calculando uma data dentro do Model Django timedelta

Question: Estou declarando uma função (data_prox_prog) para calcular uma data futura e armazenar no model, porém não está acontecendo o esperado.
Segue código:
class ProgressaoDocente(models.Model):
servidor = models.ForeignKey(Servidor, on_delete=models.PROTECT)
tipo_progressao = models.CharField(choices=const.TIPO_PROGRESSAO_DOC, max_length=1)
classe = models.CharField(choices=const.CLASSE_DOCENTE, max_length=1)
nivel = models.CharField(choices=const.NIVEL_DOCENTE, max_length=1)
data_progressao = models.DateField()
portaria = models.OneToOneField(Portaria, on_delete=models.CASCADE)
data_prox_progressao = models.DateField(blank=True, null=True)

class Meta:
    verbose_name_plural = 'Progressão Docente'

def data_prox_prog(self):
    self.data_prox_prog = (self.data_progressao + timedelta(year=2))
    self.save()

def __str__(self):
    return "{} {}, {}/{}".format(self.servidor, self.tipo_progressao, self.classe, self.nivel)

Comment: Será útil para ajudar se colocares detalhes do erro que aparece, ou o resultado esperado e o resultado actual. O código dentro de `ProgressaoDocente` não deveria estar indentado?
Answer: Consegui resolver utilizando pre-save do Django Signals.
O esperado é que quando se instancia uma nova 'ProgressaoDocente', a partir da 'data_progressao', se defina o valor da 'data_prox_progressao', contando mais 2 anos da 'data_progressao', segue solução:
class ProgressaoDocente(models.Model):
    servidor = models.ForeignKey(Servidor, on_delete=models.PROTECT)
    tipo_progressao = models.CharField(choices=const.TIPO_PROGRESSAO_DOC,
    max_length=1)
    classe = models.CharField(choices=const.CLASSE_DOCENTE, max_length=1)
    nivel = models.CharField(choices=const.NIVEL_DOCENTE, max_length=1)
    data_progressao = models.DateField()
    portaria = models.OneToOneField(Portaria, on_delete=models.CASCADE)
    data_prox_progressao = models.DateField(blank=True, null=True)

    class Meta:
        verbose_name_plural = 'Progressão Docente'

    def __str__(self):
        return "{} {}, {}/{}".format(self.servidor, self.tipo_progressao,
        self.classe, self.nivel)

@receiver(pre_save, sender=ProgressaoDocente)
def callback_progressao_docente(sender, instance, *args, **kwargs):
    instance.data_prox_progressao = (instance.data_progressao +
    relativedelta(years=+2))

Comment: Você pode também sobrescrever o método `save` e fazer essa atribuição antes de salvar. Usar signals (como o pre/post save) pode gerar algumas inconsitências no futuro (isso falando em casos onde a tendência do sistema seja crescer).


How can I make my vocals stand out without ducking the instrumental in my EDM drop?

Question: I'm pretty excited about my new EDM track, but first I better figure out how to make the vocal chops in my drop stop making the instrumental sounds duck (especially the melody synth). You can really hear this at 1:08 into the song when the vocals say "Soak me in the sun". If you have ever run into this same situation and want to have a listen, what is a simple way to fix this? I'm not opposed to modifying the relative volume of the vocals and instruments at different times, but the way the volumes work together at the moment just doesn't sound right.
P.S. I have reverb and light sidechaining with the Kickstart plugin on the vocals channel. I also EQ'd out the sub and some of the bass frequencies with a high pass filter on the vocals. I work in FL Studio.
Here is a link to the unreleased song on Soundcloud: https://soundcloud.com/gideon-grossman-253590505/do-whatever-makes-you-happy/s-BhZzBG9XI4F
I have tried fixing the issue by tweaking the Fruity Parametric EQ settings on my vocal channel and various instrument channels to no avail. I have also tested modifying the Kickstart wetness on my vocal channel. Maybe there is a sweet spot I haven't hit yet or I'm barking up the wrong tree.
Comment: It is considered bad form to cross-post the same question to multiple SE sites. Pick one & stick to it. You now have answers on both versions, so merging/migrating is no longer possible.
Answer: Yes, the instruments audibly duck at "Soak me in the sun".   This is what Kickstart does!  Either adjust its settings, or take the level of the vocals down a bit on that phrase.   They're obviously hitting a trigger level in Kickstart.


Using library project, "Sorry! The application... stopped unexpectedly"

Question: I'm having trouble using Eclipse ADT projects as libraries. I have three projects in eclipse: ToolProject, AppProject, DevProject.
The ToolProject contains classes I use in several apps (I actually have AppProject_2, as well, something completely different). In Properties, Android -> IsLibrary is ticked.
The AppProject contains the top-level app code, Activity, manifest, etc. It works – I can run it on my phone (IsLibrary ticked or unticked – both fine). Properties -> Android Library references ToolProject. The BuildPath does not reference ToolProject, in any tab.
The DevProject is so I can download and run the lastest draft on my phone, without clobbering the existing AppProject that's running there. I have created a new project, different launcher icon, different package. The Activity just subclasses AppProject's Activity.
I can't get DevProject to run on my phone. The console shows the normal messages. Logcat shows nothing for the launch. On the phone, I quickly get the "Sorry! The application DevProject (…) has stopped unexpectedly. Please try again." Nothing – no screen – from the app appears.
AppProject is marked as a library. I've tried DevProject with Library-reference to both AppProject and DevProject, and to just AppProject. Neither are in DevProject's BuildPath tabs.
Can someone tell me where to go and what to do there? I'm sorry for such a vague question, but I don't know what to tweak. Pointers to the relevant documentation or previous questions would be great.
Disclaimer: I have searched for discussions. I have read Android's Manifest documentation. But I remain unenlightened.
Comment: show me your error code please
Comment: Post your logcat error.
Comment: Grumble. There really was nothing in logcat. But... when I got your requests, I shut down eclipse, disconnected the phone, and brought it all up again. And ran it so I could post a screenshot of an empty logcat. Except... now logcat had stuff in it. I suppose somehow eclipse had lost it's connection to logcat. My apologies, and thanks for your time. [Grumble eclipse grumble.]
Answer: The app startup, in onCreate, used files from the assets/ folder. I had forgotten to copy these from AppProject to DevProject.
Problem solved.


Why is the cylinder surface on $\Bbb R^3$ orientable?

Question: Why is the cylinder surface on $\Bbb R^3$ orientable? Please can someone explain me clearly?
Comment: Intuitively, the outward pointing normal vector at a point will always point out as the point moves around the cylinder.  That is, we can specify two different 'sides' of the cylinder.  The same cannot be said of the Mobius band.  If you want a more mathematical explanation, you could write down an atlas, and show that the Jacobians of the transition functions have positive determinants.
Comment: How do I define the jacobian matrix? @jared
Answer: If the cylinder, $C$, is given by the equation $x^2+y^2=1$ in $\mathbb{R}^3$, we can give an atlas of $C$ by
$$\begin{array}{ccc}U_1=C\setminus\{x=-1\}&&U_2=C\setminus\{x=1\}\\\varphi_1:U_1\to (-\pi,\pi)\times\mathbb{R}&&\varphi_2:U_2\to (0,2\pi)\times\mathbb{R}\\(x,y,z)\mapsto(\theta,z)&& (x,y,z)\mapsto(\theta,z)\end{array}$$
where $\theta$ is the polar angle of the point $(x,y)\in\mathbb{R}^2$.  The transition functions are then given by:
$$\psi_{12}=\varphi_1\circ\varphi_2^{-1}:(0,\pi)\cup(\pi,2\pi)\times\mathbb{R}\to(-\pi,0)\cup(0,\pi)\times\mathbb{R}\\[.1in](\theta,z)\mapsto\begin{cases}(\theta,z)&0<\theta<\pi\\[.1in](\theta-2\pi,z)&\pi<\theta<2\pi\end{cases}\\[.4in]\psi_{21}=\varphi_2\circ\varphi_1^{-1}:(-\pi,0)\cup(0,\pi)\times\mathbb{R}\to(0,\pi)\cup(\pi,2\pi)\times\mathbb{R}\\[.1in](\theta,z)\mapsto\begin{cases}(\theta,z)&0<\theta<\pi\\[.1in](\theta+2\pi,z)&-\pi<\theta<0\end{cases}$$
At this point, it would be very helpful to draw some pictures of $U_1$, $U_2$, and the open subsets of $\mathbb{R}^2$ to which they are homeomorphic.  This will help you visualize the transition functions.
Now, we want to find the Jacobian of the transition functions.  If we write $\psi_{12}=(f_1,f_2)$, then the Jacobian is defined as follows:
$$\operatorname{Jac}(\psi_{12})=\begin{pmatrix}\frac{\partial f_1}{\partial\theta}&\frac{\partial f_1}{\partial z}\\\frac{\partial f_2}{\partial\theta}&\frac{\partial f_2}{\partial z}\end{pmatrix}$$
Looking at how we defined $\psi_{12}$, we see that
$$f_1(\theta,z)=\begin{cases}\theta&0<\theta<\pi\\\theta-2\pi&\pi<\theta<2\pi\end{cases}$$
and $f_2(\theta,z)=z$.  Taking partial derivatives of these functions gives the Jacobian
$$\operatorname{Jac}(\psi_{12})=\begin{pmatrix}\frac{\partial f_1}{\partial\theta}&\frac{\partial f_1}{\partial z}\\\frac{\partial f_2}{\partial\theta}&\frac{\partial f_2}{\partial z}\end{pmatrix}=\begin{pmatrix}1&0\\0&1\end{pmatrix}$$
You can also show this is the case for $\psi_{21}$.
Comment: Jared I haveunderstand but I what is these two jacobian matrix? Please can you write these two jacobian matrix clearly? And then I Will calculate the determinants of these two jacobian matrices, which show that C is orientable. But I need these two jacobian expression
Comment: By the way you explained very well:))
Comment: @B11: I've been more explicit.  I hope this helps.
Comment: Yes:))) of course:))) thank you so much for help:)
Comment: I have a question that how we can write transition function like that.I could not image in my mind.can you draw a picture please @Jared


Initialize form object properties based on url params?

Question: I did see some form classes which set form object properties in the buildForm() method.
However, these property values are no longer available in submitForm().
Simplified/incomplete example:
class MyForm {

  private $arg0;

  public function buildForm($form, $form_state, $nid) {
    $this->nid = $nid;
  }

  public function submitForm($form, $form_state) {
    $nid = $this->nid;  // $nid will be NULL.
  }
}

Actually there are some callbacks where these property values are available. E.g. if you register a #process => [[$this, 'process']] callback.
But it is not really surprising that the values are gone in some callbacks. ::buildForm() is not a constructor.
In some other form classes, they use $form_state->set($key, $value) to make data available to submitForm(). This works, but it somehow seems ugly.
Another way would be to store these values in the $form array as '#type' => 'value', or as #_my_data' => .... Again, I find this ugly.
Is there a more reliable way to initialize object properties on the form object based on url parameters? E.g. to have these parameters sent to the constructor?
Also, depending how I do this, do I need to worry that the data will be serialized?
(To me this seems like a flaw in the form API. But maybe I am missing something. I might open an issue on drupal.org, if the answer does not change my mind.)
Comment: $form_state->set('foo', 'bar'), $form_state->get('foo'). Possibly with $form_state->setRebuild() in case of ajax.
Answer: Yes, you can use form_state storage.
Object properties should work fine as well as long as you do not use private, use protected. private conflicts with the DependencySerializationTrait.
And yes, everything you store like that is serialized (unless it is a service, then that trait will remove and restore it) because that's the only way to transport this data across different requests.
Comment: The $form array, parts of $form_state including the form object, yes. Which can get somewhat confusing, because on a cached request, there will be two instances of the form object, the one that was created and the one that is unserialized. Specifically if you use a callback like array($this, 'method'), then the object is serialized like that and it will call the method on that. That's why it is recommended and easier to use '::method', which will call it on the new instance. That's not something we can do anything about, that's just how PHP works.
Comment: The reason I am not happy is lack of encapsulation (if stored in form_state or the form array), and lack of language-level invariants if stored in the form object - because buildForm() is not the constructor. It means the object properties would be in an incomplete state before the buildForm() method.
Comment: So if you say everything is serialized you mean the $form array, the $form_state object and the form object?
Answer: If you want to store parameters from the url the most reliable place for this is a form value. This is because the form gets built and rendered without that $form or $form_state is serialized and stored. And even if it would, the rendered form may be delivered later than 6 hours when the key_value storage has expired. You can store data in $form_state or in class properties of the form class under certain circumstances as @Berdir explained, but this depends on when and where you want to set and get the data.
So in general an example to store the parameter nid in the form would look like this:
public function buildForm(array $form, FormStateInterface $form_state, $nid) {

  $form['nid'] = [
    '#type' => 'hidden',
    '#value' => $nid,
  ];
  $form['#cache']['contexts'][] = 'url';

}

(I don't think this is a flaw, it's more about how html forms work)
Comment: type hidden and type value is very different. hidden should only be used for values that by design should be submitted/alterable by the browser, because they are. And type value and $form_state storage is technically being stored more or less in the same place, and $form_state storage is IMHO cleaner as it doesn't pollute the form structure (server side, it is not visible in the client)
Comment: @Berdir, a hidden form element is only alterable by the browser if you use `#default-value`. I also use $form_state if possible, but where are the values stored when the rendered form is cached?
Comment: Fair enough, if you use #value then it can't be overridden, but it is still visible on the client and sent to/from the client. Well, as mentioned, the form is only cached after the first ajax request, then it is stored in key_value, like the rest of the form definition/state. For the first POST request, it will actually just re-create the form objects and will call buildForm() again, which will set the object property or $form_state storage
Comment: @Berdir, yes, good summary of the time line. So you have to consider when the data is available to decide where you can store it.


When are angles negative?

Question: In earlier grades we learnt that in for instance an equilateral triangle all angles are 60 degrees. Now in high school I am taught that measuring angles anti-clockwise and clockwise make a difference.
So does that mean in an equilateral triangle one angle is 60 which is measures anti-clockwise and one is -60 degrees which is clockwise and.. I don't know, I am pretty confused.
How does it add to 180 then?
I was taught about this negative angle concept in trigonometry in unit circles which I understood very well but why is it if not applicable to any geometric figure?
It looks like I am lacking some common sense.
Comment: Generally, in geometric figures, we don't care about negative angles for the same reason that we don't care about negative sides.
Comment: As Silva said negative angles are not that useful in geometry, but they are widely used in trigonometry and complex algebra where they are expressed in radians
Comment: It's an [oriented angle](http://fr.wikipedia.org/wiki/Angle#Angles_orient.C3.A9s_dans_le_plan) not a geometric angle.
Comment: @user166748: Negative angles are used when one wants to distinguish clockwise and anticlockwise. That's all.
Comment: One question...so negative angles are only in trigonometry and complex numbers and no where else in mathematics ??
Comment: @Rahul: abstract sin and tan functions distinguish positive and negative angles, but there is no orientation, only maps from angles to reals.
Comment: @user166748 We give angles an orientation just as we give line segments an orientation to become vectors.
Answer: The following line segment on the number line has length four.
    ---------
0 1 2 3 4 5 6 7

The following arrow drawn on the number line represents a displacement of $-4$.
    <--------
0 1 2 3 4 5 6 7

The following arrow drawn on the number line represents a displacement of $4$.
    -------->
0 1 2 3 4 5 6 7

You can do the same thing with angles; sometimes you only care about the magnitude, but other times you pick an orientation: you decide which leg of the angle you start at and which leg you end at. When we orient angles, we typically pick counterclockwise to be the positive direction, and clockwise to be the negative direction.
Even more interesting is an idea of angular position versus angular displacement. If we consider an angle whose vertex is the origin and one leg (the starting leg) is the positive $x$ axis, then putting the other leg at $270^\circ$ would be the negative $y$ axis, but $-90^\circ$ would also be the negative $y$ axis.
The idea that $270^\circ$ and $-90^\circ$ represent the same angle is the idea of angular position.
However, there is a difference between actually going counterclockwise $270^\circ$ around the plane from the positive $x$ axis to the negative $y$ axis, and going $90^\circ$ clockwise (i.e. $-90^\circ$ counterclockwise) from the positive $x$ axis to the negative $y$ axis. When this difference matters, we call it "angular displacement". We could even consider going completely around the origin to return to the $x$ axis then continuing another three quarters the way around: this would be a displacement of $630^\circ$!

As an addendum, if we orient the two legs of the angle so that they point in opposite directions in relation to the vertex, then we usually consider the leg pointing away from the vertex to be the starting leg, and the leg pointing towards the vertex to be the ending leg.
This way, if we orient the three sides of a triangle so that the sides all point in a counter-clockwise direction around the triangle, then all of the angles are oriented counter-clockwise too.
Comment: @user166748 Is there another area of mathematics where angles are used? If there is, probably negative angles can be used there, too.
Comment: thanks for the answer..One question...so negative angles are only in trigonometry and complex numbers and no where else in mathematics ??
Answer: In plane geometry, 'negative angles' are used when defining angles of a pair of vectors; it's a measurement for the rotation which takes the first vector to the second – so that $ \mathrm{angle}(\vec u,\vec v)=-\mathrm{angle}(\vec v,\vec u)$. As an example in usual life, screwing is not the same as unscrewing.
The difference between geometric angles and 'algebraic' angles is similar to the difference betwen a segment and a vector.
Comment: You forgot to say these "positive" and "negative" angles make sense only for a plane (two dimensions) with orientation. In 3D angles between vectors are also vectors and haven't ordering on them.
Comment: so negative angles are only in vector algebra.. trigonometry and complex numbers and no where else in mathematics ??
Comment: @IncnisMrsi: You're right. Referring to plane geometry was implicit, but it's better to to say it explicitly.
Answer: Negative angle measurement don't exist. Sorry.
In a geometric figure like a triangle all angles have positive measurement.
So in a triangle our angles could have measures of $30^o, 60^o, 90^o$ or $\pi/6, \pi/3, \pi/2$ if you like. These are measurements of physical angles which are never negative.
However the measurements are done in degrees or radians which is a numerical system and we can think about a number as $-60^o$ or $-\pi/6$. These are numbers plain and simple.
You probably saw "negative angles" in trignometry class when you were confusing them with negative numbers of angle measurements. Functions like $\sin \theta, \cos \theta, \tan \theta$, etc. are easy to define for $\theta$ between $0^o$ and $360^o$ but we can just as easily define them for any other measurement including numbers like $-60^o$ by realizing that on the unit circle going $-60^o$ (or $60^o$ clockwise) is the same as going $300^o$ counterclockwise.
Hope this helps!
Comment: This answer is bad because it claims that negative angle measurement doesn't exist when it clearly does (relative to a fixed position and axis). [This answer](http://math.stackexchange.com/a/1084431/203768) explains it better.
Comment: I wonder why so clueless answer defining *physical* angles in a (mathematical) triangle collected no less than 6 upvotes. It introduces some confusing terminology, but even after that contradicts itself: "In a geometric figure all angles have positive measurement" but "Functions like sinθ, cosθ, tanθ, etc. are easy to define for θ between 0° and 360° but we can just as easily define them for any other *measurement* including numbers like −60°".
Comment: Tip: Use `^\circ` to make a degree sign: ${}^\circ$.
Comment: thanks for the answer @Chinmay Nirkhe- One question...so negative angles are only in trigonometry and complex numbers and no where else in mathematics ??
Comment: Think about a sum of vectors from tail to head adding to zero, robot arms travelling in the correct direction to the desired angle, etc.  You extract the abs value magnitude from the result when you need it.  See Geometric Algebra.  Unnecessary left/right handed, counterclock/clockwise conventions end up getting introduced when ambiguity is created by throwing away information.
Answer: Angles are not negative, however in trigonometry we easily talk about them anyway. The thing we use to make sense of them is modular arithmetic.
Modular arithmetic arranges the numbers in a clock or cycle, for example modular 3 we count $0,1,2,0,1,2,0,1,\dots$. We simply only have $3$ integers, and if we reach $3$ we simply go back to $0$. We therefore say that $3$ modulu $3$ is $0$, which is written as $3\equiv0\pmod{3}$
When using modular numbers, we don't have negative numbers either, and if we go below zero, we end up at the top again, so $-1\equiv2\pmod{3}$
We have a rule here and that is, we can add or subtract the number we're doing the modulus to as many times we want, and it'll remain the same.

When using degrees, a full turn in a circle is $360^\circ$, and when we have performed a full turn in a circle, we're just back where we started. This is just like the modulus operation I talked about above, and we can use the modulus concept to explain how angles operate when going below $0^\circ$ or above $360^\circ$.
When working with degrees, we go back to zero at $360^\circ$, therefore in degrees it makes sense to say that degrees work using modulus $360^\circ$. If we understand angles this way, we can explain what a negative angle really is. Let's for example take $-90^\circ$, we can apply modular arithmetic, which allows us to add $360$ to any angle without changing it: $-90^\circ\equiv270^\circ\pmod{360^\circ}$ and if you draw those two angles on the unit circle, notice how the angles point at the same place.
All this also explains why going above $360^\circ$ allows you to go below again, namely $400^\circ\equiv40^\circ\pmod{360^\circ}$, and therefore the angle $40^\circ$ and $400^\circ$ is just the same thing.
When talking about radians, it's much the same, except a full turn is $2\pi$ instead of $360$, and therefore we have to work modulus $2\pi$ with radians.
Comment: I mean, saying something like *working with degrees, we're simply working modulus* [sic] *360* is a worthless way to explain, because evades definition of the full angle (a.k.a. 1 turn, or revolution) that is necessary to substantiate **why** should we operate modulo 360 making calculation in degrees and modulo 2π in radians.
Comment: @IncnisMrsi I have attempted to clarify my answer.
Comment: I retract my downvote in appreciation of cleanup, but do not think this modular arithmetic stuff addresses the question of signedness enough.
Answer: Angle is a measurement and can't be negative, and it is used to define a certain point on the trigonometric circle. In the trigonometric circle, counterclockwise rotation is denoted the positive sign and counterclockwise is denoted the negative sign. for example, moving 60 degrees in the positive direction is completely identical to moving 300 degrees in the negative direction, as they both define one point.
Note that the choice of + or - is completely arbitrary and makes no difference; what really matters is the absolute value of angular displacement.
Comment: There are several situations where 360°≠0, 540°≠180°, 450°≠90°, and so on.
Comment: @IncnisMrsi Right. Imagine a screw: from the top, it looks equal no matter if you rotate by 360° or 720°. But the depth of the screw is different.
Comment: @IncnisMrsi Of course. in this simple answer I am merely concerned with angular position, and the definition of negative angles.

When are angles negative?


Partial differentiation of a composite function

Question: This should be straightforward, but don't seem to be able to crack it. Take a function $f(x_1, x_2, x_3)$ and a function $g(x4, x5, x6)$. These two functions mapp from $R^3 \rightarrow R^1$. I am interested in the partial derivatives of the following combination $ h(x_1, x_2, x4, x5, x6) = f(x_1, x_2, g(x4, x5, x6))$, or in other words $\frac{\partial h}{\partial x_1}, \;\frac{\partial h}{\partial x_2}, \dots, \,\frac{\partial h}{\partial x_6}$.
I only have access to $f$, $\frac{\partial f}{\partial x_{1,2,3}}$, $g$ and $\frac{\partial g}{\partial x_{4,5,6}}$ (i.e, $f$ and $g$ and their respective partial derivatives).
This should be a straightforward application of the chain rule, but I can't really see how it would work, and would appreciate a step-by-step guidance at how one would go at this.
Comment: Have you tried doing a function like $F(x,y)=f(x,g(y))$, for $f\colon \Bbb R^2\to\Bbb R$ and $g\colon\Bbb R\to\Bbb R$?
Answer: It should be clear that
$$\frac{\partial h}{\partial x_1}=\frac{\partial f}{\partial x_1}\big(x_1,x_2,g(x_4,x_5,x_6)\big)$$
The same for the partial w.r.t. $x_2$.
Use the chain rule for $x_4$:
$$\frac{\partial }{\partial x_4}f\big(x_1,x_2,g(x_4,x_5,x_6)\big)=\frac{\partial g}{\partial x_4}\big(x_4,x_5,x_6\big) \frac{\partial f}{\partial x_3} \big(x_1,x_2,g(x_4,x_5,x_6)\big).$$
The same for $x_5$ and $x_6$.
AN EXAMPLE:
$$f(x_1,x_2,x_3)=x_1x_2x_3$$
$$g(x_4,x_5,x_6)=x_4+x_5+x_6$$
So we have
$$h(x_1,x_2,x_4,x_5,x_6):=f\big(x_1,x_2,g(x_4,x_5,x_6)\big)=x_1x_2(x_4+x_5+x_6)$$
Now we can see that
$$\begin{align}
 \frac{\partial }{\partial x_1} f &= x_2x_3 \\
 \frac{\partial }{\partial x_4} g &=  1\\
 \frac{\partial }{\partial x_1} h &= x_2(x_4+x_5+x_6) \\
 \frac{\partial }{\partial x_4} h &= x_1x_2
\end{align}$$
Using the first formula:
$$\frac{\partial h}{\partial x_1}=\frac{\partial f}{\partial x_1}\big(x_1,x_2,g(x_4,x_5,x_6)\big)=x_2g(x_4,x_5,x_6)=x_2(x_4+x_5+x_6),$$
which agrees.
Using the second formula:
$$\frac{\partial }{\partial x_4}f\big(x_1,x_2,g(x_4,x_5,x_6)\big)=\frac{\partial g}{\partial x_4}\big(x_4,x_5,x_6\big) \frac{\partial f}{\partial x_3} \big(x_1,x_2,g(x_4,x_5,x_6)\big)
=1 \cdot x_1x_2,$$
which also agrees.
Comment: It's not the same: in the LHS you haven't taken the derivative yet; in the RHS you have taken the derivative and are plugging in the values.  I will add a concrete example as soon as I can.
Comment: I corrected a typo: the original RHS of the second line had $x_4$ where $x_3$ belonged in one place.  I hope this helps make it clear.
Comment: Are you sure about the sedond term in the RHS of the second line? It's just the same as in the LHS


How can I access the text generated dynamically within  in selenium?

Question: [![enter image description here][1]][1]
I tried using xpath as below:
Webelement req=driver.findElement(by.xpath("//[@id="leftcolumn"]/table/tbody/tr/td[2]");
req.getText();
System.out.println(req.getText());

which shows error...due to the double quotes in "leftcolumn"
Can anyone provide a solution for this..
Comment: Provide the complete HTML code of the page, or link to it if it is public.
Answer: Use single quotes for the id value:
 Webelement req=driver.findElement(by.xpath("//[@id='leftcolumn']/table/tbody/tr/td[2]");

Comment: I tried using single quotes but it doesnt works,unable to find the xpath.
Comment: your code does not compile. Single quotes fix that. If you are not finding the expected elements you need to adjust your expression.
Comment: Can you suggest any other way to access the text generated within a td tag
Answer: Escape the quotes.
Webelement req=driver.findElement(by.xpath("//[@id=\"leftcolumn\"]/table/tbody/tr/td[2]");

Answer: I myself found the solution,i just found the td tag in the page and iterated the list.I used gettext() for fetching the text in between the td tag.


Stucked on changing shader albedo alpha smoothness

Question: I want to customize unity's standard shader, I have downloaded it's source code and just want to customize it, so that smoothness of albedo alpha property should change by x(for example 0.1f) per frame. Sorry if this is bad question, but I googled everything i could but found nothing. Thanks in advance.
Here is the image to make my question more clear, I want to change this value on every frame from shader script
Answer: It's called _Glossiness inside the standard shader. You can change it using this:
material.SetFloat("_Glossiness", .25f);
However, if you're using LWRP then it's more conveniently called _Smoothness
Comment: Thanks for your responce, but this is not what i need, this is c# way of changing that value but it is calculated by cpu, and I need efficiency, so I want to do same from shader script
Comment: In that case, you can download and modify the [built-in shaders](https://unity3d.com/get-unity/download/archive).
Comment: I have already downlaoded it, but i can't modify it properly, thats why i am posting this question
Answer: It is possible to do animations inside the shader if that's what you want, but keep in mind that a shader cannot remember any kind of information about the state of your model except what is going on at this exact frame. If you want that, you'll need to use Iggy's solution, by setting values from code.
You can however animate things using the current time, and potentially together with some math like sine waves for a pulsating effect. I wouldn't try to modify the standard shader if i were you though, that is a can of worms you do not want to open. In fact, Unity designed surface shaders for this exact purpose. A surface shader can be configured to do anything that the standard shader does, but with far less code.
If you go Create>Shader>Surface Shader, you get a good base. You can also find more information here and here. For readability i will not write down the code for all the parameters in my examples, but you can see in the template roughly how it works.
In your case, you can use the _Time variable to animate the glossiness. _Time is a 4d vector, where the x, y, z, and w values represent different speeds of time (t/20, t, t*2, t*3). For instance, you could do something like this:
void surf (Input IN, inout SurfaceOutput o) {
    // This will make the smoothness pulsate with time.
    o.Smoothness = sin(_Time.z);
}

If you really need an effect to start at a certain time, then you can define an offset timestamp and set it from code like in Iggy's answer. If you want the shader to only trigger once you set the stamp, you can use some kind of condition based on the value of the timestamp.
float _StartTime
void surf (Input IN, inout SurfaceOutput o) {
    // This will make the smoothness pulsate with time.
    // saturate() clamps the value between 0 and 1.

    if (_StartTime > 0)
        o.Smoothness = sin(saturate(_Time.y - _StartTime));
    else
        o.Smoothness = 0;
}

Comment: Thank you so much, this is what i needed


$\overline{x} \times \overline{a} = \overline{b}$ has a solution when $ \langle\overline{a},\overline{b} \rangle =0$

Question: I'm trying to solve this exercise:

Let $\overline{a} \neq \overline{0}$, $\overline{b}$ be two vectors of the Euclidean vector space $V_{3}$. Prove the equation $\overline{x} \times \overline{a} = \overline{b}$ has a solution when $ \langle\overline{a},\overline{b} \rangle =0$ and find if it's the only one.

It does not seem that hard, my approach is the following, but I seem to be missing something:
Let $B = \left \{ \overline{\epsilon_{1}}, \overline{\epsilon_{2}}, \overline{\epsilon_{3}} \right \}$ be a base of $V_{3} $
Then the vectors $\overline{a}$. $\overline{b}$ can be represented as:
$\overline{a} = a_{1}\overline{\epsilon_{1}} + a_{2}\overline{\epsilon_{2}} + a_{3}\overline{\epsilon_{3}} = \sum_{i=1}^{3}a_{i}\overline{\epsilon_{i}}$
$\overline{b} = \sum_{j=1}^{3}b_{j}\overline{\epsilon_{j}}$
I also analyze the vector $\overline{x}$ as follows:
$\overline{x} = x_{1}\overline\epsilon_{1} + x_{2}\overline\epsilon_{2} +x_{3}\overline\epsilon_{3}$
$\overline{x} \times \overline{a} = \overline{b}$
$(x_{2}a_{3} - x_{3}a_{2})\overline\epsilon_{1} + (x_{3}a_{1} -x_{1}a_{3})\overline\epsilon_{2} + (x_{1}a_{2} - x_{2}a_{1})\overline\epsilon_{3} = \sum_{j=1}^{3}b_{j}\overline\epsilon_{j}$
And I get:
$x_{2}a_{3} - x_{3}a_{2} = b_{1}$
$x_{3}a_{1} - x_{3}a_{3} = b_{2}$
$x_{1}a_{2} - x_{3}a_{1} = b_{3} $
I am aware that $\langle\overline{a},\overline{b} \rangle =0$ means that the two vectors at vertical with each other, but how to I proceed from here?
Comment: I think that is just notation to say $x$ is a vector.
Comment: If $b\ne 0$ then $a,b,a\times b$ form an orthogonal basis.  Since $(a\times b)\times a$ is orthogonal to both $a\times b$ and to $a$, it has to be a multiple of $b$.
Comment: What does $\overline{x}$ stand for?
Comment: @SujaanKunalan and what does $x$ then stand for? Cause then $\overline{x}x\overline{a} = \overline{b}$ looks   incomprehensible.
Comment: I think by $\overline x x \overline a$ you mean $\overline x \times \overline a$, that is, the cross-product.
Answer: We know that $\vec x \times \vec a = \vec b$ means that $\vec a \perp \vec b$
If the two vectors are not perpendicular then there are no solutions. The following system has no solutions:
$$\left\{ \begin{gathered}
  {a_3}{x_2} - {a_2}{x_3} = {b_1}  \\
  {a_1}{x_3} - {a_3}{x_1} = {b_2}  \\
  {a_2}{x_1} - {a_1}{x_3} = {b_3}  \\
\end{gathered}  \right.$$
We know that $\vec a\perp\vec b$ which means $a_1b_1+a_2b_2+a_3b_3=0$
we can solve for $b_3$ getting $b_3=-\dfrac{a_1b_1+a_2b_2}{a_3}$ and substitute into the previous system
$$\left\{ \begin{gathered}
  {a_3}{x_2} - {a_2}{x_3} = {b_1}  \\
  {a_1}{x_3} - {a_3}{x_1} = {b_2}  \\
  {a_2}{x_1} - {a_1}{x_3} = -\dfrac{a_1b_1+a_2b_2}{a_3}  \\
\end{gathered}  \right.$$
Solving the system we get:
$$\left\{ \begin{gathered}
  {x_1} = \frac{{{b_2}{b_3} - {a_1}{b_3}{x_3}}}{{{a_1}{b_1} + {a_2}{b_2}}}  \\
  {x_2} =  - \frac{{{b_1}{b_3} - {a_2}{b_3}{x_3}}}{{{a_1}{b_1} + {a_2}{b_2}}}  \\
  {x_3} = {x_3}  \\
\end{gathered}  \right.$$
Which shows that the solution is not unique
Comment: At the end do you mean $x_3 = x_2$?
Comment: And can you solve the system in a more detailed way, I'm not getting the same results you get.
Answer: $$
0 \cdot x_1+ a_3\cdot x_2 -a_2\cdot x_3=b_1\\
-a_3\cdot x_1+0\cdot x_2+a_1\cdot x_3=b_2\\
a_2 \cdot x_1 -a_1 \cdot x_2 + 0 \cdot x_3=b_3\\
$$
This is a system of linear equation. We are given that the vector a is nonzero. Without loss of generosity, let us assume that a_3 is nonzero.
Then by using Gaussian elimination, we get:
$$
\begin{array}{ccc|c}
  1 & 0 & -a_1/a_3 & -b_2/a_3 \\
  0 & 1 & -a_2/a_3 & b_1/a_3 \\
  0 & 0 & 0 & (a_1b_1+a_2b_2+a_3b_3)/a_3
 \end{array}
$$
From linear algebra, we know that this system only has solution iff
$$
a_1b_1+a_2b_2+a_3b_3=0
$$
which is equivalent to the dot product is zero.


Rails generator para nested resources

Question: estava pesquisando mas não encontrei nenhum generator para nested resources no Rails. Alguém saberia me dizer se conhece algum?
Comment: Você provavelmente não vai encontrar. Adicionar nested_attributes_for é uma linha só. Mais facil criar os dois models e fazer manualmente.
Comment: Entendo. Estava na verdade procurando um generator para o controlador, que já soubesse como gerar um que carrega o modelo pai e define as funções no escopo dele.
Comment: tu diz algo assim: `SomeModule::Class` ?
Comment: Não exatamente. Um generator do Rails...
Answer: Henrique, não existe gerador de nested resources, mas o Rails te facilita muito a fazer isso na mão.
Para o caso de Article has many Comments, você basicamente precisaria alterar:
a) Os models:
class Article < ActiveRecord::Base
  has_many :comments
end

class Article < ActiveRecord::Base
  belongs_to :article
end

b) As rotas:
resources :articles do
  resources :comments
end

c) E, finalmente, os controllers: (essa parte pode ser mais tricky)
comments_controller.rb
class CommentsController < ApplicationController
  def index
    @article = Article.find(params[:article_id])
    @comments = @article.comments
  end

  def new
    @article = Article.find(params[:article_id])
    @comment = @article.comments.build
  end

  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.build(params[:comment])
    if @comment.save
      flash[:notice] = "Successfully created comment."
      redirect_to article_url(@comment.article_id)
    else
      render :action => 'new'
    end
  end

  def edit
    @comment = Comment.find(params[:id])
  end

  def update
    @comment = Comment.find(params[:id])
    if @comment.update_attributes(params[:comment])
      flash[:notice] = "Successfully updated comment."
      redirect_to article_url(@comment.article_id)
    else
      render :action => 'edit'
    end
  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
    flash[:notice] = "Successfully destroyed comment."
    redirect_to article_url(@comment.article_id)
  end
end

articles_controller.rb
class ArticlesController < ApplicationController
  def index
    @articles = Article.find(:all)
  end

  def show
    @article = Article.find(params[:id])
    @comment = Comment.new(:article => @article)
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(params[:article])
    if @article.save
      flash[:notice] = "Successfully created article."
      redirect_to @article
    else
      render :action => 'new'
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update_attributes(params[:article])
      flash[:notice] = "Successfully updated article."
      redirect_to @article
    else
      render :action => 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    flash[:notice] = "Successfully destroyed article."
    redirect_to articles_url
  end
end

Seguindo o modelo ilustrado acima você não deveria ter problemas =)
Qualquer dúvida mais específica, você pode fazer uma nova pergunta!

Rails generator para nested resources


Remover itens de uma lista que estão em outra

Question: Eu tenho duas listas com valores, e quando tento pesquisar um item de uma em outra, para ver se existe, está retornando False mesmo se sabendo que o item existe na lista pesquisada.

proc = [1,2,3,4]
fat = [3,4,5,6]

for p in proc:
  if proc[0] not in fat:
    result.append(proc[0])

print(result)

[]

Estas listas estao vindo de SELECT em um banco de dados, e contém um campo de tabelas.
O que posso estar fazendo de errado?
Comment: Não sei se entendi, mas **se** vc quer os elementos de `proc` que não estão em `fat`, basta fazer `result = [ p for p in proc if p not in fat ]`. E se a ordem dos elementos não for importante, outra alternativa é `result = list(set(proc) - set(fat))` (já que um `set` é otimizado para não permitir duplicados, mas ele não garante a mesma ordem da lista original)
Comment: é isso mesmo, python, funcionou perfeitamente. eu estou acostumado a usar for pra percorrer a lista, não percebo que o python é perfeito nisso de manipular listas tuplas e dicionários.
Comment: veja se atende, rodei no ideone dessa forma https://ideone.com/0tMlhG
Answer: Pelo que entendi do seu enunciado, você está precisando encontrar os valores que são comuns às duas listas.
Se o que importar for o valor do elemento, sem levar em consideração a quantidade de ocorrências de cada elemento, podemos converter as duas listas para conjuntos, calcular a intersecção dos conjuntos e, em seguida, exibir o resultado em uma nova lista. Para isso podemos utilizar o seguinte algoritmo...
proc = [1, 2, 3, 4]
fat = [3, 4, 5, 6]
proc = set(proc)
fat = set(fat)

inter = list(proc & fat)
print(inter)

Veja o funcionamento do algoritmo no repl.it.
Agora, se você pretendo exibir os elementos em ordem crescente de valores, você pode ordenar os valores na saída. Para isso aplicamos a função sorted. Para isso basta utilizar o algoritmo...
proc = [1, 2, 3, 4]
fat = [3, 4, 5, 6]
proc = set(proc)
fat = set(fat)

inter = list(sorted(proc & fat))
print(inter)

Veja o funcionamento do algoritmo no repl.it.
Answer: Se a ideia (confirmada nos comentários) é ter os elementos de proc que não estão em fat, então uma opção é:
proc = [1, 2, 3, 4]
fat = [3, 4, 5, 6]

result = []
for p in proc:
  if p not in fat:
    result.append(p)

print(result) # [1, 2]

Ou seja, para cada elemento de proc, verifique se ele não está em fat (e se não estiver, adicione em result).
O erro do seu código é que você estava verificando proc[0] (o primeiro elemento de proc) em todas as iterações.

Outra alternativa para o código acima é usar uma list comprehension, bem mais sucinta e pythônica:
result = [ p for p in proc if p not in fat ]

Mas tem um detalhe aí. Para cada elemento de proc, temos que verificar se o mesmo está em fat. E o operador in tem complexidade linear: ele percorre fat desde o início, até encontrar o elemento (ou percorre a lista toda, no caso do elemento não existir nela). Ou seja, este algoritmo percorre várias e várias vezes a mesma lista (o que o torna um forte candidato a ser um Shlemiel the painter's algorithm).
Se a ordem dos elementos não é importante, e não há elementos duplicados (ou há, mas no resultado as duplicadas podem ser eliminadas), uma opção é usar set, que é uma estrutura otimizada para certas operações, como verificar se um elemento existe, entre outras.
Assim, a ideia é transformar cada lista em um set, subtraí-los (assim eu terei outro set contendo os elementos de um que não estão no outro), e no final transformo novamente em lista:
result = list(set(proc) - set(fat))

Lembrando novamente que:

um set não garante a ordem dos elementos, então a lista result não necessariamente terá os números na mesma ordem em que estavam na lista original (pode ser que sim, pode ser que não, então não conte com isso)
um set elimina valores duplicados, então se a lista proc for, por exemplo, [1, 2, 3, 4, 1], o resultado final será apenas [1, 2]

Mas se manter a ordem original dos elementos e/ou não eliminar valores duplicados forem requisitos do problema, aí não tem jeito, tem que fazer o for mesmo.

Apenas para comparar o desempenho de cada solução, fiz um pequeno teste com o módulo timeit:
import random
import timeit

# criar listas com mil números aleatórios
nums = range(10000) # números possíveis para as listas
proc = random.choices(nums, k=1000)
fat = random.choices(nums, k=1000)

n = 100 # rodar 100 vezes cada teste
r = 3 # repetir por 3 vezes (assim, repeat retorna uma lista com 3 tempos)
print(timeit.repeat("result = []\nfor p in proc:\n  if p not in fat:\n    result.append(p)", repeat=r, number=n, globals=globals()))
print(timeit.repeat('[ p for p in proc if p not in fat ]', repeat=r, number=n, globals=globals()))
print(timeit.repeat('list(set(proc) - set(fat))', repeat=r, number=n, globals=globals()))

Claro que os tempos podem variar conforme o hardware e outro fatores, e para listas pequenas - como as que você usou - a diferença será insignificante, mas no geral, usar set se mostrou bem mais rápido. Na minha máquina os tempos foram (em segundos):
[1.4215344, 1.4107937, 1.4132282999999997]
[1.4147277999999996, 1.4120507999999994, 1.3960000999999993]
[0.015077500000000299, 0.014714099999999064, 0.015252100000001434]

Ou seja, usar set foi, em geral, cerca de 100 vezes mais rápido. No Repl.it os resultados foram similares.


Member's of a college club! Counting!

Question:
Five college clubs each have $100$ members. Each pair of the clubs contains exactly $10$ members. Each intersection of three clubs contains $3$ members. Strict college rules prevent anyone from belonging to $4$ clubs at once. How many people are in the five clubs?

Is inclusion-exclusion method used for this problem? My attempt is:
$$500=100+100+100+100+100 - 10-10-10-10-10 + 3+3+3+3+3+3+3+3+3 - X$$
$X$ represents the people who are in five clubs? Is this right?
Answer: Yes, you want inclusion-exclusion, but you start with the $5 \times 100$ members.  Then how many pairs of clubs are there?  You have double counted the $10$ in each pair, so take them out.  Now the people in three clubs were counted three times in the first, then removed three times in the second, so put them back in.  How many sets of three clubs are there?
Answer: In one club, denote $A$, there are 100 member. You can use the inclusion-exclusion method or you can separate the members:
"The members who have four or five memberships"$=0$ , because of the "strict rules"
"The members in $A$ who have three memberships"$=3*$"number of intersections of three clubs containing $A$"
$$3*\binom42=18$$
"The members in $A$ who have precisely two membership"$=10*$"number of pairs containing $A$"$-$"members in three clubs":
$$10*\binom41-18=22$$
"The members who only have one membership in one club"$=100-$"members in two clubs"$-$"members in three clubs":
$$100-22-18=60$$
Now you can sum this up:
There are five clubs. Members with only one membership: $5*60=300$
Members with exactly two membership: $\frac12*\binom52*22=110$ , because you count each member two times
Members with exactly three membership: $\frac13*\binom53*18=60$ , because you count each member three times
The total sum: $300+110+60=470$

Member's of a college club! Counting!


nunjuncks not rendering because of Content-Security-Policy

Question: The error:
Uncaught Template render error: (result.html)
  EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src *".

The nginx config:
[..]
more_set_headers   "Content-Security-Policy:
                default-src * 'unsafe-eval' 'unsave-inline';
                script-src 'self' 'unsafe-inline' 'unsafe-eval' 'unsafe-inline' https://cdn.raygun.io https://cdn.segment.com https://platform.instagram.com https://www.google-analytics.com https://cdn.mxpnl.com https://maxcdn.bootstrapcdn.com;
                connect-src 'self'  https://api.raygun.io https://api.parse.com https://api.segment.io https://api.mixpanel.com;
                img-src 'self' data: https://*.amazonaws.com https://www.google-analytics.com https://*.akamaihd.net https://www.google.com https://*.licdn.com;
                style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://maxcdn.bootstrapcdn.com;
                font-src 'self' https://fonts.gstatic.com https://maxcdn.bootstrapcdn.com;
                frame-src https://instagram.com";
[..]

The issue:
It looks like the Content-Security-Policy set in nginx config is not applied. I checked the headers returned from the server and they are set properly (including unsafe-inline and unsafe-eval).
The question:
Help? or in more detail: What else do I have to do to make Chrome render my nunjuncks templates?
I am looking for a solution that works server side (no Chrome plugin).
Answer: I missed
<meta http-equiv="Content-Security-Policy" content="default-src *">

in the template, grrrr!


Making a dice game. Trying to get the loop to break as soon as one player reaches 100

Question: fairly new to c++. I'm to create a dice game that lets you set the number of sides to the die and the number of players. Everyone starts at 1 pt and the game ends as soon as someone hits 100 or more.
This is the code I have so far
int players = 5;
int playerPosition[players];
for(int i=0; i < players; i++)
{
    playerPosition[i] = 1;
}

for(int i = 0; i < players; i++)
{
    while(playerPosition[i] < 100)
    {
        int roll;
        for (int j = 0; j < players; j++)
        {
            roll = dieRoll(6);
            // dieRoll is a function I made to simulate a die roll
            playerPosition[j] += roll;
            cout << "Player " << j + 1 << " rolled a " << roll << " and is now in position " << playerPosition [j] << endl;

        }
    }

}

So at the moment, the output will print out each turn for each player fine. The problem is that it'll keep going until every player reaches >= 100. I have tried adding
if(playerPosition[i] >= 100)
{
   break;
}

In the for loop and in the while loop. They still don't work the way I want it to. Can you tell me what the problem may be?
Thanks.
Comment: Since you are fairly new to C++, know that you don't use arrays for such things. Use `std::vector` - it's the standard collection type of C++. Use arrays only when the particular need arises.
Answer: You should check whether the player exceeded a sum of 100 every time after his sum has increased:
int players = 5;
int playerPosition[players];
for(int i=0; i < players; i++)
{
    playerPosition[i] = 1;
}

while(true)
{
    int roll;
    for (int j = 0; j < players; j++)
    {
        roll = dieRoll(6);
        // dieRoll is a function I made to simulate a die roll
        playerPosition[j] += roll;
        cout << "Player " << j + 1 << " rolled a " << roll << " and is now in position " << playerPosition [j] << endl;

        if(playerPosition[j] >= 100)
        {
            return;
        }

    }
}

Answer: The problem is that you are rolling each player, one at a time, until they reach 100 points. You need to check if there is a player over 100 each time you roll the dice
One way you could do this would be to have a bool gameOver variable declared outside the outer for loop, with its value initially set to false. Every time you increment a players score, you can add the line
playerPosition[j] += roll;
gameOver = playerPosition[j] >= 100

Now, if you change your code to have the structure
while(!gameOver) {
for(int i = 0; i < players; i++) {

it should behave as intended. The full code thus becomes
int players = 5;
bool gameOver = false;
int playerPosition[players];
for(int i=0; i < players; i++)
{
    playerPosition[i] = 1;
}

while(!gameOver) {
for(int i = 0; i < players; i++) {
    int roll;

        roll = dieRoll(6);
        // dieRoll is a function I made to simulate a die roll
        playerPosition[j] += roll;
        gameOver = playerPosition[j] >= 100
       if (gameOver)
       {
          break;
       }
        cout << "Player " << j + 1 << " rolled a " << roll << " and is now in position " << playerPosition [j] << endl;

    }
}

}

Comment: I apologize. I tried out the suggestion you gave me. It actually still doesn't work correctly. It keeps running until player 5 reaches 100. So even if the other players are already at 100+, it'll keep going until player 5 reaches the goal.
Comment: Please see my edit, you need to break out of the for loop once one player reaches 100.